Files
kvida-os/components/drivers/src/storage.cpp
Ronny Eia 967fecbf69 Add persistent script storage + hot-reload, verified live
lua_runtime now loads the running script from a new LittleFS-backed
drivers::storage (joltwallet/littlefs, the project's fifth external
managed component -- mounts the "storage" partition already reserved
in partitions.csv), falling back to the compiled-in default script
only on first boot. transport exposes GET/POST /api/script -- raw Lua
text, not JSON, since json_helpers.h can't round-trip scripts safely
-- relayed to lua_runtime via the same callback-registration pattern
already used for LedColorHandler, keeping transport free of a
dependency on lua_runtime. lua_runtime_reload() persists and hot-swaps
to a fresh Lua state immediately, no reboot.

Verified on real ESP32-C6 hardware: script loads via kvida-sdk, an
edited script hot-reloads within one tick, and the edit survives a
power cycle (proving LittleFS persistence, not just an in-RAM change).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-12 10:27:00 +02:00

80 lines
1.6 KiB
C++

#include "storage.h"
#include <cstdio>
#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<unsigned>(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