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>
This commit is contained in:
@@ -0,0 +1,145 @@
|
||||
# OTAManager
|
||||
|
||||
OTAManager handles over-the-air firmware updates for Vesper devices. It fetches a `metadata.json` manifest from one or more configured update servers, validates the available version against the running firmware, and streams the binary directly into the OTA flash partition using the ESP-IDF `Update` library. Updates can be triggered automatically at boot (emergency/mandatory only), on a nightly schedule (3:00 AM, emergency only), or on-demand via the communication layer. After a successful flash, the device saves the new version to NVS and reboots.
|
||||
|
||||
---
|
||||
|
||||
## Public API
|
||||
|
||||
| Method | Description |
|
||||
|---|---|
|
||||
| `OTAManager(ConfigManager& configManager)` | Constructor. Takes a reference to ConfigManager; all other dependencies are injected post-construction. |
|
||||
| `void begin()` | Allocates the worker task (8 KB stack, Core 0), the binary semaphore, the per-minute scheduled-check timer, and the one-shot 5-second boot-check timer. Must be called after `ConfigManager` is initialized. |
|
||||
| `void setFileManager(FileManager* fm)` | Injects the FileManager dependency. Required before `isHealthy()` returns true and before any SD-based code paths run. |
|
||||
| `void setPlayer(Player* player)` | Injects the Player reference. Used to gate updates — updates are blocked if the player is active. |
|
||||
| `void setTimeKeeper(Timekeeper* tk)` | Injects the Timekeeper reference. Its clock updates are paused during the flash write to reduce contention. |
|
||||
| `void setTelemetry(Telemetry* telemetry)` | Injects the Telemetry reference. Telemetry is paused during the flash write. |
|
||||
| `void checkForUpdates()` | Checks the `stable` channel for a newer version. Auto-applies if the update is flagged emergency or mandatory. |
|
||||
| `void checkForUpdates(const String& channel)` | Same as above but against the specified channel. |
|
||||
| `void checkForEmergencyUpdates()` | Checks `stable` and applies immediately only if the `emergency` flag is set in metadata. Used by the 3:00 AM scheduled timer. |
|
||||
| `void update()` | Applies the most recently checked update from the `stable` channel. Reboots on success. |
|
||||
| `void update(const String& channel)` | Applies the most recently checked update from the specified channel. Reboots on success. |
|
||||
| `void checkFirmwareUpdateFromSD()` | Checks the SD card for `/firmware/update.bin`. If found (and a matching `.sha256` file exists), installs it. Reboots on success. |
|
||||
| `bool performManualUpdate()` | Checks `stable` channel then applies if an update is available. Returns `false` if none found or already in progress. |
|
||||
| `bool performManualUpdate(const String& channel)` | Same as above for a specific channel. |
|
||||
| `bool performCustomUpdate(const String& firmwareUrl, const String& checksum, size_t fileSize, uint16_t version)` | Flashes firmware from an arbitrary URL. `checksum` and `fileSize` are optional (pass `""` / `0` to skip). `version` is written to NVS on success. Blocked if the player is active. |
|
||||
| `String getHardwareVariant() const` | Returns the hardware variant string from ConfigManager (e.g. `"VS"`). |
|
||||
| `void setHardwareVariant(const String& variant)` | **Deprecated.** Use `ConfigManager::setHardwareVariant` instead. Logs a warning and does nothing. |
|
||||
| `Status getStatus() const` | Returns the current `Status` enum value (`IDLE`, `CHECKING_VERSION`, `DOWNLOADING`, `INSTALLING`, `SUCCESS`, `FAILED`). |
|
||||
| `ErrorCode getLastError() const` | Returns the most recent `ErrorCode`. Useful after a `FAILED` status. |
|
||||
| `uint16_t getCurrentVersion() const` | Returns the running firmware version as a `uint16_t` (reads `ConfigManager::getFwVersion()` and calls `.toInt()`). |
|
||||
| `uint16_t getAvailableVersion() const` | Returns the version number from the last successful metadata fetch. |
|
||||
| `bool isUpdateAvailable() const` | `true` if the last `checkForUpdates` call found a newer version. |
|
||||
| `void setProgressCallback(ProgressCallback callback)` | Registers a `(size_t current, size_t total)` callback, fired during SD-based downloads. Not called during direct-to-flash downloads. |
|
||||
| `void setStatusCallback(StatusCallback callback)` | Registers a `(Status, ErrorCode)` callback fired on every status transition. |
|
||||
| `bool isHealthy() const` | Returns `true` if FileManager is set and healthy, status is not `FAILED`, hardware variant and firmware version are valid, update servers are configured, and the scheduled timer is active. |
|
||||
|
||||
---
|
||||
|
||||
## Initialization
|
||||
|
||||
`OTAManager` is constructed as a global in [main.cpp](../main.cpp) with a reference to `configManager`:
|
||||
|
||||
```cpp
|
||||
OTAManager otaManager(configManager);
|
||||
```
|
||||
|
||||
After `configManager.begin()` and before `otaManager.begin()`, the optional dependencies are injected:
|
||||
|
||||
```cpp
|
||||
otaManager.begin();
|
||||
otaManager.setFileManager(&fileManager);
|
||||
otaManager.setPlayer(&player);
|
||||
otaManager.setTimeKeeper(&timekeeper);
|
||||
otaManager.setTelemetry(&telemetry);
|
||||
```
|
||||
|
||||
`healthMonitor.setOTAManager(&otaManager)` is called afterwards to register it for periodic health polling.
|
||||
|
||||
`begin()` must be called before any update methods. The optional setters (`setFileManager`, `setPlayer`, etc.) can be called after `begin()` — the worker task and timers will already be running, but the 5-second initial-check timer fires after boot so there is enough time to inject dependencies before the first check runs.
|
||||
|
||||
---
|
||||
|
||||
## Dependencies
|
||||
|
||||
| Dependency | Type | Purpose |
|
||||
|---|---|---|
|
||||
| `ConfigManager` | Required (constructor) | Hardware variant, firmware version, update server URLs, update config (timeout, retries) |
|
||||
| `FileManager` | Required (setter) | SD card path helpers; health check delegates to `FileManager::isHealthy()` |
|
||||
| `Player` | Optional (setter) | Blocks updates while audio playback is active |
|
||||
| `Timekeeper` | Optional (setter) | Paused during flash write to reduce timer interrupt load |
|
||||
| `Telemetry` | Optional (setter) | Paused during flash write |
|
||||
| `SDCardMutex` | Internal (singleton) | Guards concurrent SD access in the legacy SD-download code path |
|
||||
| `Update` (ESP-IDF) | Internal | Writes firmware to the OTA flash partition |
|
||||
| `HTTPClient` | Internal | Downloads metadata and firmware |
|
||||
| `mbedtls` | Internal | SHA-256 checksum calculation for SD-based installs |
|
||||
|
||||
---
|
||||
|
||||
## Metadata format
|
||||
|
||||
`checkVersion()` fetches `metadata.json` from:
|
||||
|
||||
```
|
||||
<server>/ota/<hardwareVariant>/<channel>/metadata.json
|
||||
```
|
||||
|
||||
Expected fields:
|
||||
|
||||
| Field | Type | Notes |
|
||||
|---|---|---|
|
||||
| `version` | `uint16_t` | Build number (e.g. `138`) |
|
||||
| `channel` | `String` | Must match the requested channel or the server is skipped |
|
||||
| `hardwareVariant` | `String` | Must match `ConfigManager::getHardwareVariant()` if present |
|
||||
| `checksum` | `String` | 64-character SHA-256 hex string |
|
||||
| `fileSize` | `size_t` | Expected byte count; validated against `Content-Length` |
|
||||
| `minVersion` | `uint16_t` | Minimum version that can upgrade directly; `0` = no restriction |
|
||||
| `mandatory` | `bool` | Applied automatically at boot-time check |
|
||||
| `emergency` | `bool` | Applied automatically at boot and at the 3:00 AM scheduled check |
|
||||
|
||||
---
|
||||
|
||||
## Communication interface
|
||||
|
||||
OTA updates are triggered through `FirmwareHandler`, which is wired into the `CommunicationRouter`. Two commands are relevant:
|
||||
|
||||
**`ota.update`** — triggers a channel update:
|
||||
```json
|
||||
{ "v": 2, "cmd": "ota.update", "contents": { "channel": "stable" } }
|
||||
```
|
||||
`channel` defaults to `"stable"` if omitted. Blocked if the player is active.
|
||||
|
||||
**`ota.custom`** — flashes from an arbitrary URL:
|
||||
```json
|
||||
{ "v": 2, "cmd": "ota.custom", "contents": {
|
||||
"firmware_url": "http://example.com/firmware.bin",
|
||||
"checksum": "abc123...",
|
||||
"file_size": 1234567,
|
||||
"version": 139
|
||||
}}
|
||||
```
|
||||
`checksum`, `file_size`, and `version` are optional. Blocked if the player is active.
|
||||
|
||||
Both commands return a response to the caller before the update begins. If the update succeeds, the device reboots and the caller receives no further response.
|
||||
|
||||
---
|
||||
|
||||
## Gotchas and notes
|
||||
|
||||
**Direct-to-flash vs SD-based download.** The current primary code path (`downloadDirectToFlash`) streams HTTP directly into the OTA flash partition using `Update.write()` in 4 KB chunks. The older SD-based path (`downloadToSD` + `installFromSD`) is retained in the code but is not called by the active `downloadAndInstall` method. The SD path includes SHA-256 verification; the direct-to-flash path relies on the ESP32 bootloader's own integrity checks.
|
||||
|
||||
**Timer callbacks are non-blocking.** Both `initialCheckCallback` and `scheduledCheckCallback` run in the FreeRTOS Timer Service task, which has a limited stack. They only set `_pendingWork` and give a semaphore; the actual HTTP work is done in the dedicated `OTA_Worker` task (8 KB stack, Core 0, priority 2).
|
||||
|
||||
**Freeze mode.** During a flash write, `Timekeeper::pauseClockUpdates()` and `Telemetry::pause()` are called. Both are resumed on success or failure before returning. This prevents SD bus contention and reduces timer interrupt interference during the write loop.
|
||||
|
||||
**Watchdog feeding.** The direct-to-flash write loop calls `esp_task_wdt_reset()` every 500 ms. If the firmware binary is unexpectedly large or the download stalls, the watchdog will eventually fire.
|
||||
|
||||
**Scheduled check timing.** The `_scheduledCheckTimer` fires every 60 seconds. The callback checks `localtime` and only proceeds at exactly 03:00. The minute window means the check fires once at 3:00:00–3:00:59. NTP must be synchronized for this to land at the right time.
|
||||
|
||||
**`minVersion` enforcement.** If the server specifies a `minVersion` greater than the currently running version, the update is rejected with `VERSION_TOO_LOW`. An intermediate update must be applied first. This is checked per-server; the manager will try remaining servers in the list before giving up.
|
||||
|
||||
**Multiple update servers.** `ConfigManager::getUpdateServers()` returns an ordered list. Each server is tried in sequence with configurable retry count and exponential backoff. The first server to return a valid `200 OK` with a parseable, consistent metadata response is used.
|
||||
|
||||
**`isHealthy()` requires the scheduled timer to be active.** If `begin()` fails to create the timer (e.g., insufficient FreeRTOS heap), `isHealthy()` will return `false` indefinitely. Check the serial log for `"Failed to create OTA scheduled check timer!"`.
|
||||
|
||||
**`setHardwareVariant` is a no-op.** The method exists for API compatibility but logs a warning and does nothing. Hardware variant is read from NVS via `ConfigManager`.
|
||||
Reference in New Issue
Block a user