Files
project-vesper/src/FileManager
bonaminandClaude Sonnet 4.6 d4d8b1c380 docs: add per-subsystem README files
Add inline documentation for all src/ subsystems covering purpose,
responsibilities, public API, and usage notes.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-14 22:16:03 +02:00
..
2026-03-14 22:16:03 +02:00

FileManager

Summary

FileManager is the single access point for all SD card I/O in Vesper. It abstracts the Arduino SD library behind a stable API covering file downloads, JSON persistence, directory management, line appending, and existence/size queries. The subsystem exists because multiple independent consumers (Player, OTAManager, Telemetry, CommunicationRouter's SD log channel, and the files.* command handlers) all need SD access; centralizing it avoids direct SD.* calls scattered across the codebase and provides a single place to handle SD re-initialization, path normalization, and error logging.


Public API

Method Signature Description
Constructor FileManager(ConfigManager* config) Stores the ConfigManager pointer; does not initialize the SD card.
downloadFile bool downloadFile(const String& url, const String& directory, const String& filename) Downloads a file over HTTP or HTTPS (TLS, no cert validation) and writes it to directory/filename on the SD card. Creates the target directory if it does not exist.
addMelody bool addMelody(JsonVariant doc) High-level helper: extracts download_url and melodys_uid from a JSON object and calls downloadFile into /melodies/. Skips the download silently if the UID matches a built-in melody.
listFilesAsJson String listFilesAsJson(const char* dirPath) Returns a JSON string {"files": [...]} listing all non-directory entries in dirPath. Returns "{}" on any error.
fileExists bool fileExists(const String& filePath) Returns true if the file can be opened on the SD card.
deleteFile bool deleteFile(const String& filePath) Removes a file from the SD card. Returns false on failure.
createDirectory bool createDirectory(const String& dirPath) Creates a directory (and re-initializes the SD card if needed). No-op if it already exists.
getFileSize size_t getFileSize(const String& filePath) Returns the size in bytes of a file, or 0 if it cannot be opened.
writeJsonFile bool writeJsonFile(const String& filePath, JsonDocument& doc) Serializes an ArduinoJson JsonDocument to a file, overwriting any existing content.
readJsonFile bool readJsonFile(const String& filePath, JsonDocument& doc) Deserializes a file into an ArduinoJson JsonDocument. Returns false on open or parse failure.
appendLine bool appendLine(const String& filePath, const String& line) Opens a file in FILE_APPEND mode and writes line followed by \n. Used by the Logging subsystem's SD write callback to write to /logs/vesper.log.
isHealthy bool isHealthy() const Returns true if the ConfigManager pointer is set and SD.cardType() != CARD_NONE. Used by HealthMonitor.

Initialization

FileManager is constructed at file scope in main.cpp immediately after ConfigManager:

ConfigManager configManager;
FileManager fileManager(&configManager);

The constructor does nothing beyond storing the pointer. The SD card is not initialized at construction time; instead, initializeSD() (private) is called lazily at the start of every operation that needs the card. This means the subsystem is usable even if the SD card is absent at boot — individual calls will fail and log an error, but the device continues operating.

After construction, other subsystems receive a pointer via setter injection during setup():

healthMonitor.setFileManager(&fileManager);          // ~line 288
telemetry.setFileManager(&fileManager);              // ~line 340
communication.setFileManagerReference(&fileManager); // ~line 365 — also registers SD log callback
player.setDependencies(&communication, &fileManager);// ~line 373
otaManager.setFileManager(&fileManager);             // ~line 445

The setFileManagerReference call on CommunicationRouter is particularly important: it registers an appendLine callback with the Logging subsystem so that all LOG_* output is mirrored to /logs/vesper.log on the SD card.

Setup order requirement: ConfigManager must be constructed before FileManager. SDCardMutex::getInstance().begin() must be called before any SD operation executes (it is called early in setup()).


Dependencies

Dependency Type Reason
ConfigManager Subsystem pointer Reads hardwareConfig.sdChipSelect to get the CS pin for SD.begin().
Arduino SD library Platform library All card I/O.
HTTPClient, WiFiClient, WiFiClientSecure Platform libraries HTTP/HTTPS file downloads.
ArduinoJson Library JSON serialization and deserialization.
esp_task_wdt ESP-IDF Watchdog disable/re-enable around blocking HTTPS operations in downloadFile.
BuiltInMelodies Subsystem Consulted by addMelody to skip unnecessary downloads.
Logging Subsystem LOG_* macros throughout.

Gotchas / Notes

SD card is optional at runtime. Every method calls initializeSD() which calls SD.begin() on each invocation. If no card is inserted the call fails, the method returns false or "{}", and the device continues. HealthMonitor marks FileManager as WARNING (not CRITICAL) when the card is absent, so the device does not halt.

No internal mutex. FileManager does not acquire SDCardMutex internally. The ESP32 SD library is not thread-safe. If FileManager methods are called from multiple FreeRTOS tasks concurrently, callers must coordinate via SDCardMutex / SDCardLock themselves. Currently downloadFile (called from the CommandBus task via FileHandler) and appendLine (called from the Logging callback, which fires from whatever task emits the log) are the most likely concurrent paths — audit this before adding new callers from additional tasks.

Watchdog is temporarily disabled during downloads. downloadFile calls esp_task_wdt_delete(NULL) before the HTTP GET and esp_task_wdt_add(NULL) after. This removes watchdog coverage for the calling task for the duration of the TLS handshake (can be several seconds). Avoid calling downloadFile from tasks where watchdog removal is inappropriate.

HTTPS uses setInsecure(). TLS certificate validation is skipped. This is intentional for compatibility with Firebase/CDN redirect chains, but means downloads are not authenticated — file content is trusted implicitly.

SD.begin() called on every operation. Because initializeSD() runs at the top of every method, a card inserted after boot is detected automatically on the next call. Calling SD.begin() on an already-mounted card is harmless but adds ~1 ms overhead per call.

isHealthy() is lightweight by design. It uses SD.cardType() rather than SD.begin() to avoid the cost and side-effects of re-mounting on every HealthMonitor poll cycle.

listFilesAsJson has a fixed 1024-byte JSON budget. Directories with more than roughly 20–25 average-length filenames will overflow this DynamicJsonDocument allocation silently. Increase the capacity if /melodies is expected to hold a large number of files.

Log file path is hardcoded in the caller. The path /logs/vesper.log is set inside CommunicationRouter::setFileManagerReference, not inside FileManager. FileManager itself is path-agnostic.