#include "storage.h" #include #include "esp_log.h" #include "esp_littlefs.h" namespace kvida::drivers { namespace { constexpr const char *TAG = "storage"; bool g_mounted = false; } // namespace void storage_init() { if (g_mounted) { return; } esp_vfs_littlefs_conf_t conf = {}; conf.base_path = "/storage"; conf.partition_label = "storage"; conf.format_if_mount_failed = true; conf.grow_on_mount = false; esp_err_t err = esp_vfs_littlefs_register(&conf); if (err != ESP_OK) { ESP_LOGE(TAG, "esp_vfs_littlefs_register failed: %s", esp_err_to_name(err)); return; } g_mounted = true; } bool storage_read_file(const char *path, char *buf, size_t cap, size_t *out_len) { if (!g_mounted || cap == 0) { return false; } FILE *f = fopen(path, "r"); if (!f) { return false; } size_t n = fread(buf, 1, cap - 1, f); bool truncated = !feof(f); fclose(f); if (truncated) { ESP_LOGE(TAG, "%s is larger than the %u-byte read buffer", path, static_cast(cap - 1)); return false; } buf[n] = '\0'; if (out_len) { *out_len = n; } return true; } bool storage_write_file(const char *path, const char *data, size_t len) { if (!g_mounted) { return false; } FILE *f = fopen(path, "w"); if (!f) { ESP_LOGE(TAG, "fopen(%s, \"w\") failed", path); return false; } size_t written = fwrite(data, 1, len, f); fclose(f); return written == len; } } // namespace kvida::drivers