[FL-2627] Flipper applications: SDK, build and debug system (#1387)

* Added support for running applications from SD card (FAPs - Flipper Application Packages)
* Added plugin_dist target for fbt to build FAPs
* All apps of type FlipperAppType.EXTERNAL and FlipperAppType.PLUGIN are built as FAPs by default
* Updated VSCode configuration for new fbt features - re-deploy stock configuration to use them
* Added debugging support for FAPs with fbt debug & VSCode
* Added public firmware API with automated versioning

Co-authored-by: hedger <hedger@users.noreply.github.com>
Co-authored-by: SG <who.just.the.doctor@gmail.com>
Co-authored-by: あく <alleteam@gmail.com>
This commit is contained in:
SG
2022-09-15 02:11:38 +10:00
committed by Aleksandr Kutuzov
parent 0f6f9ad52e
commit b9a766d909
895 changed files with 8862 additions and 1465 deletions

View File

@@ -0,0 +1,20 @@
App(
appid="storage",
name="StorageSrv",
apptype=FlipperAppType.SERVICE,
entry_point="storage_srv",
cdefines=["SRV_STORAGE"],
requires=["storage_settings"],
provides=["storage_start"],
stack_size=3 * 1024,
order=120,
sdk_headers=["storage.h"],
)
App(
appid="storage_start",
apptype=FlipperAppType.STARTUP,
entry_point="storage_on_system_start",
requires=["storage"],
order=90,
)

View File

@@ -0,0 +1,38 @@
#include "filesystem_api_defines.h"
const char* filesystem_api_error_get_desc(FS_Error error_id) {
const char* result = "unknown error";
switch(error_id) {
case(FSE_OK):
result = "OK";
break;
case(FSE_NOT_READY):
result = "filesystem not ready";
break;
case(FSE_EXIST):
result = "file/dir already exist";
break;
case(FSE_NOT_EXIST):
result = "file/dir not exist";
break;
case(FSE_INVALID_PARAMETER):
result = "invalid parameter";
break;
case(FSE_DENIED):
result = "access denied";
break;
case(FSE_INVALID_NAME):
result = "invalid name/path";
break;
case(FSE_INTERNAL):
result = "internal error";
break;
case(FSE_NOT_IMPLEMENTED):
result = "function not implemented";
break;
case(FSE_ALREADY_OPEN):
result = "file is already open";
break;
}
return result;
}

View File

@@ -0,0 +1,60 @@
#pragma once
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/** Access mode flags */
typedef enum {
FSAM_READ = (1 << 0), /**< Read access */
FSAM_WRITE = (1 << 1), /**< Write access */
FSAM_READ_WRITE = FSAM_READ | FSAM_WRITE, /**< Read and write access */
} FS_AccessMode;
/** Open mode flags */
typedef enum {
FSOM_OPEN_EXISTING = 1, /**< Open file, fail if file doesn't exist */
FSOM_OPEN_ALWAYS = 2, /**< Open file. Create new file if not exist */
FSOM_OPEN_APPEND = 4, /**< Open file. Create new file if not exist. Set R/W pointer to EOF */
FSOM_CREATE_NEW = 8, /**< Creates a new file. Fails if the file is exist */
FSOM_CREATE_ALWAYS = 16, /**< Creates a new file. If file exist, truncate to zero size */
} FS_OpenMode;
/** API errors enumeration */
typedef enum {
FSE_OK, /**< No error */
FSE_NOT_READY, /**< FS not ready */
FSE_EXIST, /**< File/Dir alrady exist */
FSE_NOT_EXIST, /**< File/Dir does not exist */
FSE_INVALID_PARAMETER, /**< Invalid API parameter */
FSE_DENIED, /**< Access denied */
FSE_INVALID_NAME, /**< Invalid name/path */
FSE_INTERNAL, /**< Internal error */
FSE_NOT_IMPLEMENTED, /**< Functon not implemented */
FSE_ALREADY_OPEN, /**< File/Dir already opened */
} FS_Error;
/** FileInfo flags */
typedef enum {
FSF_DIRECTORY = (1 << 0), /**< Directory */
} FS_Flags;
/** Structure that hold file index and returned api errors */
typedef struct File File;
/** Structure that hold file info */
typedef struct {
uint8_t flags; /**< flags from FS_Flags enum */
uint64_t size; /**< file size */
} FileInfo;
/** Gets the error text from FS_Error
* @param error_id error id
* @return const char* error text
*/
const char* filesystem_api_error_get_desc(FS_Error error_id);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,189 @@
#pragma once
#include <furi.h>
#include "filesystem_api_defines.h"
#ifdef __cplusplus
extern "C" {
#endif
/** File type */
typedef enum {
FileTypeClosed, /**< Closed file */
FileTypeOpenDir, /**< Open dir */
FileTypeOpenFile, /**< Open file */
} FileType;
/** Structure that hold file index and returned api errors */
struct File {
uint32_t file_id; /**< File ID for internal references */
FileType type;
FS_Error error_id; /**< Standart API error from FS_Error enum */
int32_t internal_error_id; /**< Internal API error value */
void* storage;
};
/** File api structure
* @var FS_File_Api::open
* @brief Open file
* @param file pointer to file object, filled by api
* @param path path to file
* @param access_mode access mode from FS_AccessMode
* @param open_mode open mode from FS_OpenMode
* @return success flag
*
* @var FS_File_Api::close
* @brief Close file
* @param file pointer to file object
* @return success flag
*
* @var FS_File_Api::read
* @brief Read bytes from file to buffer
* @param file pointer to file object
* @param buff pointer to buffer for reading
* @param bytes_to_read how many bytes to read, must be smaller or equal to buffer size
* @return how many bytes actually has been read
*
* @var FS_File_Api::write
* @brief Write bytes from buffer to file
* @param file pointer to file object
* @param buff pointer to buffer for writing
* @param bytes_to_read how many bytes to write, must be smaller or equal to buffer size
* @return how many bytes actually has been written
*
* @var FS_File_Api::seek
* @brief Move r/w pointer
* @param file pointer to file object
* @param offset offset to move r/w pointer
* @param from_start set offset from start, or from current position
* @return success flag
*
* @var FS_File_Api::tell
* @brief Get r/w pointer position
* @param file pointer to file object
* @return current r/w pointer position
*
* @var FS_File_Api::truncate
* @brief Truncate file size to current r/w pointer position
* @param file pointer to file object
* @return success flag
*
* @var FS_File_Api::size
* @brief Fet file size
* @param file pointer to file object
* @return file size
*
* @var FS_File_Api::sync
* @brief Write file cache to storage
* @param file pointer to file object
* @return success flag
*
* @var FS_File_Api::eof
* @brief Checks that the r/w pointer is at the end of the file
* @param file pointer to file object
* @return end of file flag
*/
typedef struct {
bool (*const open)(
void* context,
File* file,
const char* path,
FS_AccessMode access_mode,
FS_OpenMode open_mode);
bool (*const close)(void* context, File* file);
uint16_t (*read)(void* context, File* file, void* buff, uint16_t bytes_to_read);
uint16_t (*write)(void* context, File* file, const void* buff, uint16_t bytes_to_write);
bool (*const seek)(void* context, File* file, uint32_t offset, bool from_start);
uint64_t (*tell)(void* context, File* file);
bool (*const truncate)(void* context, File* file);
uint64_t (*size)(void* context, File* file);
bool (*const sync)(void* context, File* file);
bool (*const eof)(void* context, File* file);
} FS_File_Api;
/** Dir api structure
* @var FS_Dir_Api::open
* @brief Open directory to get objects from
* @param file pointer to file object, filled by api
* @param path path to directory
* @return success flag
*
* @var FS_Dir_Api::close
* @brief Close directory
* @param file pointer to file object
* @return success flag
*
* @var FS_Dir_Api::read
* @brief Read next object info in directory
* @param file pointer to file object
* @param fileinfo pointer to read FileInfo, can be NULL
* @param name pointer to name buffer, can be NULL
* @param name_length name buffer length
* @return success flag (if next object not exist also returns false and set error_id to FSE_NOT_EXIST)
*
* @var FS_Dir_Api::rewind
* @brief Rewind to first object info in directory
* @param file pointer to file object
* @return success flag
*/
typedef struct {
bool (*const open)(void* context, File* file, const char* path);
bool (*const close)(void* context, File* file);
bool (*const read)(
void* context,
File* file,
FileInfo* fileinfo,
char* name,
uint16_t name_length);
bool (*const rewind)(void* context, File* file);
} FS_Dir_Api;
/** Common api structure
* @var FS_Common_Api::stat
* @brief Open directory to get objects from
* @param path path to file/directory
* @param fileinfo pointer to read FileInfo, can be NULL
* @param name pointer to name buffer, can be NULL
* @param name_length name buffer length
* @return FS_Error error info
*
* @var FS_Common_Api::remove
* @brief Remove file/directory from storage,
* directory must be empty,
* file/directory must not be opened,
* file/directory must not have FSF_READ_ONLY flag
* @param path path to file/directory
* @return FS_Error error info
*
* @var FS_Common_Api::mkdir
* @brief Create new directory
* @param path path to new directory
* @return FS_Error error info
*
* @var FS_Common_Api::fs_info
* @brief Get total and free space storage values
* @param fs_path path of fs
* @param total_space pointer to total space value
* @param free_space pointer to free space value
* @return FS_Error error info
*/
typedef struct {
FS_Error (*const stat)(void* context, const char* path, FileInfo* fileinfo);
FS_Error (*const remove)(void* context, const char* path);
FS_Error (*const mkdir)(void* context, const char* path);
FS_Error (*const fs_info)(
void* context,
const char* fs_path,
uint64_t* total_space,
uint64_t* free_space);
} FS_Common_Api;
/** Full filesystem api structure */
typedef struct {
const FS_File_Api file;
const FS_Dir_Api dir;
const FS_Common_Api common;
} FS_Api;
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,117 @@
#include "storage.h"
#include "storage_i.h"
#include "storage_message.h"
#include "storage_processing.h"
#include "storage/storage_glue.h"
#include "storages/storage_int.h"
#include "storages/storage_ext.h"
#define STORAGE_TICK 1000
#define ICON_SD_MOUNTED &I_SDcardMounted_11x8
#define ICON_SD_ERROR &I_SDcardFail_11x8
#define TAG RECORD_STORAGE
static void storage_app_sd_icon_draw_callback(Canvas* canvas, void* context) {
furi_assert(canvas);
furi_assert(context);
Storage* app = context;
// here we don't care about thread race when reading / writing status
switch(app->storage[ST_EXT].status) {
case StorageStatusNotReady:
break;
case StorageStatusOK:
canvas_draw_icon(canvas, 0, 0, ICON_SD_MOUNTED);
break;
default:
canvas_draw_icon(canvas, 0, 0, ICON_SD_ERROR);
break;
}
}
Storage* storage_app_alloc() {
Storage* app = malloc(sizeof(Storage));
app->message_queue = furi_message_queue_alloc(8, sizeof(StorageMessage));
app->pubsub = furi_pubsub_alloc();
for(uint8_t i = 0; i < STORAGE_COUNT; i++) {
storage_data_init(&app->storage[i]);
}
#ifndef FURI_RAM_EXEC
storage_int_init(&app->storage[ST_INT]);
#endif
storage_ext_init(&app->storage[ST_EXT]);
// sd icon gui
app->sd_gui.enabled = false;
app->sd_gui.view_port = view_port_alloc();
view_port_set_width(app->sd_gui.view_port, icon_get_width(ICON_SD_MOUNTED));
view_port_draw_callback_set(app->sd_gui.view_port, storage_app_sd_icon_draw_callback, app);
view_port_enabled_set(app->sd_gui.view_port, false);
Gui* gui = furi_record_open(RECORD_GUI);
gui_add_view_port(gui, app->sd_gui.view_port, GuiLayerStatusBarLeft);
furi_record_close(RECORD_GUI);
return app;
}
void storage_tick(Storage* app) {
for(uint8_t i = 0; i < STORAGE_COUNT; i++) {
StorageApi api = app->storage[i].api;
if(api.tick != NULL) {
api.tick(&app->storage[i]);
}
}
// storage not enabled but was enabled (sd card unmount)
if(app->storage[ST_EXT].status == StorageStatusNotReady && app->sd_gui.enabled == true) {
app->sd_gui.enabled = false;
view_port_enabled_set(app->sd_gui.view_port, false);
FURI_LOG_I(TAG, "SD card unmount");
StorageEvent event = {.type = StorageEventTypeCardUnmount};
furi_pubsub_publish(app->pubsub, &event);
}
// storage enabled (or in error state) but was not enabled (sd card mount)
if((app->storage[ST_EXT].status == StorageStatusOK ||
app->storage[ST_EXT].status == StorageStatusNotMounted ||
app->storage[ST_EXT].status == StorageStatusNoFS ||
app->storage[ST_EXT].status == StorageStatusNotAccessible ||
app->storage[ST_EXT].status == StorageStatusErrorInternal) &&
app->sd_gui.enabled == false) {
app->sd_gui.enabled = true;
view_port_enabled_set(app->sd_gui.view_port, true);
if(app->storage[ST_EXT].status == StorageStatusOK) {
FURI_LOG_I(TAG, "SD card mount");
StorageEvent event = {.type = StorageEventTypeCardMount};
furi_pubsub_publish(app->pubsub, &event);
} else {
FURI_LOG_I(TAG, "SD card mount error");
StorageEvent event = {.type = StorageEventTypeCardMountError};
furi_pubsub_publish(app->pubsub, &event);
}
}
}
int32_t storage_srv(void* p) {
UNUSED(p);
Storage* app = storage_app_alloc();
furi_record_create(RECORD_STORAGE, app);
StorageMessage message;
while(1) {
if(furi_message_queue_get(app->message_queue, &message, STORAGE_TICK) == FuriStatusOk) {
storage_process_message(app, &message);
} else {
storage_tick(app);
}
}
return 0;
}

View File

@@ -0,0 +1,358 @@
#pragma once
#include <stdint.h>
#include <m-string.h>
#include "filesystem_api_defines.h"
#include "storage_sd_api.h"
#ifdef __cplusplus
extern "C" {
#endif
#define STORAGE_INT_PATH_PREFIX "/int"
#define STORAGE_EXT_PATH_PREFIX "/ext"
#define STORAGE_ANY_PATH_PREFIX "/any"
#define INT_PATH(path) STORAGE_INT_PATH_PREFIX "/" path
#define EXT_PATH(path) STORAGE_EXT_PATH_PREFIX "/" path
#define ANY_PATH(path) STORAGE_ANY_PATH_PREFIX "/" path
#define RECORD_STORAGE "storage"
typedef struct Storage Storage;
/** Allocates and initializes a file descriptor
* @return File*
*/
File* storage_file_alloc(Storage* storage);
/** Frees the file descriptor. Closes the file if it was open.
*/
void storage_file_free(File* file);
typedef enum {
StorageEventTypeCardMount,
StorageEventTypeCardUnmount,
StorageEventTypeCardMountError,
StorageEventTypeFileClose,
StorageEventTypeDirClose,
} StorageEventType;
typedef struct {
StorageEventType type;
} StorageEvent;
/**
* Get storage pubsub.
* Storage will send StorageEvent messages.
* @param storage
* @return FuriPubSub*
*/
FuriPubSub* storage_get_pubsub(Storage* storage);
/******************* File Functions *******************/
/** Opens an existing file or create a new one.
* @param file pointer to file object.
* @param path path to file
* @param access_mode access mode from FS_AccessMode
* @param open_mode open mode from FS_OpenMode
* @return success flag. You need to close the file even if the open operation failed.
*/
bool storage_file_open(
File* file,
const char* path,
FS_AccessMode access_mode,
FS_OpenMode open_mode);
/** Close the file.
* @param file pointer to a file object, the file object will be freed.
* @return success flag
*/
bool storage_file_close(File* file);
/** Tells if the file is open
* @param file pointer to a file object
* @return bool true if file is open
*/
bool storage_file_is_open(File* file);
/** Tells if the file is a directory
* @param file pointer to a file object
* @return bool true if file is a directory
*/
bool storage_file_is_dir(File* file);
/** Reads bytes from a file into a buffer
* @param file pointer to file object.
* @param buff pointer to a buffer, for reading
* @param bytes_to_read how many bytes to read. Must be less than or equal to the size of the buffer.
* @return uint16_t how many bytes were actually read
*/
uint16_t storage_file_read(File* file, void* buff, uint16_t bytes_to_read);
/** Writes bytes from a buffer to a file
* @param file pointer to file object.
* @param buff pointer to buffer, for writing
* @param bytes_to_write how many bytes to write. Must be less than or equal to the size of the buffer.
* @return uint16_t how many bytes were actually written
*/
uint16_t storage_file_write(File* file, const void* buff, uint16_t bytes_to_write);
/** Moves the r/w pointer
* @param file pointer to file object.
* @param offset offset to move the r/w pointer
* @param from_start set an offset from the start or from the current position
* @return success flag
*/
bool storage_file_seek(File* file, uint32_t offset, bool from_start);
/** Gets the position of the r/w pointer
* @param file pointer to file object.
* @return uint64_t position of the r/w pointer
*/
uint64_t storage_file_tell(File* file);
/** Truncates the file size to the current position of the r/w pointer
* @param file pointer to file object.
* @return bool success flag
*/
bool storage_file_truncate(File* file);
/** Gets the size of the file
* @param file pointer to file object.
* @return uint64_t size of the file
*/
uint64_t storage_file_size(File* file);
/** Writes file cache to storage
* @param file pointer to file object.
* @return bool success flag
*/
bool storage_file_sync(File* file);
/** Checks that the r/w pointer is at the end of the file
* @param file pointer to file object.
* @return bool success flag
*/
bool storage_file_eof(File* file);
/**
* @brief Check that file exists
*
* @param storage
* @param path
* @return true if file exists
*/
bool storage_file_exists(Storage* storage, const char* path);
/******************* Dir Functions *******************/
/** Opens a directory to get objects from it
* @param app pointer to the api
* @param file pointer to file object.
* @param path path to directory
* @return bool success flag. You need to close the directory even if the open operation failed.
*/
bool storage_dir_open(File* file, const char* path);
/** Close the directory. Also free file handle structure and point it to the NULL.
* @param file pointer to a file object.
* @return bool success flag
*/
bool storage_dir_close(File* file);
/** Reads the next object in the directory
* @param file pointer to file object.
* @param fileinfo pointer to the read FileInfo, may be NULL
* @param name pointer to name buffer, may be NULL
* @param name_length name buffer length
* @return success flag (if the next object does not exist, it also returns false and sets the file error id to FSE_NOT_EXIST)
*/
bool storage_dir_read(File* file, FileInfo* fileinfo, char* name, uint16_t name_length);
/** Rewinds the read pointer to first item in the directory
* @param file pointer to file object.
* @return bool success flag
*/
bool storage_dir_rewind(File* file);
/******************* Common Functions *******************/
/** Retrieves information about a file/directory
* @param app pointer to the api
* @param path path to file/directory
* @param fileinfo pointer to the read FileInfo, may be NULL
* @return FS_Error operation result
*/
FS_Error storage_common_stat(Storage* storage, const char* path, FileInfo* fileinfo);
/** Removes a file/directory from the repository, the directory must be empty and the file/directory must not be open
* @param app pointer to the api
* @param path
* @return FS_Error operation result
*/
FS_Error storage_common_remove(Storage* storage, const char* path);
/** Renames file/directory, file/directory must not be open
* @param app pointer to the api
* @param old_path old path
* @param new_path new path
* @return FS_Error operation result
*/
FS_Error storage_common_rename(Storage* storage, const char* old_path, const char* new_path);
/** Copy file, file must not be open
* @param app pointer to the api
* @param old_path old path
* @param new_path new path
* @return FS_Error operation result
*/
FS_Error storage_common_copy(Storage* storage, const char* old_path, const char* new_path);
/** Copy one folder contents into another with rename of all conflicting files
* @param app pointer to the api
* @param old_path old path
* @param new_path new path
* @return FS_Error operation result
*/
FS_Error storage_common_merge(Storage* storage, const char* old_path, const char* new_path);
/** Creates a directory
* @param app pointer to the api
* @param path directory path
* @return FS_Error operation result
*/
FS_Error storage_common_mkdir(Storage* storage, const char* path);
/** Gets general information about the storage
* @param app pointer to the api
* @param fs_path the path to the storage of interest
* @param total_space pointer to total space record, will be filled
* @param free_space pointer to free space record, will be filled
* @return FS_Error operation result
*/
FS_Error storage_common_fs_info(
Storage* storage,
const char* fs_path,
uint64_t* total_space,
uint64_t* free_space);
/******************* Error Functions *******************/
/** Retrieves the error text from the error id
* @param error_id error id
* @return const char* error text
*/
const char* storage_error_get_desc(FS_Error error_id);
/** Retrieves the error id from the file object
* @param file pointer to file object. Pointer must not point to NULL. YOU CANNOT RETREIVE THE ERROR ID IF THE FILE HAS BEEN CLOSED
* @return FS_Error error id
*/
FS_Error storage_file_get_error(File* file);
/** Retrieves the internal (storage-specific) error id from the file object
* @param file pointer to file object. Pointer must not point to NULL. YOU CANNOT RETREIVE THE INTERNAL ERROR ID IF THE FILE HAS BEEN CLOSED
* @return FS_Error error id
*/
int32_t storage_file_get_internal_error(File* file);
/** Retrieves the error text from the file object
* @param file pointer to file object. Pointer must not point to NULL. YOU CANNOT RETREIVE THE ERROR TEXT IF THE FILE HAS BEEN CLOSED
* @return const char* error text
*/
const char* storage_file_get_error_desc(File* file);
/******************* SD Card Functions *******************/
/** Formats SD Card
* @param api pointer to the api
* @return FS_Error operation result
*/
FS_Error storage_sd_format(Storage* api);
/** Will unmount the SD card
* @param api pointer to the api
* @return FS_Error operation result
*/
FS_Error storage_sd_unmount(Storage* api);
/** Retrieves SD card information
* @param api pointer to the api
* @param info pointer to the info
* @return FS_Error operation result
*/
FS_Error storage_sd_info(Storage* api, SDInfo* info);
/** Retrieves SD card status
* @param api pointer to the api
* @return FS_Error operation result
*/
FS_Error storage_sd_status(Storage* api);
/******************* Internal LFS Functions *******************/
typedef void (*Storage_name_converter)(string_t);
/** Backs up internal storage to a tar archive
* @param api pointer to the api
* @param dstmane destination archive path
* @return FS_Error operation result
*/
FS_Error storage_int_backup(Storage* api, const char* dstname);
/** Restores internal storage from a tar archive
* @param api pointer to the api
* @param dstmane archive path
* @param converter pointer to filename conversion function, may be NULL
* @return FS_Error operation result
*/
FS_Error storage_int_restore(Storage* api, const char* dstname, Storage_name_converter converter);
/***************** Simplified Functions ******************/
/**
* Removes a file/directory, the directory must be empty and the file/directory must not be open
* @param storage pointer to the api
* @param path
* @return true on success or if file/dir is not exist
*/
bool storage_simply_remove(Storage* storage, const char* path);
/**
* Recursively removes a file/directory, the directory can be not empty
* @param storage pointer to the api
* @param path
* @return true on success or if file/dir is not exist
*/
bool storage_simply_remove_recursive(Storage* storage, const char* path);
/**
* Creates a directory
* @param storage
* @param path
* @return true on success or if directory is already exist
*/
bool storage_simply_mkdir(Storage* storage, const char* path);
/**
* @brief Get next free filename.
*
* @param storage
* @param dirname
* @param filename
* @param fileextension
* @param nextfilename return name
* @param max_len max len name
*/
void storage_get_next_filename(
Storage* storage,
const char* dirname,
const char* filename,
const char* fileextension,
string_t nextfilename,
uint8_t max_len);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,609 @@
#include <furi.h>
#include <furi_hal.h>
#include <cli/cli.h>
#include <lib/toolbox/args.h>
#include <lib/toolbox/md5.h>
#include <lib/toolbox/dir_walk.h>
#include <storage/storage.h>
#include <storage/storage_sd_api.h>
#include <power/power_service/power.h>
#define MAX_NAME_LENGTH 255
static void storage_cli_print_usage() {
printf("Usage:\r\n");
printf("storage <cmd> <path> <args>\r\n");
printf("The path must start with /int or /ext\r\n");
printf("Cmd list:\r\n");
printf("\tinfo\t - get FS info\r\n");
printf("\tformat\t - format filesystem\r\n");
printf("\tlist\t - list files and dirs\r\n");
printf("\ttree\t - list files and dirs, recursive\r\n");
printf("\tremove\t - delete the file or directory\r\n");
printf("\tread\t - read text from file and print file size and content to cli\r\n");
printf(
"\tread_chunks\t - read data from file and print file size and content to cli, <args> should contain how many bytes you want to read in block\r\n");
printf("\twrite\t - read text from cli and append it to file, stops by ctrl+c\r\n");
printf(
"\twrite_chunk\t - read data from cli and append it to file, <args> should contain how many bytes you want to write\r\n");
printf("\tcopy\t - copy file to new file, <args> must contain new path\r\n");
printf("\trename\t - move file to new file, <args> must contain new path\r\n");
printf("\tmkdir\t - creates a new directory\r\n");
printf("\tmd5\t - md5 hash of the file\r\n");
printf("\tstat\t - info about file or dir\r\n");
};
static void storage_cli_print_error(FS_Error error) {
printf("Storage error: %s\r\n", storage_error_get_desc(error));
}
static void storage_cli_info(Cli* cli, string_t path) {
UNUSED(cli);
Storage* api = furi_record_open(RECORD_STORAGE);
if(string_cmp_str(path, STORAGE_INT_PATH_PREFIX) == 0) {
uint64_t total_space;
uint64_t free_space;
FS_Error error =
storage_common_fs_info(api, STORAGE_INT_PATH_PREFIX, &total_space, &free_space);
if(error != FSE_OK) {
storage_cli_print_error(error);
} else {
printf(
"Label: %s\r\nType: LittleFS\r\n%luKB total\r\n%luKB free\r\n",
furi_hal_version_get_name_ptr() ? furi_hal_version_get_name_ptr() : "Unknown",
(uint32_t)(total_space / 1024),
(uint32_t)(free_space / 1024));
}
} else if(string_cmp_str(path, STORAGE_EXT_PATH_PREFIX) == 0) {
SDInfo sd_info;
FS_Error error = storage_sd_info(api, &sd_info);
if(error != FSE_OK) {
storage_cli_print_error(error);
} else {
printf(
"Label: %s\r\nType: %s\r\n%luKB total\r\n%luKB free\r\n",
sd_info.label,
sd_api_get_fs_type_text(sd_info.fs_type),
sd_info.kb_total,
sd_info.kb_free);
}
} else {
storage_cli_print_usage();
}
furi_record_close(RECORD_STORAGE);
};
static void storage_cli_format(Cli* cli, string_t path) {
if(string_cmp_str(path, STORAGE_INT_PATH_PREFIX) == 0) {
storage_cli_print_error(FSE_NOT_IMPLEMENTED);
} else if(string_cmp_str(path, STORAGE_EXT_PATH_PREFIX) == 0) {
printf("Formatting SD card, All data will be lost! Are you sure (y/n)?\r\n");
char answer = cli_getc(cli);
if(answer == 'y' || answer == 'Y') {
Storage* api = furi_record_open(RECORD_STORAGE);
printf("Formatting, please wait...\r\n");
FS_Error error = storage_sd_format(api);
if(error != FSE_OK) {
storage_cli_print_error(error);
} else {
printf("SD card was successfully formatted.\r\n");
}
furi_record_close(RECORD_STORAGE);
} else {
printf("Cancelled.\r\n");
}
} else {
storage_cli_print_usage();
}
};
static void storage_cli_list(Cli* cli, string_t path) {
UNUSED(cli);
if(string_cmp_str(path, "/") == 0) {
printf("\t[D] int\r\n");
printf("\t[D] ext\r\n");
printf("\t[D] any\r\n");
} else {
Storage* api = furi_record_open(RECORD_STORAGE);
File* file = storage_file_alloc(api);
if(storage_dir_open(file, string_get_cstr(path))) {
FileInfo fileinfo;
char name[MAX_NAME_LENGTH];
bool read_done = false;
while(storage_dir_read(file, &fileinfo, name, MAX_NAME_LENGTH)) {
read_done = true;
if(fileinfo.flags & FSF_DIRECTORY) {
printf("\t[D] %s\r\n", name);
} else {
printf("\t[F] %s %lub\r\n", name, (uint32_t)(fileinfo.size));
}
}
if(!read_done) {
printf("\tEmpty\r\n");
}
} else {
storage_cli_print_error(storage_file_get_error(file));
}
storage_dir_close(file);
storage_file_free(file);
furi_record_close(RECORD_STORAGE);
}
}
static void storage_cli_tree(Cli* cli, string_t path) {
if(string_cmp_str(path, "/") == 0) {
string_set(path, STORAGE_INT_PATH_PREFIX);
storage_cli_tree(cli, path);
string_set(path, STORAGE_EXT_PATH_PREFIX);
storage_cli_tree(cli, path);
} else {
Storage* api = furi_record_open(RECORD_STORAGE);
DirWalk* dir_walk = dir_walk_alloc(api);
string_t name;
string_init(name);
if(dir_walk_open(dir_walk, string_get_cstr(path))) {
FileInfo fileinfo;
bool read_done = false;
while(dir_walk_read(dir_walk, name, &fileinfo) == DirWalkOK) {
read_done = true;
if(fileinfo.flags & FSF_DIRECTORY) {
printf("\t[D] %s\r\n", string_get_cstr(name));
} else {
printf("\t[F] %s %lub\r\n", string_get_cstr(name), (uint32_t)(fileinfo.size));
}
}
if(!read_done) {
printf("\tEmpty\r\n");
}
} else {
storage_cli_print_error(dir_walk_get_error(dir_walk));
}
string_clear(name);
dir_walk_free(dir_walk);
furi_record_close(RECORD_STORAGE);
}
}
static void storage_cli_read(Cli* cli, string_t path) {
UNUSED(cli);
Storage* api = furi_record_open(RECORD_STORAGE);
File* file = storage_file_alloc(api);
if(storage_file_open(file, string_get_cstr(path), FSAM_READ, FSOM_OPEN_EXISTING)) {
const uint16_t buffer_size = 128;
uint16_t read_size = 0;
uint8_t* data = malloc(buffer_size);
printf("Size: %lu\r\n", (uint32_t)storage_file_size(file));
do {
read_size = storage_file_read(file, data, buffer_size);
for(uint16_t i = 0; i < read_size; i++) {
printf("%c", data[i]);
}
} while(read_size > 0);
printf("\r\n");
free(data);
} else {
storage_cli_print_error(storage_file_get_error(file));
}
storage_file_close(file);
storage_file_free(file);
furi_record_close(RECORD_STORAGE);
}
static void storage_cli_write(Cli* cli, string_t path) {
Storage* api = furi_record_open(RECORD_STORAGE);
File* file = storage_file_alloc(api);
const uint16_t buffer_size = 512;
uint8_t* buffer = malloc(buffer_size);
if(storage_file_open(file, string_get_cstr(path), FSAM_WRITE, FSOM_OPEN_APPEND)) {
printf("Just write your text data. New line by Ctrl+Enter, exit by Ctrl+C.\r\n");
uint32_t read_index = 0;
while(true) {
uint8_t symbol = cli_getc(cli);
if(symbol == CliSymbolAsciiETX) {
uint16_t write_size = read_index % buffer_size;
if(write_size > 0) {
uint16_t written_size = storage_file_write(file, buffer, write_size);
if(written_size != write_size) {
storage_cli_print_error(storage_file_get_error(file));
}
break;
}
}
buffer[read_index % buffer_size] = symbol;
printf("%c", buffer[read_index % buffer_size]);
fflush(stdout);
read_index++;
if(((read_index % buffer_size) == 0)) {
uint16_t written_size = storage_file_write(file, buffer, buffer_size);
if(written_size != buffer_size) {
storage_cli_print_error(storage_file_get_error(file));
break;
}
}
}
printf("\r\n");
} else {
storage_cli_print_error(storage_file_get_error(file));
}
storage_file_close(file);
free(buffer);
storage_file_free(file);
furi_record_close(RECORD_STORAGE);
}
static void storage_cli_read_chunks(Cli* cli, string_t path, string_t args) {
Storage* api = furi_record_open(RECORD_STORAGE);
File* file = storage_file_alloc(api);
uint32_t buffer_size;
int parsed_count = sscanf(string_get_cstr(args), "%lu", &buffer_size);
if(parsed_count == EOF || parsed_count != 1) {
storage_cli_print_usage();
} else if(storage_file_open(file, string_get_cstr(path), FSAM_READ, FSOM_OPEN_EXISTING)) {
uint64_t file_size = storage_file_size(file);
printf("Size: %lu\r\n", (uint32_t)file_size);
if(buffer_size) {
uint8_t* data = malloc(buffer_size);
while(file_size > 0) {
printf("\r\nReady?\r\n");
cli_getc(cli);
uint16_t read_size = storage_file_read(file, data, buffer_size);
for(uint16_t i = 0; i < read_size; i++) {
putchar(data[i]);
}
file_size -= read_size;
}
free(data);
}
printf("\r\n");
} else {
storage_cli_print_error(storage_file_get_error(file));
}
storage_file_close(file);
storage_file_free(file);
furi_record_close(RECORD_STORAGE);
}
static void storage_cli_write_chunk(Cli* cli, string_t path, string_t args) {
Storage* api = furi_record_open(RECORD_STORAGE);
File* file = storage_file_alloc(api);
uint32_t buffer_size;
int parsed_count = sscanf(string_get_cstr(args), "%lu", &buffer_size);
if(parsed_count == EOF || parsed_count != 1) {
storage_cli_print_usage();
} else {
if(storage_file_open(file, string_get_cstr(path), FSAM_WRITE, FSOM_OPEN_APPEND)) {
printf("Ready\r\n");
if(buffer_size) {
uint8_t* buffer = malloc(buffer_size);
for(uint32_t i = 0; i < buffer_size; i++) {
buffer[i] = cli_getc(cli);
}
uint16_t written_size = storage_file_write(file, buffer, buffer_size);
if(written_size != buffer_size) {
storage_cli_print_error(storage_file_get_error(file));
}
free(buffer);
}
} else {
storage_cli_print_error(storage_file_get_error(file));
}
storage_file_close(file);
}
storage_file_free(file);
furi_record_close(RECORD_STORAGE);
}
static void storage_cli_stat(Cli* cli, string_t path) {
UNUSED(cli);
Storage* api = furi_record_open(RECORD_STORAGE);
if(string_cmp_str(path, "/") == 0) {
printf("Storage\r\n");
} else if(
string_cmp_str(path, STORAGE_EXT_PATH_PREFIX) == 0 ||
string_cmp_str(path, STORAGE_INT_PATH_PREFIX) == 0 ||
string_cmp_str(path, STORAGE_ANY_PATH_PREFIX) == 0) {
uint64_t total_space;
uint64_t free_space;
FS_Error error =
storage_common_fs_info(api, string_get_cstr(path), &total_space, &free_space);
if(error != FSE_OK) {
storage_cli_print_error(error);
} else {
printf(
"Storage, %luKB total, %luKB free\r\n",
(uint32_t)(total_space / 1024),
(uint32_t)(free_space / 1024));
}
} else {
FileInfo fileinfo;
FS_Error error = storage_common_stat(api, string_get_cstr(path), &fileinfo);
if(error == FSE_OK) {
if(fileinfo.flags & FSF_DIRECTORY) {
printf("Directory\r\n");
} else {
printf("File, size: %lub\r\n", (uint32_t)(fileinfo.size));
}
} else {
storage_cli_print_error(error);
}
}
furi_record_close(RECORD_STORAGE);
}
static void storage_cli_copy(Cli* cli, string_t old_path, string_t args) {
UNUSED(cli);
Storage* api = furi_record_open(RECORD_STORAGE);
string_t new_path;
string_init(new_path);
if(!args_read_probably_quoted_string_and_trim(args, new_path)) {
storage_cli_print_usage();
} else {
FS_Error error =
storage_common_copy(api, string_get_cstr(old_path), string_get_cstr(new_path));
if(error != FSE_OK) {
storage_cli_print_error(error);
}
}
string_clear(new_path);
furi_record_close(RECORD_STORAGE);
}
static void storage_cli_remove(Cli* cli, string_t path) {
UNUSED(cli);
Storage* api = furi_record_open(RECORD_STORAGE);
FS_Error error = storage_common_remove(api, string_get_cstr(path));
if(error != FSE_OK) {
storage_cli_print_error(error);
}
furi_record_close(RECORD_STORAGE);
}
static void storage_cli_rename(Cli* cli, string_t old_path, string_t args) {
UNUSED(cli);
Storage* api = furi_record_open(RECORD_STORAGE);
string_t new_path;
string_init(new_path);
if(!args_read_probably_quoted_string_and_trim(args, new_path)) {
storage_cli_print_usage();
} else {
FS_Error error =
storage_common_rename(api, string_get_cstr(old_path), string_get_cstr(new_path));
if(error != FSE_OK) {
storage_cli_print_error(error);
}
}
string_clear(new_path);
furi_record_close(RECORD_STORAGE);
}
static void storage_cli_mkdir(Cli* cli, string_t path) {
UNUSED(cli);
Storage* api = furi_record_open(RECORD_STORAGE);
FS_Error error = storage_common_mkdir(api, string_get_cstr(path));
if(error != FSE_OK) {
storage_cli_print_error(error);
}
furi_record_close(RECORD_STORAGE);
}
static void storage_cli_md5(Cli* cli, string_t path) {
UNUSED(cli);
Storage* api = furi_record_open(RECORD_STORAGE);
File* file = storage_file_alloc(api);
if(storage_file_open(file, string_get_cstr(path), FSAM_READ, FSOM_OPEN_EXISTING)) {
const uint16_t buffer_size = 512;
const uint8_t hash_size = 16;
uint8_t* data = malloc(buffer_size);
uint8_t* hash = malloc(sizeof(uint8_t) * hash_size);
md5_context* md5_ctx = malloc(sizeof(md5_context));
md5_starts(md5_ctx);
while(true) {
uint16_t read_size = storage_file_read(file, data, buffer_size);
if(read_size == 0) break;
md5_update(md5_ctx, data, read_size);
}
md5_finish(md5_ctx, hash);
free(md5_ctx);
for(uint8_t i = 0; i < hash_size; i++) {
printf("%02x", hash[i]);
}
printf("\r\n");
free(hash);
free(data);
} else {
storage_cli_print_error(storage_file_get_error(file));
}
storage_file_close(file);
storage_file_free(file);
furi_record_close(RECORD_STORAGE);
}
void storage_cli(Cli* cli, string_t args, void* context) {
UNUSED(context);
string_t cmd;
string_t path;
string_init(cmd);
string_init(path);
do {
if(!args_read_string_and_trim(args, cmd)) {
storage_cli_print_usage();
break;
}
if(!args_read_probably_quoted_string_and_trim(args, path)) {
storage_cli_print_usage();
break;
}
if(string_cmp_str(cmd, "info") == 0) {
storage_cli_info(cli, path);
break;
}
if(string_cmp_str(cmd, "format") == 0) {
storage_cli_format(cli, path);
break;
}
if(string_cmp_str(cmd, "list") == 0) {
storage_cli_list(cli, path);
break;
}
if(string_cmp_str(cmd, "tree") == 0) {
storage_cli_tree(cli, path);
break;
}
if(string_cmp_str(cmd, "read") == 0) {
storage_cli_read(cli, path);
break;
}
if(string_cmp_str(cmd, "read_chunks") == 0) {
storage_cli_read_chunks(cli, path, args);
break;
}
if(string_cmp_str(cmd, "write") == 0) {
storage_cli_write(cli, path);
break;
}
if(string_cmp_str(cmd, "write_chunk") == 0) {
storage_cli_write_chunk(cli, path, args);
break;
}
if(string_cmp_str(cmd, "copy") == 0) {
storage_cli_copy(cli, path, args);
break;
}
if(string_cmp_str(cmd, "remove") == 0) {
storage_cli_remove(cli, path);
break;
}
if(string_cmp_str(cmd, "rename") == 0) {
storage_cli_rename(cli, path, args);
break;
}
if(string_cmp_str(cmd, "mkdir") == 0) {
storage_cli_mkdir(cli, path);
break;
}
if(string_cmp_str(cmd, "md5") == 0) {
storage_cli_md5(cli, path);
break;
}
if(string_cmp_str(cmd, "stat") == 0) {
storage_cli_stat(cli, path);
break;
}
storage_cli_print_usage();
} while(false);
string_clear(path);
string_clear(cmd);
}
static void storage_cli_factory_reset(Cli* cli, string_t args, void* context) {
UNUSED(args);
UNUSED(context);
printf("All data will be lost! Are you sure (y/n)?\r\n");
char c = cli_getc(cli);
if(c == 'y' || c == 'Y') {
printf("Data will be wiped after reboot.\r\n");
furi_hal_rtc_set_flag(FuriHalRtcFlagFactoryReset);
power_reboot(PowerBootModeNormal);
} else {
printf("Safe choice.\r\n");
}
}
void storage_on_system_start() {
#ifdef SRV_CLI
Cli* cli = furi_record_open(RECORD_CLI);
cli_add_command(cli, RECORD_STORAGE, CliCommandFlagParallelSafe, storage_cli, NULL);
cli_add_command(
cli, "factory_reset", CliCommandFlagParallelSafe, storage_cli_factory_reset, NULL);
furi_record_close(RECORD_CLI);
#else
UNUSED(storage_cli_factory_reset);
#endif
}

View File

@@ -0,0 +1,801 @@
#include <core/log.h>
#include <core/record.h>
#include <m-string.h>
#include "storage.h"
#include "storage_i.h"
#include "storage_message.h"
#include <toolbox/stream/file_stream.h>
#include <toolbox/dir_walk.h>
#include "toolbox/path.h"
#define MAX_NAME_LENGTH 256
#define MAX_EXT_LEN 16
#define TAG "StorageAPI"
#define S_API_PROLOGUE \
FuriSemaphore* semaphore = furi_semaphore_alloc(1, 0); \
furi_check(semaphore != NULL);
#define S_FILE_API_PROLOGUE \
Storage* storage = file->storage; \
furi_assert(storage);
#define S_API_EPILOGUE \
furi_check( \
furi_message_queue_put(storage->message_queue, &message, FuriWaitForever) == \
FuriStatusOk); \
furi_semaphore_acquire(semaphore, FuriWaitForever); \
furi_semaphore_free(semaphore);
#define S_API_MESSAGE(_command) \
SAReturn return_data; \
StorageMessage message = { \
.semaphore = semaphore, \
.command = _command, \
.data = &data, \
.return_data = &return_data, \
};
#define S_API_DATA_FILE \
SAData data = { \
.file = { \
.file = file, \
}};
#define S_API_DATA_PATH \
SAData data = { \
.path = { \
.path = path, \
}};
#define S_RETURN_BOOL (return_data.bool_value);
#define S_RETURN_UINT16 (return_data.uint16_value);
#define S_RETURN_UINT64 (return_data.uint64_value);
#define S_RETURN_ERROR (return_data.error_value);
#define S_RETURN_CSTRING (return_data.cstring_value);
typedef enum {
StorageEventFlagFileClose = (1 << 0),
} StorageEventFlag;
/****************** FILE ******************/
static bool storage_file_open_internal(
File* file,
const char* path,
FS_AccessMode access_mode,
FS_OpenMode open_mode) {
S_FILE_API_PROLOGUE;
S_API_PROLOGUE;
SAData data = {
.fopen = {
.file = file,
.path = path,
.access_mode = access_mode,
.open_mode = open_mode,
}};
file->type = FileTypeOpenFile;
S_API_MESSAGE(StorageCommandFileOpen);
S_API_EPILOGUE;
return S_RETURN_BOOL;
}
static void storage_file_close_callback(const void* message, void* context) {
const StorageEvent* storage_event = message;
if(storage_event->type == StorageEventTypeFileClose ||
storage_event->type == StorageEventTypeDirClose) {
furi_assert(context);
FuriEventFlag* event = context;
furi_event_flag_set(event, StorageEventFlagFileClose);
}
}
bool storage_file_open(
File* file,
const char* path,
FS_AccessMode access_mode,
FS_OpenMode open_mode) {
bool result;
FuriEventFlag* event = furi_event_flag_alloc();
FuriPubSubSubscription* subscription = furi_pubsub_subscribe(
storage_get_pubsub(file->storage), storage_file_close_callback, event);
do {
result = storage_file_open_internal(file, path, access_mode, open_mode);
if(!result && file->error_id == FSE_ALREADY_OPEN) {
furi_event_flag_wait(
event, StorageEventFlagFileClose, FuriFlagWaitAny, FuriWaitForever);
} else {
break;
}
} while(true);
furi_pubsub_unsubscribe(storage_get_pubsub(file->storage), subscription);
furi_event_flag_free(event);
FURI_LOG_T(
TAG, "File %p - %p open (%s)", (uint32_t)file - SRAM_BASE, file->file_id - SRAM_BASE, path);
return result;
}
bool storage_file_close(File* file) {
S_FILE_API_PROLOGUE;
S_API_PROLOGUE;
S_API_DATA_FILE;
S_API_MESSAGE(StorageCommandFileClose);
S_API_EPILOGUE;
FURI_LOG_T(TAG, "File %p - %p closed", (uint32_t)file - SRAM_BASE, file->file_id - SRAM_BASE);
file->type = FileTypeClosed;
return S_RETURN_BOOL;
}
uint16_t storage_file_read(File* file, void* buff, uint16_t bytes_to_read) {
if(bytes_to_read == 0) {
return 0;
}
S_FILE_API_PROLOGUE;
S_API_PROLOGUE;
SAData data = {
.fread = {
.file = file,
.buff = buff,
.bytes_to_read = bytes_to_read,
}};
S_API_MESSAGE(StorageCommandFileRead);
S_API_EPILOGUE;
return S_RETURN_UINT16;
}
uint16_t storage_file_write(File* file, const void* buff, uint16_t bytes_to_write) {
if(bytes_to_write == 0) {
return 0;
}
S_FILE_API_PROLOGUE;
S_API_PROLOGUE;
SAData data = {
.fwrite = {
.file = file,
.buff = buff,
.bytes_to_write = bytes_to_write,
}};
S_API_MESSAGE(StorageCommandFileWrite);
S_API_EPILOGUE;
return S_RETURN_UINT16;
}
bool storage_file_seek(File* file, uint32_t offset, bool from_start) {
S_FILE_API_PROLOGUE;
S_API_PROLOGUE;
SAData data = {
.fseek = {
.file = file,
.offset = offset,
.from_start = from_start,
}};
S_API_MESSAGE(StorageCommandFileSeek);
S_API_EPILOGUE;
return S_RETURN_BOOL;
}
uint64_t storage_file_tell(File* file) {
S_FILE_API_PROLOGUE;
S_API_PROLOGUE;
S_API_DATA_FILE;
S_API_MESSAGE(StorageCommandFileTell);
S_API_EPILOGUE;
return S_RETURN_UINT64;
}
bool storage_file_truncate(File* file) {
S_FILE_API_PROLOGUE;
S_API_PROLOGUE;
S_API_DATA_FILE;
S_API_MESSAGE(StorageCommandFileTruncate);
S_API_EPILOGUE;
return S_RETURN_BOOL;
}
uint64_t storage_file_size(File* file) {
S_FILE_API_PROLOGUE;
S_API_PROLOGUE;
S_API_DATA_FILE;
S_API_MESSAGE(StorageCommandFileSize);
S_API_EPILOGUE;
return S_RETURN_UINT64;
}
bool storage_file_sync(File* file) {
S_FILE_API_PROLOGUE;
S_API_PROLOGUE;
S_API_DATA_FILE;
S_API_MESSAGE(StorageCommandFileSync);
S_API_EPILOGUE;
return S_RETURN_BOOL;
}
bool storage_file_eof(File* file) {
S_FILE_API_PROLOGUE;
S_API_PROLOGUE;
S_API_DATA_FILE;
S_API_MESSAGE(StorageCommandFileEof);
S_API_EPILOGUE;
return S_RETURN_BOOL;
}
bool storage_file_exists(Storage* storage, const char* path) {
bool exist = false;
FileInfo fileinfo;
FS_Error error = storage_common_stat(storage, path, &fileinfo);
if(error == FSE_OK && !(fileinfo.flags & FSF_DIRECTORY)) {
exist = true;
}
return exist;
}
/****************** DIR ******************/
static bool storage_dir_open_internal(File* file, const char* path) {
S_FILE_API_PROLOGUE;
S_API_PROLOGUE;
SAData data = {
.dopen = {
.file = file,
.path = path,
}};
file->type = FileTypeOpenDir;
S_API_MESSAGE(StorageCommandDirOpen);
S_API_EPILOGUE;
return S_RETURN_BOOL;
}
bool storage_dir_open(File* file, const char* path) {
bool result;
FuriEventFlag* event = furi_event_flag_alloc();
FuriPubSubSubscription* subscription = furi_pubsub_subscribe(
storage_get_pubsub(file->storage), storage_file_close_callback, event);
do {
result = storage_dir_open_internal(file, path);
if(!result && file->error_id == FSE_ALREADY_OPEN) {
furi_event_flag_wait(
event, StorageEventFlagFileClose, FuriFlagWaitAny, FuriWaitForever);
} else {
break;
}
} while(true);
furi_pubsub_unsubscribe(storage_get_pubsub(file->storage), subscription);
furi_event_flag_free(event);
FURI_LOG_T(
TAG, "Dir %p - %p open (%s)", (uint32_t)file - SRAM_BASE, file->file_id - SRAM_BASE, path);
return result;
}
bool storage_dir_close(File* file) {
S_FILE_API_PROLOGUE;
S_API_PROLOGUE;
S_API_DATA_FILE;
S_API_MESSAGE(StorageCommandDirClose);
S_API_EPILOGUE;
FURI_LOG_T(TAG, "Dir %p - %p closed", (uint32_t)file - SRAM_BASE, file->file_id - SRAM_BASE);
file->type = FileTypeClosed;
return S_RETURN_BOOL;
}
bool storage_dir_read(File* file, FileInfo* fileinfo, char* name, uint16_t name_length) {
S_FILE_API_PROLOGUE;
S_API_PROLOGUE;
SAData data = {
.dread = {
.file = file,
.fileinfo = fileinfo,
.name = name,
.name_length = name_length,
}};
S_API_MESSAGE(StorageCommandDirRead);
S_API_EPILOGUE;
return S_RETURN_BOOL;
}
bool storage_dir_rewind(File* file) {
S_FILE_API_PROLOGUE;
S_API_PROLOGUE;
S_API_DATA_FILE;
S_API_MESSAGE(StorageCommandDirRewind);
S_API_EPILOGUE;
return S_RETURN_BOOL;
}
/****************** COMMON ******************/
FS_Error storage_common_stat(Storage* storage, const char* path, FileInfo* fileinfo) {
S_API_PROLOGUE;
SAData data = {.cstat = {.path = path, .fileinfo = fileinfo}};
S_API_MESSAGE(StorageCommandCommonStat);
S_API_EPILOGUE;
return S_RETURN_ERROR;
}
FS_Error storage_common_remove(Storage* storage, const char* path) {
S_API_PROLOGUE;
S_API_DATA_PATH;
S_API_MESSAGE(StorageCommandCommonRemove);
S_API_EPILOGUE;
return S_RETURN_ERROR;
}
FS_Error storage_common_rename(Storage* storage, const char* old_path, const char* new_path) {
FS_Error error = storage_common_copy(storage, old_path, new_path);
if(error == FSE_OK) {
if(storage_simply_remove_recursive(storage, old_path)) {
error = FSE_OK;
} else {
error = FSE_INTERNAL;
}
}
return error;
}
static FS_Error
storage_copy_recursive(Storage* storage, const char* old_path, const char* new_path) {
FS_Error error = storage_common_mkdir(storage, new_path);
DirWalk* dir_walk = dir_walk_alloc(storage);
string_t path;
string_t tmp_new_path;
string_t tmp_old_path;
FileInfo fileinfo;
string_init(path);
string_init(tmp_new_path);
string_init(tmp_old_path);
do {
if(error != FSE_OK) break;
if(!dir_walk_open(dir_walk, old_path)) {
error = dir_walk_get_error(dir_walk);
break;
}
while(1) {
DirWalkResult res = dir_walk_read(dir_walk, path, &fileinfo);
if(res == DirWalkError) {
error = dir_walk_get_error(dir_walk);
break;
} else if(res == DirWalkLast) {
break;
} else {
string_set(tmp_old_path, path);
string_right(path, strlen(old_path));
string_printf(tmp_new_path, "%s%s", new_path, string_get_cstr(path));
if(fileinfo.flags & FSF_DIRECTORY) {
error = storage_common_mkdir(storage, string_get_cstr(tmp_new_path));
} else {
error = storage_common_copy(
storage, string_get_cstr(tmp_old_path), string_get_cstr(tmp_new_path));
}
if(error != FSE_OK) break;
}
}
} while(false);
string_clear(tmp_new_path);
string_clear(tmp_old_path);
string_clear(path);
dir_walk_free(dir_walk);
return error;
}
FS_Error storage_common_copy(Storage* storage, const char* old_path, const char* new_path) {
FS_Error error;
FileInfo fileinfo;
error = storage_common_stat(storage, old_path, &fileinfo);
if(error == FSE_OK) {
if(fileinfo.flags & FSF_DIRECTORY) {
error = storage_copy_recursive(storage, old_path, new_path);
} else {
Stream* stream_from = file_stream_alloc(storage);
Stream* stream_to = file_stream_alloc(storage);
do {
if(!file_stream_open(stream_from, old_path, FSAM_READ, FSOM_OPEN_EXISTING)) break;
if(!file_stream_open(stream_to, new_path, FSAM_WRITE, FSOM_CREATE_NEW)) break;
stream_copy_full(stream_from, stream_to);
} while(false);
error = file_stream_get_error(stream_from);
if(error == FSE_OK) {
error = file_stream_get_error(stream_to);
}
stream_free(stream_from);
stream_free(stream_to);
}
}
return error;
}
static FS_Error
storage_merge_recursive(Storage* storage, const char* old_path, const char* new_path) {
FS_Error error = storage_common_mkdir(storage, new_path);
DirWalk* dir_walk = dir_walk_alloc(storage);
string_t path, file_basename, tmp_new_path;
FileInfo fileinfo;
string_init(path);
string_init(file_basename);
string_init(tmp_new_path);
do {
if((error != FSE_OK) && (error != FSE_EXIST)) break;
dir_walk_set_recursive(dir_walk, false);
if(!dir_walk_open(dir_walk, old_path)) {
error = dir_walk_get_error(dir_walk);
break;
}
while(1) {
DirWalkResult res = dir_walk_read(dir_walk, path, &fileinfo);
if(res == DirWalkError) {
error = dir_walk_get_error(dir_walk);
break;
} else if(res == DirWalkLast) {
break;
} else {
path_extract_basename(string_get_cstr(path), file_basename);
path_concat(new_path, string_get_cstr(file_basename), tmp_new_path);
if(fileinfo.flags & FSF_DIRECTORY) {
if(storage_common_stat(storage, string_get_cstr(tmp_new_path), &fileinfo) ==
FSE_OK) {
if(fileinfo.flags & FSF_DIRECTORY) {
error = storage_common_mkdir(storage, string_get_cstr(tmp_new_path));
if(error != FSE_OK) {
break;
}
}
}
}
error = storage_common_merge(
storage, string_get_cstr(path), string_get_cstr(tmp_new_path));
if(error != FSE_OK) {
break;
}
}
}
} while(false);
string_clear(tmp_new_path);
string_clear(file_basename);
string_clear(path);
dir_walk_free(dir_walk);
return error;
}
FS_Error storage_common_merge(Storage* storage, const char* old_path, const char* new_path) {
FS_Error error;
const char* new_path_tmp;
string_t new_path_next;
string_init(new_path_next);
FileInfo fileinfo;
error = storage_common_stat(storage, old_path, &fileinfo);
if(error == FSE_OK) {
if(fileinfo.flags & FSF_DIRECTORY) {
error = storage_merge_recursive(storage, old_path, new_path);
} else {
error = storage_common_stat(storage, new_path, &fileinfo);
if(error == FSE_OK) {
string_set_str(new_path_next, new_path);
string_t dir_path;
string_t filename;
char extension[MAX_EXT_LEN];
string_init(dir_path);
string_init(filename);
path_extract_filename(new_path_next, filename, true);
path_extract_dirname(new_path, dir_path);
path_extract_extension(new_path_next, extension, MAX_EXT_LEN);
storage_get_next_filename(
storage,
string_get_cstr(dir_path),
string_get_cstr(filename),
extension,
new_path_next,
255);
string_cat_printf(dir_path, "/%s%s", string_get_cstr(new_path_next), extension);
string_set(new_path_next, dir_path);
string_clear(dir_path);
string_clear(filename);
new_path_tmp = string_get_cstr(new_path_next);
} else {
new_path_tmp = new_path;
}
Stream* stream_from = file_stream_alloc(storage);
Stream* stream_to = file_stream_alloc(storage);
do {
if(!file_stream_open(stream_from, old_path, FSAM_READ, FSOM_OPEN_EXISTING)) break;
if(!file_stream_open(stream_to, new_path_tmp, FSAM_WRITE, FSOM_CREATE_NEW)) break;
stream_copy_full(stream_from, stream_to);
} while(false);
error = file_stream_get_error(stream_from);
if(error == FSE_OK) {
error = file_stream_get_error(stream_to);
}
stream_free(stream_from);
stream_free(stream_to);
}
}
string_clear(new_path_next);
return error;
}
FS_Error storage_common_mkdir(Storage* storage, const char* path) {
S_API_PROLOGUE;
S_API_DATA_PATH;
S_API_MESSAGE(StorageCommandCommonMkDir);
S_API_EPILOGUE;
return S_RETURN_ERROR;
}
FS_Error storage_common_fs_info(
Storage* storage,
const char* fs_path,
uint64_t* total_space,
uint64_t* free_space) {
S_API_PROLOGUE;
SAData data = {
.cfsinfo = {
.fs_path = fs_path,
.total_space = total_space,
.free_space = free_space,
}};
S_API_MESSAGE(StorageCommandCommonFSInfo);
S_API_EPILOGUE;
return S_RETURN_ERROR;
}
/****************** ERROR ******************/
const char* storage_error_get_desc(FS_Error error_id) {
return filesystem_api_error_get_desc(error_id);
}
FS_Error storage_file_get_error(File* file) {
furi_check(file != NULL);
return file->error_id;
}
int32_t storage_file_get_internal_error(File* file) {
furi_check(file != NULL);
return file->internal_error_id;
}
const char* storage_file_get_error_desc(File* file) {
furi_check(file != NULL);
return filesystem_api_error_get_desc(file->error_id);
}
/****************** Raw SD API ******************/
FS_Error storage_sd_format(Storage* storage) {
S_API_PROLOGUE;
SAData data = {};
S_API_MESSAGE(StorageCommandSDFormat);
S_API_EPILOGUE;
return S_RETURN_ERROR;
}
FS_Error storage_sd_unmount(Storage* storage) {
S_API_PROLOGUE;
SAData data = {};
S_API_MESSAGE(StorageCommandSDUnmount);
S_API_EPILOGUE;
return S_RETURN_ERROR;
}
FS_Error storage_sd_info(Storage* storage, SDInfo* info) {
S_API_PROLOGUE;
SAData data = {
.sdinfo = {
.info = info,
}};
S_API_MESSAGE(StorageCommandSDInfo);
S_API_EPILOGUE;
return S_RETURN_ERROR;
}
FS_Error storage_sd_status(Storage* storage) {
S_API_PROLOGUE;
SAData data = {};
S_API_MESSAGE(StorageCommandSDStatus);
S_API_EPILOGUE;
return S_RETURN_ERROR;
}
File* storage_file_alloc(Storage* storage) {
File* file = malloc(sizeof(File));
file->type = FileTypeClosed;
file->storage = storage;
FURI_LOG_T(TAG, "File/Dir %p alloc", (uint32_t)file - SRAM_BASE);
return file;
}
bool storage_file_is_open(File* file) {
return (file->type != FileTypeClosed);
}
bool storage_file_is_dir(File* file) {
return (file->type == FileTypeOpenDir);
}
void storage_file_free(File* file) {
if(storage_file_is_open(file)) {
if(storage_file_is_dir(file)) {
storage_dir_close(file);
} else {
storage_file_close(file);
}
}
FURI_LOG_T(TAG, "File/Dir %p free", (uint32_t)file - SRAM_BASE);
free(file);
}
FuriPubSub* storage_get_pubsub(Storage* storage) {
return storage->pubsub;
}
bool storage_simply_remove_recursive(Storage* storage, const char* path) {
furi_assert(storage);
furi_assert(path);
FileInfo fileinfo;
bool result = false;
string_t fullname;
string_t cur_dir;
if(storage_simply_remove(storage, path)) {
return true;
}
char* name = malloc(MAX_NAME_LENGTH + 1);
File* dir = storage_file_alloc(storage);
string_init_set_str(cur_dir, path);
bool go_deeper = false;
while(1) {
if(!storage_dir_open(dir, string_get_cstr(cur_dir))) {
storage_dir_close(dir);
break;
}
while(storage_dir_read(dir, &fileinfo, name, MAX_NAME_LENGTH)) {
if(fileinfo.flags & FSF_DIRECTORY) {
string_cat_printf(cur_dir, "/%s", name);
go_deeper = true;
break;
}
string_init_printf(fullname, "%s/%s", string_get_cstr(cur_dir), name);
FS_Error error = storage_common_remove(storage, string_get_cstr(fullname));
furi_check(error == FSE_OK);
string_clear(fullname);
}
storage_dir_close(dir);
if(go_deeper) {
go_deeper = false;
continue;
}
FS_Error error = storage_common_remove(storage, string_get_cstr(cur_dir));
furi_check(error == FSE_OK);
if(string_cmp(cur_dir, path)) {
size_t last_char = string_search_rchar(cur_dir, '/');
furi_assert(last_char != STRING_FAILURE);
string_left(cur_dir, last_char);
} else {
result = true;
break;
}
}
storage_file_free(dir);
string_clear(cur_dir);
free(name);
return result;
}
bool storage_simply_remove(Storage* storage, const char* path) {
FS_Error result;
result = storage_common_remove(storage, path);
return result == FSE_OK || result == FSE_NOT_EXIST;
}
bool storage_simply_mkdir(Storage* storage, const char* path) {
FS_Error result;
result = storage_common_mkdir(storage, path);
return result == FSE_OK || result == FSE_EXIST;
}
void storage_get_next_filename(
Storage* storage,
const char* dirname,
const char* filename,
const char* fileextension,
string_t nextfilename,
uint8_t max_len) {
string_t temp_str;
uint16_t num = 0;
string_init_printf(temp_str, "%s/%s%s", dirname, filename, fileextension);
while(storage_common_stat(storage, string_get_cstr(temp_str), NULL) == FSE_OK) {
num++;
string_printf(temp_str, "%s/%s%d%s", dirname, filename, num, fileextension);
}
if(num && (max_len > strlen(filename))) {
string_printf(nextfilename, "%s%d", filename, num);
} else {
string_printf(nextfilename, "%s", filename);
}
string_clear(temp_str);
}

View File

@@ -0,0 +1,188 @@
#include "storage_glue.h"
#include <furi_hal.h>
/****************** storage file ******************/
void storage_file_init(StorageFile* obj) {
obj->file = NULL;
obj->type = ST_ERROR;
obj->file_data = NULL;
string_init(obj->path);
}
void storage_file_init_set(StorageFile* obj, const StorageFile* src) {
obj->file = src->file;
obj->type = src->type;
obj->file_data = src->file_data;
string_init_set(obj->path, src->path);
}
void storage_file_set(StorageFile* obj, const StorageFile* src) {
obj->file = src->file;
obj->type = src->type;
obj->file_data = src->file_data;
string_set(obj->path, src->path);
}
void storage_file_clear(StorageFile* obj) {
string_clear(obj->path);
}
/****************** storage data ******************/
void storage_data_init(StorageData* storage) {
storage->mutex = furi_mutex_alloc(FuriMutexTypeNormal);
furi_check(storage->mutex != NULL);
storage->data = NULL;
storage->status = StorageStatusNotReady;
StorageFileList_init(storage->files);
}
bool storage_data_lock(StorageData* storage) {
return (furi_mutex_acquire(storage->mutex, FuriWaitForever) == FuriStatusOk);
}
bool storage_data_unlock(StorageData* storage) {
return (furi_mutex_release(storage->mutex) == FuriStatusOk);
}
StorageStatus storage_data_status(StorageData* storage) {
StorageStatus status;
storage_data_lock(storage);
status = storage->status;
storage_data_unlock(storage);
return status;
}
const char* storage_data_status_text(StorageData* storage) {
const char* result = "unknown";
switch(storage->status) {
case StorageStatusOK:
result = "ok";
break;
case StorageStatusNotReady:
result = "not ready";
break;
case StorageStatusNotMounted:
result = "not mounted";
break;
case StorageStatusNoFS:
result = "no filesystem";
break;
case StorageStatusNotAccessible:
result = "not accessible";
break;
case StorageStatusErrorInternal:
result = "internal";
break;
}
return result;
}
/****************** storage glue ******************/
bool storage_has_file(const File* file, StorageData* storage_data) {
bool result = false;
StorageFileList_it_t it;
for(StorageFileList_it(it, storage_data->files); !StorageFileList_end_p(it);
StorageFileList_next(it)) {
const StorageFile* storage_file = StorageFileList_cref(it);
if(storage_file->file->file_id == file->file_id) {
result = true;
break;
}
}
return result;
}
bool storage_path_already_open(string_t path, StorageFileList_t array) {
bool open = false;
StorageFileList_it_t it;
for(StorageFileList_it(it, array); !StorageFileList_end_p(it); StorageFileList_next(it)) {
const StorageFile* storage_file = StorageFileList_cref(it);
if(string_cmp(storage_file->path, path) == 0) {
open = true;
break;
}
}
return open;
}
void storage_set_storage_file_data(const File* file, void* file_data, StorageData* storage) {
StorageFile* founded_file = NULL;
StorageFileList_it_t it;
for(StorageFileList_it(it, storage->files); !StorageFileList_end_p(it);
StorageFileList_next(it)) {
StorageFile* storage_file = StorageFileList_ref(it);
if(storage_file->file->file_id == file->file_id) {
founded_file = storage_file;
break;
}
}
furi_check(founded_file != NULL);
founded_file->file_data = file_data;
}
void* storage_get_storage_file_data(const File* file, StorageData* storage) {
const StorageFile* founded_file = NULL;
StorageFileList_it_t it;
for(StorageFileList_it(it, storage->files); !StorageFileList_end_p(it);
StorageFileList_next(it)) {
const StorageFile* storage_file = StorageFileList_cref(it);
if(storage_file->file->file_id == file->file_id) {
founded_file = storage_file;
break;
}
}
furi_check(founded_file != NULL);
return founded_file->file_data;
}
void storage_push_storage_file(File* file, string_t path, StorageType type, StorageData* storage) {
StorageFile* storage_file = StorageFileList_push_new(storage->files);
furi_check(storage_file != NULL);
file->file_id = (uint32_t)storage_file;
storage_file->file = file;
storage_file->type = type;
string_set(storage_file->path, path);
}
bool storage_pop_storage_file(File* file, StorageData* storage) {
StorageFileList_it_t it;
bool result = false;
for(StorageFileList_it(it, storage->files); !StorageFileList_end_p(it);
StorageFileList_next(it)) {
if(StorageFileList_cref(it)->file->file_id == file->file_id) {
result = true;
break;
}
}
if(result) {
StorageFileList_remove(storage->files, it);
}
return result;
}

View File

@@ -0,0 +1,75 @@
#pragma once
#include <furi.h>
#include "filesystem_api_internal.h"
#include <m-string.h>
#include <m-list.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef enum { ST_EXT = 0, ST_INT = 1, ST_ANY, ST_ERROR } StorageType;
typedef struct StorageData StorageData;
typedef struct {
void (*tick)(StorageData* storage);
} StorageApi;
typedef struct {
File* file;
StorageType type;
void* file_data;
string_t path;
} StorageFile;
typedef enum {
StorageStatusOK, /**< storage ok */
StorageStatusNotReady, /**< storage not ready (not initialized or waiting for data storage to appear) */
StorageStatusNotMounted, /**< datastore appeared, but we cannot mount it */
StorageStatusNoFS, /**< datastore appeared and mounted, but does not have a file system */
StorageStatusNotAccessible, /**< datastore appeared and mounted, but not available */
StorageStatusErrorInternal, /**< any other internal error */
} StorageStatus;
void storage_file_init(StorageFile* obj);
void storage_file_init_set(StorageFile* obj, const StorageFile* src);
void storage_file_set(StorageFile* obj, const StorageFile* src);
void storage_file_clear(StorageFile* obj);
void storage_data_init(StorageData* storage);
bool storage_data_lock(StorageData* storage);
bool storage_data_unlock(StorageData* storage);
StorageStatus storage_data_status(StorageData* storage);
const char* storage_data_status_text(StorageData* storage);
LIST_DEF(
StorageFileList,
StorageFile,
(INIT(API_2(storage_file_init)),
SET(API_6(storage_file_init_set)),
INIT_SET(API_6(storage_file_set)),
CLEAR(API_2(storage_file_clear))))
struct StorageData {
const FS_Api* fs_api;
StorageApi api;
void* data;
FuriMutex* mutex;
StorageStatus status;
StorageFileList_t files;
};
bool storage_has_file(const File* file, StorageData* storage_data);
bool storage_path_already_open(string_t path, StorageFileList_t files);
void storage_set_storage_file_data(const File* file, void* file_data, StorageData* storage);
void* storage_get_storage_file_data(const File* file, StorageData* storage);
void storage_push_storage_file(File* file, string_t path, StorageType type, StorageData* storage);
bool storage_pop_storage_file(File* file, StorageData* storage);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,28 @@
#pragma once
#include <furi.h>
#include <gui/gui.h>
#include "storage_glue.h"
#include "storage_sd_api.h"
#include "filesystem_api_internal.h"
#ifdef __cplusplus
extern "C" {
#endif
#define STORAGE_COUNT (ST_INT + 1)
typedef struct {
ViewPort* view_port;
bool enabled;
} StorageSDGui;
struct Storage {
FuriMessageQueue* message_queue;
StorageData storage[STORAGE_COUNT];
StorageSDGui sd_gui;
FuriPubSub* pubsub;
};
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,21 @@
#include <core/record.h>
#include <m-string.h>
#include "storage.h"
#include <toolbox/tar/tar_archive.h>
FS_Error storage_int_backup(Storage* api, const char* dstname) {
TarArchive* archive = tar_archive_alloc(api);
bool success = tar_archive_open(archive, dstname, TAR_OPEN_MODE_WRITE) &&
tar_archive_add_dir(archive, STORAGE_INT_PATH_PREFIX, "") &&
tar_archive_finalize(archive);
tar_archive_free(archive);
return success ? FSE_OK : FSE_INTERNAL;
}
FS_Error storage_int_restore(Storage* api, const char* srcname, Storage_name_converter converter) {
TarArchive* archive = tar_archive_alloc(api);
bool success = tar_archive_open(archive, srcname, TAR_OPEN_MODE_READ) &&
tar_archive_unpack_to(archive, STORAGE_INT_PATH_PREFIX, converter);
tar_archive_free(archive);
return success ? FSE_OK : FSE_INTERNAL;
}

View File

@@ -0,0 +1,134 @@
#pragma once
#include <furi.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
File* file;
const char* path;
FS_AccessMode access_mode;
FS_OpenMode open_mode;
} SADataFOpen;
typedef struct {
File* file;
void* buff;
uint16_t bytes_to_read;
} SADataFRead;
typedef struct {
File* file;
const void* buff;
uint16_t bytes_to_write;
} SADataFWrite;
typedef struct {
File* file;
uint32_t offset;
bool from_start;
} SADataFSeek;
typedef struct {
File* file;
const char* path;
} SADataDOpen;
typedef struct {
File* file;
FileInfo* fileinfo;
char* name;
uint16_t name_length;
} SADataDRead;
typedef struct {
const char* path;
FileInfo* fileinfo;
} SADataCStat;
typedef struct {
const char* fs_path;
uint64_t* total_space;
uint64_t* free_space;
} SADataCFSInfo;
typedef struct {
uint32_t id;
} SADataError;
typedef struct {
const char* path;
} SADataPath;
typedef struct {
File* file;
} SADataFile;
typedef struct {
SDInfo* info;
} SAInfo;
typedef union {
SADataFOpen fopen;
SADataFRead fread;
SADataFWrite fwrite;
SADataFSeek fseek;
SADataDOpen dopen;
SADataDRead dread;
SADataCStat cstat;
SADataCFSInfo cfsinfo;
SADataError error;
SADataFile file;
SADataPath path;
SAInfo sdinfo;
} SAData;
typedef union {
bool bool_value;
uint16_t uint16_value;
uint64_t uint64_value;
FS_Error error_value;
const char* cstring_value;
} SAReturn;
typedef enum {
StorageCommandFileOpen,
StorageCommandFileClose,
StorageCommandFileRead,
StorageCommandFileWrite,
StorageCommandFileSeek,
StorageCommandFileTell,
StorageCommandFileTruncate,
StorageCommandFileSize,
StorageCommandFileSync,
StorageCommandFileEof,
StorageCommandDirOpen,
StorageCommandDirClose,
StorageCommandDirRead,
StorageCommandDirRewind,
StorageCommandCommonStat,
StorageCommandCommonRemove,
StorageCommandCommonMkDir,
StorageCommandCommonFSInfo,
StorageCommandSDFormat,
StorageCommandSDUnmount,
StorageCommandSDInfo,
StorageCommandSDStatus,
} StorageCommand;
typedef struct {
FuriSemaphore* semaphore;
StorageCommand command;
SAData* data;
SAReturn* return_data;
} StorageMessage;
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,583 @@
#include "storage_processing.h"
#include <m-list.h>
#include <m-dict.h>
#include <m-string.h>
#define FS_CALL(_storage, _fn) \
storage_data_lock(_storage); \
ret = _storage->fs_api->_fn; \
storage_data_unlock(_storage);
#define ST_CALL(_storage, _fn) \
storage_data_lock(_storage); \
ret = _storage->api._fn; \
storage_data_unlock(_storage);
static StorageData* storage_get_storage_by_type(Storage* app, StorageType type) {
furi_check(type == ST_EXT || type == ST_INT);
StorageData* storage = &app->storage[type];
return storage;
}
static bool storage_type_is_not_valid(StorageType type) {
#ifdef FURI_RAM_EXEC
return type != ST_EXT;
#else
return type >= ST_ERROR;
#endif
}
static StorageData* get_storage_by_file(File* file, StorageData* storages) {
StorageData* storage_data = NULL;
for(uint8_t i = 0; i < STORAGE_COUNT; i++) {
if(storage_has_file(file, &storages[i])) {
storage_data = &storages[i];
}
}
return storage_data;
}
static const char* remove_vfs(const char* path) {
return path + MIN(4u, strlen(path));
}
static StorageType storage_get_type_by_path(Storage* app, const char* path) {
StorageType type = ST_ERROR;
if(strlen(path) >= strlen(STORAGE_EXT_PATH_PREFIX) &&
memcmp(path, STORAGE_EXT_PATH_PREFIX, strlen(STORAGE_EXT_PATH_PREFIX)) == 0) {
type = ST_EXT;
} else if(
strlen(path) >= strlen(STORAGE_INT_PATH_PREFIX) &&
memcmp(path, STORAGE_INT_PATH_PREFIX, strlen(STORAGE_INT_PATH_PREFIX)) == 0) {
type = ST_INT;
} else if(
strlen(path) >= strlen(STORAGE_ANY_PATH_PREFIX) &&
memcmp(path, STORAGE_ANY_PATH_PREFIX, strlen(STORAGE_ANY_PATH_PREFIX)) == 0) {
type = ST_ANY;
}
if(type == ST_ANY) {
type = ST_INT;
if(storage_data_status(&app->storage[ST_EXT]) == StorageStatusOK) {
type = ST_EXT;
}
}
return type;
}
static void storage_path_change_to_real_storage(string_t path, StorageType real_storage) {
if(memcmp(string_get_cstr(path), STORAGE_ANY_PATH_PREFIX, strlen(STORAGE_ANY_PATH_PREFIX)) ==
0) {
switch(real_storage) {
case ST_EXT:
string_set_char(path, 0, STORAGE_EXT_PATH_PREFIX[0]);
string_set_char(path, 1, STORAGE_EXT_PATH_PREFIX[1]);
string_set_char(path, 2, STORAGE_EXT_PATH_PREFIX[2]);
string_set_char(path, 3, STORAGE_EXT_PATH_PREFIX[3]);
break;
case ST_INT:
string_set_char(path, 0, STORAGE_INT_PATH_PREFIX[0]);
string_set_char(path, 1, STORAGE_INT_PATH_PREFIX[1]);
string_set_char(path, 2, STORAGE_INT_PATH_PREFIX[2]);
string_set_char(path, 3, STORAGE_INT_PATH_PREFIX[3]);
break;
default:
break;
}
}
}
/******************* File Functions *******************/
bool storage_process_file_open(
Storage* app,
File* file,
const char* path,
FS_AccessMode access_mode,
FS_OpenMode open_mode) {
bool ret = false;
StorageType type = storage_get_type_by_path(app, path);
StorageData* storage;
file->error_id = FSE_OK;
if(storage_type_is_not_valid(type)) {
file->error_id = FSE_INVALID_NAME;
} else {
storage = storage_get_storage_by_type(app, type);
string_t real_path;
string_init_set(real_path, path);
storage_path_change_to_real_storage(real_path, type);
if(storage_path_already_open(real_path, storage->files)) {
file->error_id = FSE_ALREADY_OPEN;
} else {
storage_push_storage_file(file, real_path, type, storage);
FS_CALL(storage, file.open(storage, file, remove_vfs(path), access_mode, open_mode));
}
string_clear(real_path);
}
return ret;
}
bool storage_process_file_close(Storage* app, File* file) {
bool ret = false;
StorageData* storage = get_storage_by_file(file, app->storage);
if(storage == NULL) {
file->error_id = FSE_INVALID_PARAMETER;
} else {
FS_CALL(storage, file.close(storage, file));
storage_pop_storage_file(file, storage);
StorageEvent event = {.type = StorageEventTypeFileClose};
furi_pubsub_publish(app->pubsub, &event);
}
return ret;
}
static uint16_t
storage_process_file_read(Storage* app, File* file, void* buff, uint16_t const bytes_to_read) {
uint16_t ret = 0;
StorageData* storage = get_storage_by_file(file, app->storage);
if(storage == NULL) {
file->error_id = FSE_INVALID_PARAMETER;
} else {
FS_CALL(storage, file.read(storage, file, buff, bytes_to_read));
}
return ret;
}
static uint16_t storage_process_file_write(
Storage* app,
File* file,
const void* buff,
uint16_t const bytes_to_write) {
uint16_t ret = 0;
StorageData* storage = get_storage_by_file(file, app->storage);
if(storage == NULL) {
file->error_id = FSE_INVALID_PARAMETER;
} else {
FS_CALL(storage, file.write(storage, file, buff, bytes_to_write));
}
return ret;
}
static bool storage_process_file_seek(
Storage* app,
File* file,
const uint32_t offset,
const bool from_start) {
bool ret = false;
StorageData* storage = get_storage_by_file(file, app->storage);
if(storage == NULL) {
file->error_id = FSE_INVALID_PARAMETER;
} else {
FS_CALL(storage, file.seek(storage, file, offset, from_start));
}
return ret;
}
static uint64_t storage_process_file_tell(Storage* app, File* file) {
uint64_t ret = 0;
StorageData* storage = get_storage_by_file(file, app->storage);
if(storage == NULL) {
file->error_id = FSE_INVALID_PARAMETER;
} else {
FS_CALL(storage, file.tell(storage, file));
}
return ret;
}
static bool storage_process_file_truncate(Storage* app, File* file) {
bool ret = false;
StorageData* storage = get_storage_by_file(file, app->storage);
if(storage == NULL) {
file->error_id = FSE_INVALID_PARAMETER;
} else {
FS_CALL(storage, file.truncate(storage, file));
}
return ret;
}
static bool storage_process_file_sync(Storage* app, File* file) {
bool ret = false;
StorageData* storage = get_storage_by_file(file, app->storage);
if(storage == NULL) {
file->error_id = FSE_INVALID_PARAMETER;
} else {
FS_CALL(storage, file.sync(storage, file));
}
return ret;
}
static uint64_t storage_process_file_size(Storage* app, File* file) {
uint64_t ret = 0;
StorageData* storage = get_storage_by_file(file, app->storage);
if(storage == NULL) {
file->error_id = FSE_INVALID_PARAMETER;
} else {
FS_CALL(storage, file.size(storage, file));
}
return ret;
}
static bool storage_process_file_eof(Storage* app, File* file) {
bool ret = false;
StorageData* storage = get_storage_by_file(file, app->storage);
if(storage == NULL) {
file->error_id = FSE_INVALID_PARAMETER;
} else {
FS_CALL(storage, file.eof(storage, file));
}
return ret;
}
/******************* Dir Functions *******************/
bool storage_process_dir_open(Storage* app, File* file, const char* path) {
bool ret = false;
StorageType type = storage_get_type_by_path(app, path);
StorageData* storage;
file->error_id = FSE_OK;
if(storage_type_is_not_valid(type)) {
file->error_id = FSE_INVALID_NAME;
} else {
storage = storage_get_storage_by_type(app, type);
string_t real_path;
string_init_set(real_path, path);
storage_path_change_to_real_storage(real_path, type);
if(storage_path_already_open(real_path, storage->files)) {
file->error_id = FSE_ALREADY_OPEN;
} else {
storage_push_storage_file(file, real_path, type, storage);
FS_CALL(storage, dir.open(storage, file, remove_vfs(path)));
}
string_clear(real_path);
}
return ret;
}
bool storage_process_dir_close(Storage* app, File* file) {
bool ret = false;
StorageData* storage = get_storage_by_file(file, app->storage);
if(storage == NULL) {
file->error_id = FSE_INVALID_PARAMETER;
} else {
FS_CALL(storage, dir.close(storage, file));
storage_pop_storage_file(file, storage);
StorageEvent event = {.type = StorageEventTypeDirClose};
furi_pubsub_publish(app->pubsub, &event);
}
return ret;
}
bool storage_process_dir_read(
Storage* app,
File* file,
FileInfo* fileinfo,
char* name,
const uint16_t name_length) {
bool ret = false;
StorageData* storage = get_storage_by_file(file, app->storage);
if(storage == NULL) {
file->error_id = FSE_INVALID_PARAMETER;
} else {
FS_CALL(storage, dir.read(storage, file, fileinfo, name, name_length));
}
return ret;
}
bool storage_process_dir_rewind(Storage* app, File* file) {
bool ret = false;
StorageData* storage = get_storage_by_file(file, app->storage);
if(storage == NULL) {
file->error_id = FSE_INVALID_PARAMETER;
} else {
FS_CALL(storage, dir.rewind(storage, file));
}
return ret;
}
/******************* Common FS Functions *******************/
static FS_Error storage_process_common_stat(Storage* app, const char* path, FileInfo* fileinfo) {
FS_Error ret = FSE_OK;
StorageType type = storage_get_type_by_path(app, path);
if(storage_type_is_not_valid(type)) {
ret = FSE_INVALID_NAME;
} else {
StorageData* storage = storage_get_storage_by_type(app, type);
FS_CALL(storage, common.stat(storage, remove_vfs(path), fileinfo));
}
return ret;
}
static FS_Error storage_process_common_remove(Storage* app, const char* path) {
FS_Error ret = FSE_OK;
StorageType type = storage_get_type_by_path(app, path);
string_t real_path;
string_init_set(real_path, path);
storage_path_change_to_real_storage(real_path, type);
do {
if(storage_type_is_not_valid(type)) {
ret = FSE_INVALID_NAME;
break;
}
StorageData* storage = storage_get_storage_by_type(app, type);
if(storage_path_already_open(real_path, storage->files)) {
ret = FSE_ALREADY_OPEN;
break;
}
FS_CALL(storage, common.remove(storage, remove_vfs(path)));
} while(false);
string_clear(real_path);
return ret;
}
static FS_Error storage_process_common_mkdir(Storage* app, const char* path) {
FS_Error ret = FSE_OK;
StorageType type = storage_get_type_by_path(app, path);
if(storage_type_is_not_valid(type)) {
ret = FSE_INVALID_NAME;
} else {
StorageData* storage = storage_get_storage_by_type(app, type);
FS_CALL(storage, common.mkdir(storage, remove_vfs(path)));
}
return ret;
}
static FS_Error storage_process_common_fs_info(
Storage* app,
const char* fs_path,
uint64_t* total_space,
uint64_t* free_space) {
FS_Error ret = FSE_OK;
StorageType type = storage_get_type_by_path(app, fs_path);
if(storage_type_is_not_valid(type)) {
ret = FSE_INVALID_NAME;
} else {
StorageData* storage = storage_get_storage_by_type(app, type);
FS_CALL(storage, common.fs_info(storage, remove_vfs(fs_path), total_space, free_space));
}
return ret;
}
/****************** Raw SD API ******************/
// TODO think about implementing a custom storage API to split that kind of api linkage
#include "storages/storage_ext.h"
static FS_Error storage_process_sd_format(Storage* app) {
FS_Error ret = FSE_OK;
if(storage_data_status(&app->storage[ST_EXT]) == StorageStatusNotReady) {
ret = FSE_NOT_READY;
} else {
ret = sd_format_card(&app->storage[ST_EXT]);
}
return ret;
}
static FS_Error storage_process_sd_unmount(Storage* app) {
FS_Error ret = FSE_OK;
if(storage_data_status(&app->storage[ST_EXT]) == StorageStatusNotReady) {
ret = FSE_NOT_READY;
} else {
sd_unmount_card(&app->storage[ST_EXT]);
}
return ret;
}
static FS_Error storage_process_sd_info(Storage* app, SDInfo* info) {
FS_Error ret = FSE_OK;
if(storage_data_status(&app->storage[ST_EXT]) == StorageStatusNotReady) {
ret = FSE_NOT_READY;
} else {
ret = sd_card_info(&app->storage[ST_EXT], info);
}
return ret;
}
static FS_Error storage_process_sd_status(Storage* app) {
FS_Error ret;
StorageStatus status = storage_data_status(&app->storage[ST_EXT]);
switch(status) {
case StorageStatusOK:
ret = FSE_OK;
break;
case StorageStatusNotReady:
ret = FSE_NOT_READY;
break;
default:
ret = FSE_INTERNAL;
break;
}
return ret;
}
/****************** API calls processing ******************/
void storage_process_message_internal(Storage* app, StorageMessage* message) {
switch(message->command) {
case StorageCommandFileOpen:
message->return_data->bool_value = storage_process_file_open(
app,
message->data->fopen.file,
message->data->fopen.path,
message->data->fopen.access_mode,
message->data->fopen.open_mode);
break;
case StorageCommandFileClose:
message->return_data->bool_value =
storage_process_file_close(app, message->data->fopen.file);
break;
case StorageCommandFileRead:
message->return_data->uint16_value = storage_process_file_read(
app,
message->data->fread.file,
message->data->fread.buff,
message->data->fread.bytes_to_read);
break;
case StorageCommandFileWrite:
message->return_data->uint16_value = storage_process_file_write(
app,
message->data->fwrite.file,
message->data->fwrite.buff,
message->data->fwrite.bytes_to_write);
break;
case StorageCommandFileSeek:
message->return_data->bool_value = storage_process_file_seek(
app,
message->data->fseek.file,
message->data->fseek.offset,
message->data->fseek.from_start);
break;
case StorageCommandFileTell:
message->return_data->uint64_value =
storage_process_file_tell(app, message->data->file.file);
break;
case StorageCommandFileTruncate:
message->return_data->bool_value =
storage_process_file_truncate(app, message->data->file.file);
break;
case StorageCommandFileSync:
message->return_data->bool_value =
storage_process_file_sync(app, message->data->file.file);
break;
case StorageCommandFileSize:
message->return_data->uint64_value =
storage_process_file_size(app, message->data->file.file);
break;
case StorageCommandFileEof:
message->return_data->bool_value = storage_process_file_eof(app, message->data->file.file);
break;
case StorageCommandDirOpen:
message->return_data->bool_value =
storage_process_dir_open(app, message->data->dopen.file, message->data->dopen.path);
break;
case StorageCommandDirClose:
message->return_data->bool_value =
storage_process_dir_close(app, message->data->file.file);
break;
case StorageCommandDirRead:
message->return_data->bool_value = storage_process_dir_read(
app,
message->data->dread.file,
message->data->dread.fileinfo,
message->data->dread.name,
message->data->dread.name_length);
break;
case StorageCommandDirRewind:
message->return_data->bool_value =
storage_process_dir_rewind(app, message->data->file.file);
break;
case StorageCommandCommonStat:
message->return_data->error_value = storage_process_common_stat(
app, message->data->cstat.path, message->data->cstat.fileinfo);
break;
case StorageCommandCommonRemove:
message->return_data->error_value =
storage_process_common_remove(app, message->data->path.path);
break;
case StorageCommandCommonMkDir:
message->return_data->error_value =
storage_process_common_mkdir(app, message->data->path.path);
break;
case StorageCommandCommonFSInfo:
message->return_data->error_value = storage_process_common_fs_info(
app,
message->data->cfsinfo.fs_path,
message->data->cfsinfo.total_space,
message->data->cfsinfo.free_space);
break;
case StorageCommandSDFormat:
message->return_data->error_value = storage_process_sd_format(app);
break;
case StorageCommandSDUnmount:
message->return_data->error_value = storage_process_sd_unmount(app);
break;
case StorageCommandSDInfo:
message->return_data->error_value =
storage_process_sd_info(app, message->data->sdinfo.info);
break;
case StorageCommandSDStatus:
message->return_data->error_value = storage_process_sd_status(app);
break;
}
furi_semaphore_release(message->semaphore);
}
void storage_process_message(Storage* app, StorageMessage* message) {
storage_process_message_internal(app, message);
}

View File

@@ -0,0 +1,16 @@
#pragma once
#include <furi.h>
#include "storage.h"
#include "storage_i.h"
#include "storage_message.h"
#include "storage_glue.h"
#ifdef __cplusplus
extern "C" {
#endif
void storage_process_message(Storage* app, StorageMessage* message);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,21 @@
#include "storage_sd_api.h"
const char* sd_api_get_fs_type_text(SDFsType fs_type) {
switch(fs_type) {
case(FST_FAT12):
return "FAT12";
break;
case(FST_FAT16):
return "FAT16";
break;
case(FST_FAT32):
return "FAT32";
break;
case(FST_EXFAT):
return "EXFAT";
break;
default:
return "UNKNOWN";
break;
}
}

View File

@@ -0,0 +1,33 @@
#pragma once
#include <furi.h>
#include "filesystem_api_defines.h"
#ifdef __cplusplus
extern "C" {
#endif
#define SD_LABEL_LENGTH 34
typedef enum {
FST_UNKNOWN,
FST_FAT12,
FST_FAT16,
FST_FAT32,
FST_EXFAT,
} SDFsType;
typedef struct {
SDFsType fs_type;
uint32_t kb_total;
uint32_t kb_free;
uint16_t cluster_size;
uint16_t sector_size;
char label[SD_LABEL_LENGTH];
FS_Error error;
} SDInfo;
const char* sd_api_get_fs_type_text(SDFsType fs_type);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,342 @@
#include <furi.h>
#include <furi_hal.h>
#include <storage/storage.h>
#define TAG "StorageTest"
#define BYTES_COUNT 16
#define TEST_STRING "TestDataStringProvidedByDiceRoll"
#define SEEK_OFFSET_FROM_START 10
#define SEEK_OFFSET_INCREASE 12
#define SEEK_OFFSET_SUM (SEEK_OFFSET_FROM_START + SEEK_OFFSET_INCREASE)
static void do_file_test(Storage* api, const char* path) {
File* file = storage_file_alloc(api);
bool result;
uint8_t bytes[BYTES_COUNT + 1];
uint8_t bytes_count;
uint64_t position;
uint64_t size;
FURI_LOG_I(TAG, "--------- FILE \"%s\" ---------", path);
// open
result = storage_file_open(file, path, FSAM_WRITE, FSOM_CREATE_ALWAYS);
if(result) {
FURI_LOG_I(TAG, "open");
} else {
FURI_LOG_E(TAG, "open, %s", storage_file_get_error_desc(file));
}
// write
bytes_count = storage_file_write(file, TEST_STRING, strlen(TEST_STRING));
if(bytes_count == 0) {
FURI_LOG_E(TAG, "write, %s", storage_file_get_error_desc(file));
} else {
FURI_LOG_I(TAG, "write");
}
// sync
result = storage_file_sync(file);
if(result) {
FURI_LOG_I(TAG, "sync");
} else {
FURI_LOG_E(TAG, "sync, %s", storage_file_get_error_desc(file));
}
// eof #1
result = storage_file_eof(file);
if(result) {
FURI_LOG_I(TAG, "eof #1");
} else {
FURI_LOG_E(TAG, "eof #1, %s", storage_file_get_error_desc(file));
}
// seek from start and tell
result = storage_file_seek(file, SEEK_OFFSET_FROM_START, true);
if(result) {
FURI_LOG_I(TAG, "seek #1");
} else {
FURI_LOG_E(TAG, "seek #1, %s", storage_file_get_error_desc(file));
}
position = storage_file_tell(file);
if(position != SEEK_OFFSET_FROM_START) {
FURI_LOG_E(TAG, "tell #1, %s", storage_file_get_error_desc(file));
} else {
FURI_LOG_I(TAG, "tell #1");
}
// size
size = storage_file_size(file);
if(size != strlen(TEST_STRING)) {
FURI_LOG_E(TAG, "size #1, %s", storage_file_get_error_desc(file));
} else {
FURI_LOG_I(TAG, "size #1");
}
// seek and tell
result = storage_file_seek(file, SEEK_OFFSET_INCREASE, false);
if(result) {
FURI_LOG_I(TAG, "seek #2");
} else {
FURI_LOG_E(TAG, "seek #2, %s", storage_file_get_error_desc(file));
}
position = storage_file_tell(file);
if(position != SEEK_OFFSET_SUM) {
FURI_LOG_E(TAG, "tell #2, %s", storage_file_get_error_desc(file));
} else {
FURI_LOG_I(TAG, "tell #2");
}
// eof #2
result = storage_file_eof(file);
if(!result) {
FURI_LOG_I(TAG, "eof #2");
} else {
FURI_LOG_E(TAG, "eof #2, %s", storage_file_get_error_desc(file));
}
// truncate
result = storage_file_truncate(file);
if(result) {
FURI_LOG_I(TAG, "truncate");
} else {
FURI_LOG_E(TAG, "truncate, %s", storage_file_get_error_desc(file));
}
size = storage_file_size(file);
if(size != SEEK_OFFSET_SUM) {
FURI_LOG_E(TAG, "size #2, %s", storage_file_get_error_desc(file));
} else {
FURI_LOG_I(TAG, "size #2");
}
// close
result = storage_file_close(file);
if(result) {
FURI_LOG_I(TAG, "close");
} else {
FURI_LOG_E(TAG, "close, error");
}
// open
result = storage_file_open(file, path, FSAM_READ, FSOM_OPEN_EXISTING);
if(result) {
FURI_LOG_I(TAG, "open");
} else {
FURI_LOG_E(TAG, "open, %s", storage_file_get_error_desc(file));
}
// read
memset(bytes, 0, BYTES_COUNT + 1);
bytes_count = storage_file_read(file, bytes, BYTES_COUNT);
if(bytes_count == 0) {
FURI_LOG_E(TAG, "read, %s", storage_file_get_error_desc(file));
} else {
if(memcmp(TEST_STRING, bytes, bytes_count) == 0) {
FURI_LOG_I(TAG, "read");
} else {
FURI_LOG_E(TAG, "read, garbage");
}
}
// close
result = storage_file_close(file);
if(result) {
FURI_LOG_I(TAG, "close");
} else {
FURI_LOG_E(TAG, "close, error");
}
storage_file_free(file);
}
static void do_dir_test(Storage* api, const char* path) {
File* file = storage_file_alloc(api);
bool result;
FURI_LOG_I(TAG, "--------- DIR \"%s\" ---------", path);
// open
result = storage_dir_open(file, path);
if(result) {
FURI_LOG_I(TAG, "open");
} else {
FURI_LOG_E(TAG, "open, %s", storage_file_get_error_desc(file));
}
// read
const uint8_t filename_size = 100;
char* filename = malloc(filename_size);
FileInfo fileinfo;
do {
result = storage_dir_read(file, &fileinfo, filename, filename_size);
if(result) {
if(strlen(filename)) {
FURI_LOG_I(
TAG,
"read #1, [%s]%s",
((fileinfo.flags & FSF_DIRECTORY) ? "D" : "F"),
filename);
}
} else if(storage_file_get_error(file) != FSE_NOT_EXIST) {
FURI_LOG_E(TAG, "read #1, %s", storage_file_get_error_desc(file));
break;
}
} while(result);
// rewind
result = storage_dir_rewind(file);
if(result) {
FURI_LOG_I(TAG, "rewind");
} else {
FURI_LOG_E(TAG, "rewind, %s", storage_file_get_error_desc(file));
}
// read
do {
result = storage_dir_read(file, &fileinfo, filename, filename_size);
if(result) {
if(strlen(filename)) {
FURI_LOG_I(
TAG,
"read #2, [%s]%s",
((fileinfo.flags & FSF_DIRECTORY) ? "D" : "F"),
filename);
}
} else if(storage_file_get_error(file) != FSE_NOT_EXIST) {
FURI_LOG_E(TAG, "read #2, %s", storage_file_get_error_desc(file));
break;
}
} while((strlen(filename)));
// close
result = storage_dir_close(file);
if(result) {
FURI_LOG_I(TAG, "close");
} else {
FURI_LOG_E(TAG, "close, error");
}
storage_file_free(file);
free(filename);
}
static void do_test_start(Storage* api, const char* path) {
string_t str_path;
string_init_printf(str_path, "%s/test-folder", path);
FURI_LOG_I(TAG, "--------- START \"%s\" ---------", path);
// mkdir
FS_Error result = storage_common_mkdir(api, string_get_cstr(str_path));
if(result == FSE_OK) {
FURI_LOG_I(TAG, "mkdir ok");
} else {
FURI_LOG_E(TAG, "mkdir, %s", storage_error_get_desc(result));
}
// stat
FileInfo fileinfo;
result = storage_common_stat(api, string_get_cstr(str_path), &fileinfo);
if(result == FSE_OK) {
if(fileinfo.flags & FSF_DIRECTORY) {
FURI_LOG_I(TAG, "stat #1 ok");
} else {
FURI_LOG_E(TAG, "stat #1, %s", storage_error_get_desc(result));
}
} else {
FURI_LOG_E(TAG, "stat #1, %s", storage_error_get_desc(result));
}
string_clear(str_path);
}
static void do_test_end(Storage* api, const char* path) {
uint64_t total_space;
uint64_t free_space;
string_t str_path_1;
string_t str_path_2;
string_init_printf(str_path_1, "%s/test-folder", path);
string_init_printf(str_path_2, "%s/test-folder2", path);
FURI_LOG_I(TAG, "--------- END \"%s\" ---------", path);
// fs stat
FS_Error result = storage_common_fs_info(api, path, &total_space, &free_space);
if(result == FSE_OK) {
uint32_t total_kb = total_space / 1024;
uint32_t free_kb = free_space / 1024;
FURI_LOG_I(TAG, "fs_info: total %luk, free %luk", total_kb, free_kb);
} else {
FURI_LOG_E(TAG, "fs_info, %s", storage_error_get_desc(result));
}
// rename #1
result = storage_common_rename(api, string_get_cstr(str_path_1), string_get_cstr(str_path_2));
if(result == FSE_OK) {
FURI_LOG_I(TAG, "rename #1 ok");
} else {
FURI_LOG_E(TAG, "rename #1, %s", storage_error_get_desc(result));
}
// remove #1
result = storage_common_remove(api, string_get_cstr(str_path_2));
if(result == FSE_OK) {
FURI_LOG_I(TAG, "remove #1 ok");
} else {
FURI_LOG_E(TAG, "remove #1, %s", storage_error_get_desc(result));
}
// rename #2
string_printf(str_path_1, "%s/test.txt", path);
string_printf(str_path_2, "%s/test2.txt", path);
result = storage_common_rename(api, string_get_cstr(str_path_1), string_get_cstr(str_path_2));
if(result == FSE_OK) {
FURI_LOG_I(TAG, "rename #2 ok");
} else {
FURI_LOG_E(TAG, "rename #2, %s", storage_error_get_desc(result));
}
// remove #2
result = storage_common_remove(api, string_get_cstr(str_path_2));
if(result == FSE_OK) {
FURI_LOG_I(TAG, "remove #2 ok");
} else {
FURI_LOG_E(TAG, "remove #2, %s", storage_error_get_desc(result));
}
string_clear(str_path_1);
string_clear(str_path_2);
}
int32_t storage_test_app(void* p) {
UNUSED(p);
Storage* api = furi_record_open(RECORD_STORAGE);
do_test_start(api, STORAGE_INT_PATH_PREFIX);
do_test_start(api, STORAGE_ANY_PATH_PREFIX);
do_test_start(api, STORAGE_EXT_PATH_PREFIX);
do_file_test(api, INT_PATH("test.txt"));
do_file_test(api, ANY_PATH("test.txt"));
do_file_test(api, EXT_PATH("test.txt"));
do_dir_test(api, STORAGE_INT_PATH_PREFIX);
do_dir_test(api, STORAGE_ANY_PATH_PREFIX);
do_dir_test(api, STORAGE_EXT_PATH_PREFIX);
do_test_end(api, STORAGE_INT_PATH_PREFIX);
do_test_end(api, STORAGE_ANY_PATH_PREFIX);
do_test_end(api, STORAGE_EXT_PATH_PREFIX);
while(true) {
furi_delay_ms(1000);
}
return 0;
}

View File

@@ -0,0 +1,82 @@
#include "sd_notify.h"
static const NotificationSequence sd_sequence_success = {
&message_green_255,
&message_delay_50,
&message_green_0,
&message_delay_50,
&message_green_255,
&message_delay_50,
&message_green_0,
&message_delay_50,
&message_green_255,
&message_delay_50,
&message_green_0,
&message_delay_50,
NULL,
};
static const NotificationSequence sd_sequence_error = {
&message_red_255,
&message_delay_50,
&message_red_0,
&message_delay_50,
&message_red_255,
&message_delay_50,
&message_red_0,
&message_delay_50,
&message_red_255,
&message_delay_50,
&message_red_0,
&message_delay_50,
NULL,
};
static const NotificationSequence sd_sequence_eject = {
&message_blue_255,
&message_delay_50,
&message_blue_0,
&message_delay_50,
&message_blue_255,
&message_delay_50,
&message_blue_0,
&message_delay_50,
&message_blue_255,
&message_delay_50,
&message_blue_0,
&message_delay_50,
NULL,
};
static const NotificationSequence sd_sequence_wait = {
&message_red_255,
&message_blue_255,
&message_do_not_reset,
NULL,
};
static const NotificationSequence sd_sequence_wait_off = {
&message_red_0,
&message_blue_0,
NULL,
};
void sd_notify_wait(NotificationApp* notifications) {
notification_message(notifications, &sd_sequence_wait);
}
void sd_notify_wait_off(NotificationApp* notifications) {
notification_message(notifications, &sd_sequence_wait_off);
}
void sd_notify_success(NotificationApp* notifications) {
notification_message(notifications, &sd_sequence_success);
}
void sd_notify_eject(NotificationApp* notifications) {
notification_message(notifications, &sd_sequence_eject);
}
void sd_notify_error(NotificationApp* notifications) {
notification_message(notifications, &sd_sequence_error);
}

View File

@@ -0,0 +1,17 @@
#pragma once
#include <furi.h>
#include <notification/notification_messages.h>
#ifdef __cplusplus
extern "C" {
#endif
void sd_notify_wait(NotificationApp* notifications);
void sd_notify_wait_off(NotificationApp* notifications);
void sd_notify_success(NotificationApp* notifications);
void sd_notify_eject(NotificationApp* notifications);
void sd_notify_error(NotificationApp* notifications);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,630 @@
#include "fatfs.h"
#include "../filesystem_api_internal.h"
#include "storage_ext.h"
#include <furi_hal.h>
#include "sd_notify.h"
#include <furi_hal_sd.h>
typedef FIL SDFile;
typedef DIR SDDir;
typedef FILINFO SDFileInfo;
typedef FRESULT SDError;
#define TAG "StorageExt"
/********************* Definitions ********************/
typedef struct {
FATFS* fs;
const char* path;
bool sd_was_present;
} SDData;
static FS_Error storage_ext_parse_error(SDError error);
/******************* Core Functions *******************/
static bool sd_mount_card(StorageData* storage, bool notify) {
bool result = false;
uint8_t counter = BSP_SD_MaxMountRetryCount();
uint8_t bsp_result;
SDData* sd_data = storage->data;
storage_data_lock(storage);
while(result == false && counter > 0 && hal_sd_detect()) {
if(notify) {
NotificationApp* notification = furi_record_open(RECORD_NOTIFICATION);
sd_notify_wait(notification);
furi_record_close(RECORD_NOTIFICATION);
}
if((counter % 2) == 0) {
// power reset sd card
bsp_result = BSP_SD_Init(true);
} else {
bsp_result = BSP_SD_Init(false);
}
if(bsp_result) {
// bsp error
storage->status = StorageStatusErrorInternal;
} else {
SDError status = f_mount(sd_data->fs, sd_data->path, 1);
if(status == FR_OK || status == FR_NO_FILESYSTEM) {
#ifndef FURI_RAM_EXEC
FATFS* fs;
uint32_t free_clusters;
status = f_getfree(sd_data->path, &free_clusters, &fs);
#endif
if(status == FR_OK || status == FR_NO_FILESYSTEM) {
result = true;
}
if(status == FR_OK) {
storage->status = StorageStatusOK;
} else if(status == FR_NO_FILESYSTEM) {
storage->status = StorageStatusNoFS;
} else {
storage->status = StorageStatusNotAccessible;
}
} else {
storage->status = StorageStatusNotMounted;
}
}
if(notify) {
NotificationApp* notification = furi_record_open(RECORD_NOTIFICATION);
sd_notify_wait_off(notification);
furi_record_close(RECORD_NOTIFICATION);
}
if(!result) {
furi_delay_ms(1000);
FURI_LOG_E(
TAG, "init cycle %d, error: %s", counter, storage_data_status_text(storage));
counter--;
}
}
storage_data_unlock(storage);
return result;
}
FS_Error sd_unmount_card(StorageData* storage) {
SDData* sd_data = storage->data;
SDError error;
storage_data_lock(storage);
storage->status = StorageStatusNotReady;
error = FR_DISK_ERR;
// TODO do i need to close the files?
f_mount(0, sd_data->path, 0);
storage_data_unlock(storage);
return storage_ext_parse_error(error);
}
FS_Error sd_format_card(StorageData* storage) {
#ifdef FURI_RAM_EXEC
UNUSED(storage);
return FSE_NOT_READY;
#else
uint8_t* work_area;
SDData* sd_data = storage->data;
SDError error;
storage_data_lock(storage);
work_area = malloc(_MAX_SS);
error = f_mkfs(sd_data->path, FM_ANY, 0, work_area, _MAX_SS);
free(work_area);
do {
storage->status = StorageStatusNotAccessible;
if(error != FR_OK) break;
storage->status = StorageStatusNoFS;
error = f_setlabel("Flipper SD");
if(error != FR_OK) break;
storage->status = StorageStatusNotMounted;
error = f_mount(sd_data->fs, sd_data->path, 1);
if(error != FR_OK) break;
storage->status = StorageStatusOK;
} while(false);
storage_data_unlock(storage);
return storage_ext_parse_error(error);
#endif
}
FS_Error sd_card_info(StorageData* storage, SDInfo* sd_info) {
#ifndef FURI_RAM_EXEC
uint32_t free_clusters, free_sectors, total_sectors;
FATFS* fs;
#endif
SDData* sd_data = storage->data;
SDError error;
// clean data
memset(sd_info, 0, sizeof(SDInfo));
// get fs info
storage_data_lock(storage);
error = f_getlabel(sd_data->path, sd_info->label, NULL);
if(error == FR_OK) {
#ifndef FURI_RAM_EXEC
error = f_getfree(sd_data->path, &free_clusters, &fs);
#endif
}
storage_data_unlock(storage);
if(error == FR_OK) {
// calculate size
#ifndef FURI_RAM_EXEC
total_sectors = (fs->n_fatent - 2) * fs->csize;
free_sectors = free_clusters * fs->csize;
#endif
uint16_t sector_size = _MAX_SS;
#if _MAX_SS != _MIN_SS
sector_size = fs->ssize;
#endif
#ifdef FURI_RAM_EXEC
sd_info->fs_type = 0;
sd_info->kb_total = 0;
sd_info->kb_free = 0;
sd_info->cluster_size = 512;
sd_info->sector_size = sector_size;
#else
sd_info->fs_type = fs->fs_type;
switch(fs->fs_type) {
case FS_FAT12:
sd_info->fs_type = FST_FAT12;
break;
case FS_FAT16:
sd_info->fs_type = FST_FAT16;
break;
case FS_FAT32:
sd_info->fs_type = FST_FAT32;
break;
case FS_EXFAT:
sd_info->fs_type = FST_EXFAT;
break;
default:
sd_info->fs_type = FST_UNKNOWN;
break;
}
sd_info->kb_total = total_sectors / 1024 * sector_size;
sd_info->kb_free = free_sectors / 1024 * sector_size;
sd_info->cluster_size = fs->csize;
sd_info->sector_size = sector_size;
#endif
}
return storage_ext_parse_error(error);
}
static void storage_ext_tick_internal(StorageData* storage, bool notify) {
SDData* sd_data = storage->data;
if(sd_data->sd_was_present) {
if(hal_sd_detect()) {
FURI_LOG_I(TAG, "card detected");
sd_mount_card(storage, notify);
if(storage->status != StorageStatusOK) {
FURI_LOG_E(TAG, "sd init error: %s", storage_data_status_text(storage));
if(notify) {
NotificationApp* notification = furi_record_open(RECORD_NOTIFICATION);
sd_notify_error(notification);
furi_record_close(RECORD_NOTIFICATION);
}
} else {
FURI_LOG_I(TAG, "card mounted");
if(notify) {
NotificationApp* notification = furi_record_open(RECORD_NOTIFICATION);
sd_notify_success(notification);
furi_record_close(RECORD_NOTIFICATION);
}
}
sd_data->sd_was_present = false;
if(!hal_sd_detect()) {
FURI_LOG_I(TAG, "card removed while mounting");
sd_unmount_card(storage);
sd_data->sd_was_present = true;
}
}
} else {
if(!hal_sd_detect()) {
FURI_LOG_I(TAG, "card removed");
sd_data->sd_was_present = true;
sd_unmount_card(storage);
if(notify) {
NotificationApp* notification = furi_record_open(RECORD_NOTIFICATION);
sd_notify_eject(notification);
furi_record_close(RECORD_NOTIFICATION);
}
}
}
}
static void storage_ext_tick(StorageData* storage) {
storage_ext_tick_internal(storage, true);
}
/****************** Common Functions ******************/
static FS_Error storage_ext_parse_error(SDError error) {
FS_Error result;
switch(error) {
case FR_OK:
result = FSE_OK;
break;
case FR_NOT_READY:
result = FSE_NOT_READY;
break;
case FR_NO_FILE:
case FR_NO_PATH:
case FR_NO_FILESYSTEM:
result = FSE_NOT_EXIST;
break;
case FR_EXIST:
result = FSE_EXIST;
break;
case FR_INVALID_NAME:
result = FSE_INVALID_NAME;
break;
case FR_INVALID_OBJECT:
case FR_INVALID_PARAMETER:
result = FSE_INVALID_PARAMETER;
break;
case FR_DENIED:
result = FSE_DENIED;
break;
default:
result = FSE_INTERNAL;
break;
}
return result;
}
/******************* File Functions *******************/
static bool storage_ext_file_open(
void* ctx,
File* file,
const char* path,
FS_AccessMode access_mode,
FS_OpenMode open_mode) {
StorageData* storage = ctx;
uint8_t _mode = 0;
if(access_mode & FSAM_READ) _mode |= FA_READ;
if(access_mode & FSAM_WRITE) _mode |= FA_WRITE;
if(open_mode & FSOM_OPEN_EXISTING) _mode |= FA_OPEN_EXISTING;
if(open_mode & FSOM_OPEN_ALWAYS) _mode |= FA_OPEN_ALWAYS;
if(open_mode & FSOM_OPEN_APPEND) _mode |= FA_OPEN_APPEND;
if(open_mode & FSOM_CREATE_NEW) _mode |= FA_CREATE_NEW;
if(open_mode & FSOM_CREATE_ALWAYS) _mode |= FA_CREATE_ALWAYS;
SDFile* file_data = malloc(sizeof(SDFile));
storage_set_storage_file_data(file, file_data, storage);
file->internal_error_id = f_open(file_data, path, _mode);
file->error_id = storage_ext_parse_error(file->internal_error_id);
return (file->error_id == FSE_OK);
}
static bool storage_ext_file_close(void* ctx, File* file) {
StorageData* storage = ctx;
SDFile* file_data = storage_get_storage_file_data(file, storage);
file->internal_error_id = f_close(file_data);
file->error_id = storage_ext_parse_error(file->internal_error_id);
free(file_data);
return (file->error_id == FSE_OK);
}
static uint16_t
storage_ext_file_read(void* ctx, File* file, void* buff, uint16_t const bytes_to_read) {
StorageData* storage = ctx;
SDFile* file_data = storage_get_storage_file_data(file, storage);
uint16_t bytes_read = 0;
file->internal_error_id = f_read(file_data, buff, bytes_to_read, &bytes_read);
file->error_id = storage_ext_parse_error(file->internal_error_id);
return bytes_read;
}
static uint16_t
storage_ext_file_write(void* ctx, File* file, const void* buff, uint16_t const bytes_to_write) {
#ifdef FURI_RAM_EXEC
UNUSED(ctx);
UNUSED(file);
UNUSED(buff);
UNUSED(bytes_to_write);
return FSE_NOT_READY;
#else
StorageData* storage = ctx;
SDFile* file_data = storage_get_storage_file_data(file, storage);
uint16_t bytes_written = 0;
file->internal_error_id = f_write(file_data, buff, bytes_to_write, &bytes_written);
file->error_id = storage_ext_parse_error(file->internal_error_id);
return bytes_written;
#endif
}
static bool
storage_ext_file_seek(void* ctx, File* file, const uint32_t offset, const bool from_start) {
StorageData* storage = ctx;
SDFile* file_data = storage_get_storage_file_data(file, storage);
if(from_start) {
file->internal_error_id = f_lseek(file_data, offset);
} else {
uint64_t position = f_tell(file_data);
position += offset;
file->internal_error_id = f_lseek(file_data, position);
}
file->error_id = storage_ext_parse_error(file->internal_error_id);
return (file->error_id == FSE_OK);
}
static uint64_t storage_ext_file_tell(void* ctx, File* file) {
StorageData* storage = ctx;
SDFile* file_data = storage_get_storage_file_data(file, storage);
uint64_t position = 0;
position = f_tell(file_data);
file->error_id = FSE_OK;
return position;
}
static bool storage_ext_file_truncate(void* ctx, File* file) {
#ifdef FURI_RAM_EXEC
UNUSED(ctx);
UNUSED(file);
return FSE_NOT_READY;
#else
StorageData* storage = ctx;
SDFile* file_data = storage_get_storage_file_data(file, storage);
file->internal_error_id = f_truncate(file_data);
file->error_id = storage_ext_parse_error(file->internal_error_id);
return (file->error_id == FSE_OK);
#endif
}
static bool storage_ext_file_sync(void* ctx, File* file) {
#ifdef FURI_RAM_EXEC
UNUSED(ctx);
UNUSED(file);
return FSE_NOT_READY;
#else
StorageData* storage = ctx;
SDFile* file_data = storage_get_storage_file_data(file, storage);
file->internal_error_id = f_sync(file_data);
file->error_id = storage_ext_parse_error(file->internal_error_id);
return (file->error_id == FSE_OK);
#endif
}
static uint64_t storage_ext_file_size(void* ctx, File* file) {
StorageData* storage = ctx;
SDFile* file_data = storage_get_storage_file_data(file, storage);
uint64_t size = 0;
size = f_size(file_data);
file->error_id = FSE_OK;
return size;
}
static bool storage_ext_file_eof(void* ctx, File* file) {
StorageData* storage = ctx;
SDFile* file_data = storage_get_storage_file_data(file, storage);
bool eof = f_eof(file_data);
file->internal_error_id = 0;
file->error_id = FSE_OK;
return eof;
}
/******************* Dir Functions *******************/
static bool storage_ext_dir_open(void* ctx, File* file, const char* path) {
StorageData* storage = ctx;
SDDir* file_data = malloc(sizeof(SDDir));
storage_set_storage_file_data(file, file_data, storage);
file->internal_error_id = f_opendir(file_data, path);
file->error_id = storage_ext_parse_error(file->internal_error_id);
return (file->error_id == FSE_OK);
}
static bool storage_ext_dir_close(void* ctx, File* file) {
StorageData* storage = ctx;
SDDir* file_data = storage_get_storage_file_data(file, storage);
file->internal_error_id = f_closedir(file_data);
file->error_id = storage_ext_parse_error(file->internal_error_id);
free(file_data);
return (file->error_id == FSE_OK);
}
static bool storage_ext_dir_read(
void* ctx,
File* file,
FileInfo* fileinfo,
char* name,
const uint16_t name_length) {
StorageData* storage = ctx;
SDDir* file_data = storage_get_storage_file_data(file, storage);
SDFileInfo _fileinfo;
file->internal_error_id = f_readdir(file_data, &_fileinfo);
file->error_id = storage_ext_parse_error(file->internal_error_id);
if(fileinfo != NULL) {
fileinfo->size = _fileinfo.fsize;
fileinfo->flags = 0;
if(_fileinfo.fattrib & AM_DIR) fileinfo->flags |= FSF_DIRECTORY;
}
if(name != NULL) {
snprintf(name, name_length, "%s", _fileinfo.fname);
}
if(_fileinfo.fname[0] == 0) {
file->error_id = FSE_NOT_EXIST;
}
return (file->error_id == FSE_OK);
}
static bool storage_ext_dir_rewind(void* ctx, File* file) {
StorageData* storage = ctx;
SDDir* file_data = storage_get_storage_file_data(file, storage);
file->internal_error_id = f_readdir(file_data, NULL);
file->error_id = storage_ext_parse_error(file->internal_error_id);
return (file->error_id == FSE_OK);
}
/******************* Common FS Functions *******************/
static FS_Error storage_ext_common_stat(void* ctx, const char* path, FileInfo* fileinfo) {
UNUSED(ctx);
SDFileInfo _fileinfo;
SDError result = f_stat(path, &_fileinfo);
if(fileinfo != NULL) {
fileinfo->size = _fileinfo.fsize;
fileinfo->flags = 0;
if(_fileinfo.fattrib & AM_DIR) fileinfo->flags |= FSF_DIRECTORY;
}
return storage_ext_parse_error(result);
}
static FS_Error storage_ext_common_remove(void* ctx, const char* path) {
UNUSED(ctx);
#ifdef FURI_RAM_EXEC
UNUSED(path);
return FSE_NOT_READY;
#else
SDError result = f_unlink(path);
return storage_ext_parse_error(result);
#endif
}
static FS_Error storage_ext_common_mkdir(void* ctx, const char* path) {
UNUSED(ctx);
#ifdef FURI_RAM_EXEC
UNUSED(path);
return FSE_NOT_READY;
#else
SDError result = f_mkdir(path);
return storage_ext_parse_error(result);
#endif
}
static FS_Error storage_ext_common_fs_info(
void* ctx,
const char* fs_path,
uint64_t* total_space,
uint64_t* free_space) {
UNUSED(fs_path);
#ifdef FURI_RAM_EXEC
UNUSED(ctx);
UNUSED(total_space);
UNUSED(free_space);
return FSE_NOT_READY;
#else
StorageData* storage = ctx;
SDData* sd_data = storage->data;
DWORD free_clusters;
FATFS* fs;
SDError fresult = f_getfree(sd_data->path, &free_clusters, &fs);
if((FRESULT)fresult == FR_OK) {
uint32_t total_sectors = (fs->n_fatent - 2) * fs->csize;
uint32_t free_sectors = free_clusters * fs->csize;
uint16_t sector_size = _MAX_SS;
#if _MAX_SS != _MIN_SS
sector_size = fs->ssize;
#endif
if(total_space != NULL) {
*total_space = (uint64_t)total_sectors * (uint64_t)sector_size;
}
if(free_space != NULL) {
*free_space = (uint64_t)free_sectors * (uint64_t)sector_size;
}
}
return storage_ext_parse_error(fresult);
#endif
}
/******************* Init Storage *******************/
static const FS_Api fs_api = {
.file =
{
.open = storage_ext_file_open,
.close = storage_ext_file_close,
.read = storage_ext_file_read,
.write = storage_ext_file_write,
.seek = storage_ext_file_seek,
.tell = storage_ext_file_tell,
.truncate = storage_ext_file_truncate,
.size = storage_ext_file_size,
.sync = storage_ext_file_sync,
.eof = storage_ext_file_eof,
},
.dir =
{
.open = storage_ext_dir_open,
.close = storage_ext_dir_close,
.read = storage_ext_dir_read,
.rewind = storage_ext_dir_rewind,
},
.common =
{
.stat = storage_ext_common_stat,
.mkdir = storage_ext_common_mkdir,
.remove = storage_ext_common_remove,
.fs_info = storage_ext_common_fs_info,
},
};
void storage_ext_init(StorageData* storage) {
SDData* sd_data = malloc(sizeof(SDData));
sd_data->fs = &USERFatFS;
sd_data->path = "0:/";
sd_data->sd_was_present = true;
storage->data = sd_data;
storage->api.tick = storage_ext_tick;
storage->fs_api = &fs_api;
hal_sd_detect_init();
// do not notify on first launch, notifications app is waiting for our thread to read settings
storage_ext_tick_internal(storage, false);
}

View File

@@ -0,0 +1,16 @@
#pragma once
#include <furi.h>
#include "../storage_glue.h"
#include "../storage_sd_api.h"
#ifdef __cplusplus
extern "C" {
#endif
void storage_ext_init(StorageData* storage);
FS_Error sd_unmount_card(StorageData* storage);
FS_Error sd_format_card(StorageData* storage);
FS_Error sd_card_info(StorageData* storage, SDInfo* sd_info);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,761 @@
#include "storage_int.h"
#include <lfs.h>
#include <furi_hal.h>
#include <toolbox/path.h>
#define TAG "StorageInt"
#define STORAGE_PATH STORAGE_INT_PATH_PREFIX
#define LFS_CLEAN_FINGERPRINT 0
/* When less than LFS_RESERVED_PAGES_COUNT are left free, creation &
* modification of non-dot files is restricted */
#define LFS_RESERVED_PAGES_COUNT 3
typedef struct {
const size_t start_address;
const size_t start_page;
struct lfs_config config;
lfs_t lfs;
} LFSData;
typedef struct {
void* data;
bool open;
} LFSHandle;
static LFSHandle* lfs_handle_alloc_file() {
LFSHandle* handle = malloc(sizeof(LFSHandle));
handle->data = malloc(sizeof(lfs_file_t));
return handle;
}
static LFSHandle* lfs_handle_alloc_dir() {
LFSHandle* handle = malloc(sizeof(LFSHandle));
handle->data = malloc(sizeof(lfs_dir_t));
return handle;
}
/* INTERNALS */
static lfs_dir_t* lfs_handle_get_dir(LFSHandle* handle) {
return handle->data;
}
static lfs_file_t* lfs_handle_get_file(LFSHandle* handle) {
return handle->data;
}
static void lfs_handle_free(LFSHandle* handle) {
free(handle->data);
free(handle);
}
static void lfs_handle_set_open(LFSHandle* handle) {
handle->open = true;
}
static bool lfs_handle_is_open(LFSHandle* handle) {
return handle->open;
}
static lfs_t* lfs_get_from_storage(StorageData* storage) {
return &((LFSData*)storage->data)->lfs;
}
static LFSData* lfs_data_get_from_storage(StorageData* storage) {
return (LFSData*)storage->data;
}
static int storage_int_device_read(
const struct lfs_config* c,
lfs_block_t block,
lfs_off_t off,
void* buffer,
lfs_size_t size) {
LFSData* lfs_data = c->context;
size_t address = lfs_data->start_address + block * c->block_size + off;
FURI_LOG_T(
TAG,
"Device read: block %d, off %d, buffer: %p, size %d, translated address: %p",
block,
off,
buffer,
size,
address);
memcpy(buffer, (void*)address, size);
return 0;
}
static int storage_int_device_prog(
const struct lfs_config* c,
lfs_block_t block,
lfs_off_t off,
const void* buffer,
lfs_size_t size) {
LFSData* lfs_data = c->context;
size_t address = lfs_data->start_address + block * c->block_size + off;
FURI_LOG_T(
TAG,
"Device prog: block %d, off %d, buffer: %p, size %d, translated address: %p",
block,
off,
buffer,
size,
address);
int ret = 0;
while(size > 0) {
if(!furi_hal_flash_write_dword(address, *(uint64_t*)buffer)) {
ret = -1;
break;
}
address += c->prog_size;
buffer += c->prog_size;
size -= c->prog_size;
}
return ret;
}
static int storage_int_device_erase(const struct lfs_config* c, lfs_block_t block) {
LFSData* lfs_data = c->context;
size_t page = lfs_data->start_page + block;
FURI_LOG_D(TAG, "Device erase: page %d, translated page: %x", block, page);
if(furi_hal_flash_erase(page)) {
return 0;
} else {
return -1;
}
}
static int storage_int_device_sync(const struct lfs_config* c) {
UNUSED(c);
FURI_LOG_D(TAG, "Device sync: skipping, cause ");
return 0;
}
static LFSData* storage_int_lfs_data_alloc() {
LFSData* lfs_data = malloc(sizeof(LFSData));
// Internal storage start address
*(size_t*)(&lfs_data->start_address) = furi_hal_flash_get_free_page_start_address();
*(size_t*)(&lfs_data->start_page) =
(lfs_data->start_address - furi_hal_flash_get_base()) / furi_hal_flash_get_page_size();
// LFS configuration
// Glue and context
lfs_data->config.context = lfs_data;
lfs_data->config.read = storage_int_device_read;
lfs_data->config.prog = storage_int_device_prog;
lfs_data->config.erase = storage_int_device_erase;
lfs_data->config.sync = storage_int_device_sync;
// Block device description
lfs_data->config.read_size = furi_hal_flash_get_read_block_size();
lfs_data->config.prog_size = furi_hal_flash_get_write_block_size();
lfs_data->config.block_size = furi_hal_flash_get_page_size();
lfs_data->config.block_count = furi_hal_flash_get_free_page_count();
lfs_data->config.block_cycles = furi_hal_flash_get_cycles_count();
lfs_data->config.cache_size = 16;
lfs_data->config.lookahead_size = 16;
return lfs_data;
};
// Returns true if fingerprint was invalid and LFS reformatting is needed
static bool storage_int_check_and_set_fingerprint(LFSData* lfs_data) {
bool value = false;
uint32_t os_fingerprint = 0;
os_fingerprint |= ((lfs_data->start_page & 0xFF) << 0);
os_fingerprint |= ((lfs_data->config.block_count & 0xFF) << 8);
os_fingerprint |= ((LFS_DISK_VERSION_MAJOR & 0xFFFF) << 16);
uint32_t rtc_fingerprint = furi_hal_rtc_get_register(FuriHalRtcRegisterLfsFingerprint);
if(rtc_fingerprint == LFS_CLEAN_FINGERPRINT) {
FURI_LOG_I(TAG, "Storing LFS fingerprint in RTC");
furi_hal_rtc_set_register(FuriHalRtcRegisterLfsFingerprint, os_fingerprint);
} else if(rtc_fingerprint != os_fingerprint) {
FURI_LOG_E(TAG, "LFS fingerprint mismatch");
furi_hal_rtc_set_register(FuriHalRtcRegisterLfsFingerprint, os_fingerprint);
value = true;
}
return value;
}
static void storage_int_lfs_mount(LFSData* lfs_data, StorageData* storage) {
int err;
lfs_t* lfs = &lfs_data->lfs;
bool was_fingerprint_outdated = storage_int_check_and_set_fingerprint(lfs_data);
bool need_format = furi_hal_rtc_is_flag_set(FuriHalRtcFlagFactoryReset) ||
was_fingerprint_outdated;
if(need_format) {
// Format storage
err = lfs_format(lfs, &lfs_data->config);
if(err == 0) {
FURI_LOG_I(TAG, "Factory reset: Format successful, trying to mount");
furi_hal_rtc_reset_flag(FuriHalRtcFlagFactoryReset);
err = lfs_mount(lfs, &lfs_data->config);
if(err == 0) {
FURI_LOG_I(TAG, "Factory reset: Mounted");
storage->status = StorageStatusOK;
} else {
FURI_LOG_E(TAG, "Factory reset: Mount after format failed");
storage->status = StorageStatusNotMounted;
}
} else {
FURI_LOG_E(TAG, "Factory reset: Format failed");
storage->status = StorageStatusNoFS;
}
} else {
// Normal
err = lfs_mount(lfs, &lfs_data->config);
if(err == 0) {
FURI_LOG_I(TAG, "Mounted");
storage->status = StorageStatusOK;
} else {
FURI_LOG_E(TAG, "Mount failed, formatting");
err = lfs_format(lfs, &lfs_data->config);
if(err == 0) {
FURI_LOG_I(TAG, "Format successful, trying to mount");
err = lfs_mount(lfs, &lfs_data->config);
if(err == 0) {
FURI_LOG_I(TAG, "Mounted");
storage->status = StorageStatusOK;
} else {
FURI_LOG_E(TAG, "Mount after format failed");
storage->status = StorageStatusNotMounted;
}
} else {
FURI_LOG_E(TAG, "Format failed");
storage->status = StorageStatusNoFS;
}
}
}
}
/****************** Common Functions ******************/
static FS_Error storage_int_parse_error(int error) {
FS_Error result = FSE_INTERNAL;
if(error >= LFS_ERR_OK) {
result = FSE_OK;
} else {
switch(error) {
case LFS_ERR_IO:
result = FSE_INTERNAL;
break;
case LFS_ERR_CORRUPT:
result = FSE_INTERNAL;
break;
case LFS_ERR_NOENT:
result = FSE_NOT_EXIST;
break;
case LFS_ERR_EXIST:
result = FSE_EXIST;
break;
case LFS_ERR_NOTDIR:
result = FSE_INVALID_NAME;
break;
case LFS_ERR_ISDIR:
result = FSE_INVALID_NAME;
break;
case LFS_ERR_NOTEMPTY:
result = FSE_DENIED;
break;
case LFS_ERR_BADF:
result = FSE_INVALID_NAME;
break;
case LFS_ERR_FBIG:
result = FSE_INTERNAL;
break;
case LFS_ERR_INVAL:
result = FSE_INVALID_PARAMETER;
break;
case LFS_ERR_NOSPC:
result = FSE_INTERNAL;
break;
case LFS_ERR_NOMEM:
result = FSE_INTERNAL;
break;
case LFS_ERR_NOATTR:
result = FSE_INVALID_PARAMETER;
break;
case LFS_ERR_NAMETOOLONG:
result = FSE_INVALID_NAME;
break;
default:
break;
}
}
return result;
}
/* Returns false if less than reserved space is left free */
static bool storage_int_check_for_free_space(StorageData* storage) {
LFSData* lfs_data = lfs_data_get_from_storage(storage);
lfs_ssize_t result = lfs_fs_size(lfs_get_from_storage(storage));
if(result >= 0) {
lfs_size_t free_space =
(lfs_data->config.block_count - result) * lfs_data->config.block_size;
return (free_space > LFS_RESERVED_PAGES_COUNT * furi_hal_flash_get_page_size());
}
return false;
}
/******************* File Functions *******************/
static bool storage_int_file_open(
void* ctx,
File* file,
const char* path,
FS_AccessMode access_mode,
FS_OpenMode open_mode) {
StorageData* storage = ctx;
lfs_t* lfs = lfs_get_from_storage(storage);
bool enough_free_space = storage_int_check_for_free_space(storage);
int flags = 0;
if(access_mode & FSAM_READ) flags |= LFS_O_RDONLY;
if(access_mode & FSAM_WRITE) flags |= LFS_O_WRONLY;
if(open_mode & FSOM_OPEN_EXISTING) flags |= 0;
if(open_mode & FSOM_OPEN_ALWAYS) flags |= LFS_O_CREAT;
if(open_mode & FSOM_OPEN_APPEND) flags |= LFS_O_CREAT | LFS_O_APPEND;
if(open_mode & FSOM_CREATE_NEW) flags |= LFS_O_CREAT | LFS_O_EXCL;
if(open_mode & FSOM_CREATE_ALWAYS) flags |= LFS_O_CREAT | LFS_O_TRUNC;
LFSHandle* handle = lfs_handle_alloc_file();
storage_set_storage_file_data(file, handle, storage);
if(!enough_free_space) {
string_t filename;
string_init(filename);
path_extract_basename(path, filename);
bool is_dot_file = (!string_empty_p(filename) && (string_get_char(filename, 0) == '.'));
string_clear(filename);
/* Restrict write & creation access to all non-dot files */
if(!is_dot_file && (flags & (LFS_O_CREAT | LFS_O_WRONLY))) {
file->internal_error_id = LFS_ERR_NOSPC;
file->error_id = FSE_DENIED;
FURI_LOG_W(TAG, "Denied access to '%s': no free space", path);
return false;
}
}
file->internal_error_id = lfs_file_open(lfs, lfs_handle_get_file(handle), path, flags);
if(file->internal_error_id >= LFS_ERR_OK) {
lfs_handle_set_open(handle);
}
file->error_id = storage_int_parse_error(file->internal_error_id);
return (file->error_id == FSE_OK);
}
static bool storage_int_file_close(void* ctx, File* file) {
StorageData* storage = ctx;
lfs_t* lfs = lfs_get_from_storage(storage);
LFSHandle* handle = storage_get_storage_file_data(file, storage);
if(lfs_handle_is_open(handle)) {
file->internal_error_id = lfs_file_close(lfs, lfs_handle_get_file(handle));
} else {
file->internal_error_id = LFS_ERR_BADF;
}
file->error_id = storage_int_parse_error(file->internal_error_id);
lfs_handle_free(handle);
return (file->error_id == FSE_OK);
}
static uint16_t
storage_int_file_read(void* ctx, File* file, void* buff, uint16_t const bytes_to_read) {
StorageData* storage = ctx;
lfs_t* lfs = lfs_get_from_storage(storage);
LFSHandle* handle = storage_get_storage_file_data(file, storage);
uint16_t bytes_read = 0;
if(lfs_handle_is_open(handle)) {
file->internal_error_id =
lfs_file_read(lfs, lfs_handle_get_file(handle), buff, bytes_to_read);
} else {
file->internal_error_id = LFS_ERR_BADF;
}
file->error_id = storage_int_parse_error(file->internal_error_id);
if(file->error_id == FSE_OK) {
bytes_read = file->internal_error_id;
file->internal_error_id = 0;
}
return bytes_read;
}
static uint16_t
storage_int_file_write(void* ctx, File* file, const void* buff, uint16_t const bytes_to_write) {
StorageData* storage = ctx;
lfs_t* lfs = lfs_get_from_storage(storage);
LFSHandle* handle = storage_get_storage_file_data(file, storage);
uint16_t bytes_written = 0;
if(lfs_handle_is_open(handle)) {
file->internal_error_id =
lfs_file_write(lfs, lfs_handle_get_file(handle), buff, bytes_to_write);
} else {
file->internal_error_id = LFS_ERR_BADF;
}
file->error_id = storage_int_parse_error(file->internal_error_id);
if(file->error_id == FSE_OK) {
bytes_written = file->internal_error_id;
file->internal_error_id = 0;
}
return bytes_written;
}
static bool
storage_int_file_seek(void* ctx, File* file, const uint32_t offset, const bool from_start) {
StorageData* storage = ctx;
lfs_t* lfs = lfs_get_from_storage(storage);
LFSHandle* handle = storage_get_storage_file_data(file, storage);
if(lfs_handle_is_open(handle)) {
if(from_start) {
file->internal_error_id =
lfs_file_seek(lfs, lfs_handle_get_file(handle), offset, LFS_SEEK_SET);
} else {
file->internal_error_id =
lfs_file_seek(lfs, lfs_handle_get_file(handle), offset, LFS_SEEK_CUR);
}
} else {
file->internal_error_id = LFS_ERR_BADF;
}
file->error_id = storage_int_parse_error(file->internal_error_id);
return (file->error_id == FSE_OK);
}
static uint64_t storage_int_file_tell(void* ctx, File* file) {
StorageData* storage = ctx;
lfs_t* lfs = lfs_get_from_storage(storage);
LFSHandle* handle = storage_get_storage_file_data(file, storage);
if(lfs_handle_is_open(handle)) {
file->internal_error_id = lfs_file_tell(lfs, lfs_handle_get_file(handle));
} else {
file->internal_error_id = LFS_ERR_BADF;
}
file->error_id = storage_int_parse_error(file->internal_error_id);
int32_t position = 0;
if(file->error_id == FSE_OK) {
position = file->internal_error_id;
file->internal_error_id = 0;
}
return position;
}
static bool storage_int_file_truncate(void* ctx, File* file) {
StorageData* storage = ctx;
lfs_t* lfs = lfs_get_from_storage(storage);
LFSHandle* handle = storage_get_storage_file_data(file, storage);
if(lfs_handle_is_open(handle)) {
file->internal_error_id = lfs_file_tell(lfs, lfs_handle_get_file(handle));
file->error_id = storage_int_parse_error(file->internal_error_id);
if(file->error_id == FSE_OK) {
uint32_t position = file->internal_error_id;
file->internal_error_id =
lfs_file_truncate(lfs, lfs_handle_get_file(handle), position);
file->error_id = storage_int_parse_error(file->internal_error_id);
}
} else {
file->internal_error_id = LFS_ERR_BADF;
file->error_id = storage_int_parse_error(file->internal_error_id);
}
return (file->error_id == FSE_OK);
}
static bool storage_int_file_sync(void* ctx, File* file) {
StorageData* storage = ctx;
lfs_t* lfs = lfs_get_from_storage(storage);
LFSHandle* handle = storage_get_storage_file_data(file, storage);
if(lfs_handle_is_open(handle)) {
file->internal_error_id = lfs_file_sync(lfs, lfs_handle_get_file(handle));
} else {
file->internal_error_id = LFS_ERR_BADF;
}
file->error_id = storage_int_parse_error(file->internal_error_id);
return (file->error_id == FSE_OK);
}
static uint64_t storage_int_file_size(void* ctx, File* file) {
StorageData* storage = ctx;
lfs_t* lfs = lfs_get_from_storage(storage);
LFSHandle* handle = storage_get_storage_file_data(file, storage);
if(lfs_handle_is_open(handle)) {
file->internal_error_id = lfs_file_size(lfs, lfs_handle_get_file(handle));
} else {
file->internal_error_id = LFS_ERR_BADF;
}
file->error_id = storage_int_parse_error(file->internal_error_id);
uint32_t size = 0;
if(file->error_id == FSE_OK) {
size = file->internal_error_id;
file->internal_error_id = 0;
}
return size;
}
static bool storage_int_file_eof(void* ctx, File* file) {
StorageData* storage = ctx;
lfs_t* lfs = lfs_get_from_storage(storage);
LFSHandle* handle = storage_get_storage_file_data(file, storage);
bool eof = true;
if(lfs_handle_is_open(handle)) {
int32_t position = lfs_file_tell(lfs, lfs_handle_get_file(handle));
int32_t size = lfs_file_size(lfs, lfs_handle_get_file(handle));
if(position < 0) {
file->internal_error_id = position;
} else if(size < 0) {
file->internal_error_id = size;
} else {
file->internal_error_id = LFS_ERR_OK;
eof = (position >= size);
}
} else {
file->internal_error_id = LFS_ERR_BADF;
}
file->error_id = storage_int_parse_error(file->internal_error_id);
return eof;
}
/******************* Dir Functions *******************/
static bool storage_int_dir_open(void* ctx, File* file, const char* path) {
StorageData* storage = ctx;
lfs_t* lfs = lfs_get_from_storage(storage);
LFSHandle* handle = lfs_handle_alloc_dir();
storage_set_storage_file_data(file, handle, storage);
file->internal_error_id = lfs_dir_open(lfs, lfs_handle_get_dir(handle), path);
if(file->internal_error_id >= LFS_ERR_OK) {
lfs_handle_set_open(handle);
}
file->error_id = storage_int_parse_error(file->internal_error_id);
return (file->error_id == FSE_OK);
}
static bool storage_int_dir_close(void* ctx, File* file) {
StorageData* storage = ctx;
lfs_t* lfs = lfs_get_from_storage(storage);
LFSHandle* handle = storage_get_storage_file_data(file, storage);
if(lfs_handle_is_open(handle)) {
file->internal_error_id = lfs_dir_close(lfs, lfs_handle_get_dir(handle));
} else {
file->internal_error_id = LFS_ERR_BADF;
}
file->error_id = storage_int_parse_error(file->internal_error_id);
lfs_handle_free(handle);
return (file->error_id == FSE_OK);
}
static bool storage_int_dir_read(
void* ctx,
File* file,
FileInfo* fileinfo,
char* name,
const uint16_t name_length) {
StorageData* storage = ctx;
lfs_t* lfs = lfs_get_from_storage(storage);
LFSHandle* handle = storage_get_storage_file_data(file, storage);
if(lfs_handle_is_open(handle)) {
struct lfs_info _fileinfo;
// LFS returns virtual directories "." and "..", so we read until we get something meaningful or an empty string
do {
file->internal_error_id = lfs_dir_read(lfs, lfs_handle_get_dir(handle), &_fileinfo);
file->error_id = storage_int_parse_error(file->internal_error_id);
} while(strcmp(_fileinfo.name, ".") == 0 || strcmp(_fileinfo.name, "..") == 0);
if(fileinfo != NULL) {
fileinfo->size = _fileinfo.size;
fileinfo->flags = 0;
if(_fileinfo.type & LFS_TYPE_DIR) fileinfo->flags |= FSF_DIRECTORY;
}
if(name != NULL) {
snprintf(name, name_length, "%s", _fileinfo.name);
}
// set FSE_NOT_EXIST error on end of directory
if(file->internal_error_id == 0) {
file->error_id = FSE_NOT_EXIST;
}
} else {
file->internal_error_id = LFS_ERR_BADF;
file->error_id = storage_int_parse_error(file->internal_error_id);
}
return (file->error_id == FSE_OK);
}
static bool storage_int_dir_rewind(void* ctx, File* file) {
StorageData* storage = ctx;
lfs_t* lfs = lfs_get_from_storage(storage);
LFSHandle* handle = storage_get_storage_file_data(file, storage);
if(lfs_handle_is_open(handle)) {
file->internal_error_id = lfs_dir_rewind(lfs, lfs_handle_get_dir(handle));
} else {
file->internal_error_id = LFS_ERR_BADF;
}
file->error_id = storage_int_parse_error(file->internal_error_id);
return (file->error_id == FSE_OK);
}
/******************* Common FS Functions *******************/
static FS_Error storage_int_common_stat(void* ctx, const char* path, FileInfo* fileinfo) {
StorageData* storage = ctx;
lfs_t* lfs = lfs_get_from_storage(storage);
struct lfs_info _fileinfo;
int result = lfs_stat(lfs, path, &_fileinfo);
if(fileinfo != NULL) {
fileinfo->size = _fileinfo.size;
fileinfo->flags = 0;
if(_fileinfo.type & LFS_TYPE_DIR) fileinfo->flags |= FSF_DIRECTORY;
}
return storage_int_parse_error(result);
}
static FS_Error storage_int_common_remove(void* ctx, const char* path) {
StorageData* storage = ctx;
lfs_t* lfs = lfs_get_from_storage(storage);
int result = lfs_remove(lfs, path);
return storage_int_parse_error(result);
}
static FS_Error storage_int_common_mkdir(void* ctx, const char* path) {
StorageData* storage = ctx;
lfs_t* lfs = lfs_get_from_storage(storage);
int result = lfs_mkdir(lfs, path);
return storage_int_parse_error(result);
}
static FS_Error storage_int_common_fs_info(
void* ctx,
const char* fs_path,
uint64_t* total_space,
uint64_t* free_space) {
UNUSED(fs_path);
StorageData* storage = ctx;
lfs_t* lfs = lfs_get_from_storage(storage);
LFSData* lfs_data = lfs_data_get_from_storage(storage);
if(total_space) {
*total_space = lfs_data->config.block_size * lfs_data->config.block_count;
}
lfs_ssize_t result = lfs_fs_size(lfs);
if(free_space && (result >= 0)) {
*free_space = (lfs_data->config.block_count - result) * lfs_data->config.block_size;
}
return storage_int_parse_error(result);
}
/******************* Init Storage *******************/
static const FS_Api fs_api = {
.file =
{
.open = storage_int_file_open,
.close = storage_int_file_close,
.read = storage_int_file_read,
.write = storage_int_file_write,
.seek = storage_int_file_seek,
.tell = storage_int_file_tell,
.truncate = storage_int_file_truncate,
.size = storage_int_file_size,
.sync = storage_int_file_sync,
.eof = storage_int_file_eof,
},
.dir =
{
.open = storage_int_dir_open,
.close = storage_int_dir_close,
.read = storage_int_dir_read,
.rewind = storage_int_dir_rewind,
},
.common =
{
.stat = storage_int_common_stat,
.mkdir = storage_int_common_mkdir,
.remove = storage_int_common_remove,
.fs_info = storage_int_common_fs_info,
},
};
void storage_int_init(StorageData* storage) {
FURI_LOG_I(TAG, "Starting");
LFSData* lfs_data = storage_int_lfs_data_alloc();
FURI_LOG_I(
TAG,
"Config: start %p, read %d, write %d, page size: %d, page count: %d, cycles: %d",
lfs_data->start_address,
lfs_data->config.read_size,
lfs_data->config.prog_size,
lfs_data->config.block_size,
lfs_data->config.block_count,
lfs_data->config.block_cycles);
storage_int_lfs_mount(lfs_data, storage);
storage->data = lfs_data;
storage->api.tick = NULL;
storage->fs_api = &fs_api;
}

View File

@@ -0,0 +1,13 @@
#pragma once
#include <furi.h>
#include "../storage_glue.h"
#ifdef __cplusplus
extern "C" {
#endif
void storage_int_init(StorageData* storage);
#ifdef __cplusplus
}
#endif