From 7675a67c90bab25f3dda93bade1fdd28f5740e11 Mon Sep 17 00:00:00 2001 From: bonamin Date: Wed, 15 Jul 2026 00:04:42 +0300 Subject: [PATCH] feat(FirmwareValidator): expose rollback safety-net diagnostics via firmware.status MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Startup retry count, runtime failure count, and backup partition info were tracked internally (NVS-persisted) but only visible via LOG_* output — not queryable remotely. Added getStartupRetryCount()/getRuntimeFailureCount() getters and extended firmware.status with startup_retry_count, max_startup_retries, runtime_failure_count, max_runtime_failures, backup_version, backup_is_valid. F-049 in the feature catalog. Also finalizes the feature-catalog.md and api-reference.md updates for F-045/F-046/F-047/F-048 from the two prior commits (doc content is consolidated into this final commit rather than split across the changeset). --- docs/features/feature-catalog.md | 62 +++++++++++++++++++ docs/reference/api-reference.md | 44 ++++++++++++- .../FirmwareHandler/FirmwareHandler.cpp | 9 +++ src/FirmwareValidator/FirmwareValidator.hpp | 6 ++ src/FirmwareValidator/README.md | 4 +- 5 files changed, 123 insertions(+), 2 deletions(-) diff --git a/docs/features/feature-catalog.md b/docs/features/feature-catalog.md index 41e50ed..f96a268 100644 --- a/docs/features/feature-catalog.md +++ b/docs/features/feature-catalog.md @@ -54,6 +54,11 @@ Every feature — user-facing or significant internal mechanism — is listed he | F-042 | Combined clock config commands (`clock.set_config` / `clock.set_alerts_config`) | v2.1.1 | Stable | | F-043 | `network.info` expanded — subnet, MAC, hostname, SSID, connection type | v2.1.1 | Stable | | F-044 | `network.status` slimmed — pure runtime state (connected, state, RSSI, uptime, AP mode) | v2.1.1 | Stable | +| F-045 | Day-rotated SD log files with size cap (`/logs/YYYY-MM-DD.log`) | v2.1.2 | Stable | +| F-046 | Boot reset-reason capture, routed to alerts (fault) or info (expected) | v2.1.2 | Stable | +| F-047 | Per-subsystem MQTT log rate limiting (token bucket + drop summary) | v2.1.2 | Stable | +| F-048 | SD log retrieval commands (`logs.list` / `logs.download`) | v2.1.2 | Stable | +| F-049 | `firmware.status` rollback safety-net diagnostics (retry/failure counts, backup partition) | v2.1.2 | Stable | --- @@ -607,3 +612,60 @@ Subsystem: `src/Communication/Handlers/NetworkHandler/NetworkHandler.cpp` Removed from `network.status`: `ip`, `mac`, `hostname`, `ssid`, `type` — these are static addressing facts, now served by `network.info`. Subsystem: `src/Communication/Handlers/NetworkHandler/NetworkHandler.cpp` + +--- + +### F-045 — Day-rotated SD log files with size cap + +Fixes a bug where SD logging was a silent no-op: `FileManager::appendLine` never created the `/logs` directory before opening the file in append mode, which fails on most SD/FAT implementations when the parent directory doesn't exist. + +New `FileManager::appendLogLine(logDir, line, timestamp, maxTotalBytes)` replaces the direct `appendLine` call as the SD log channel's write path: +- Ensures `logDir` exists before every write. +- Names the file `YYYY-MM-DD.log` from the supplied timestamp (`time(nullptr)`, works with or without an RTC once NTP has synced). Falls back to `unset-date.log` if no wall clock is available yet, rather than dropping early-boot lines. +- Prunes oldest whole files once the directory exceeds a 512KB total budget (`SD_LOG_MAX_TOTAL_BYTES` in `CommunicationRouter.cpp`). + +Subsystems: `src/FileManager/FileManager.cpp`, `src/Communication/CommunicationRouter/CommunicationRouter.cpp` + +--- + +### F-046 — Boot reset-reason capture + +`Telemetry::begin()` now reads `esp_reset_reason()` at the very start of boot, before anything else can crash again this cycle. Classified into fault (`ESP_RST_PANIC`, `ESP_RST_INT_WDT`, `ESP_RST_TASK_WDT`, `ESP_RST_WDT`, `ESP_RST_BROWNOUT`) vs expected (power-on, software reset/OTA, deep sleep wake, etc). + +- Persisted in the SD boot log (`/telemetry_boot_log.json`, field `reason`) regardless of connectivity — works for offline devices. +- For online devices, `CommunicationRouter::reportBootReasonOnce()` fires the first time MQTT connects after boot (registered via `MQTTDriver::setOnConnectCallback`): fault reasons publish to `vesper/{uid}/status/alerts`, expected reasons publish to `vesper/{uid}/status/info` (event type `boot_reason`). Fires once per boot, not on every reconnect. + +Subsystems: `src/Telemetry/Telemetry.cpp`, `src/Communication/CommunicationRouter/CommunicationRouter.cpp`, `src/Communication/Drivers/MQTTDriver/MQTTDriver.cpp` + +--- + +### F-047 — Per-subsystem MQTT log rate limiting + +Token bucket per subsystem tag on the MQTT log channel (burst of 10, refills 1/second) inside `Logging::publishToMqtt()`. Protects the broker/airtime from a chatty or misconfigured subsystem (e.g. a per-subsystem override left at VERBOSE via `log.set_mqtt`). + +Drops are counted, not silently discarded: the next time a rate-limited tag is allowed to publish again, a `WARNING` summary line (`"suppressed N log message(s) (MQTT rate limit)"`) is emitted first. Serial and SD channels are unaffected — MQTT only. + +Subsystem: `src/Logging/Logging.cpp` + +--- + +### F-048 — SD log retrieval commands (`logs.list` / `logs.download`) + +Two new commands on `LoggingHandler` for pulling day-rotated SD logs off a device remotely (offline-device troubleshooting workflow: app queries device directly, or backend requests once the device is back online). + +| Command | Description | +|---|---| +| `logs.list` | Lists dated log files under `/logs` with name + size. | +| `logs.download` | Returns a bounded chunk (`{file, offset}` → `{data, next_offset, eof}`) of a log file. Callers loop, feeding `next_offset` back as `offset`, until `eof` is true. Rejects path traversal in `file`. | + +Chunked rather than whole-file because `CommandResult` JSON payloads need to stay small regardless of file size (a rotated file can be up to the full SD log budget). Both commands return an error (not a crash) on boards without an SD card — `LoggingHandler` now takes an optional `FileManager*`. + +Subsystems: `src/Communication/Handlers/LoggingHandler/LoggingHandler.cpp`, `src/FileManager/FileManager.cpp` + +--- + +### F-049 — `firmware.status` rollback safety-net diagnostics + +`FirmwareValidator` tracked startup retry count, runtime failure count, and backup partition info internally (NVS-persisted) but never exposed them remotely — only visible via `LOG_*` output. Added public getters (`getStartupRetryCount()`, `getRuntimeFailureCount()`) and extended `firmware.status` with `startup_retry_count`, `max_startup_retries`, `runtime_failure_count`, `max_runtime_failures`, `backup_version`, `backup_is_valid`. + +Subsystems: `src/FirmwareValidator/FirmwareValidator.hpp`, `src/Communication/Handlers/FirmwareHandler/FirmwareHandler.cpp` diff --git a/docs/reference/api-reference.md b/docs/reference/api-reference.md index c96a28e..2018118 100644 --- a/docs/reference/api-reference.md +++ b/docs/reference/api-reference.md @@ -459,7 +459,9 @@ Get firmware validation state. | | | |---|---| -| Returns | `{ "validation_state", "version", "boot_count", "can_commit", "can_rollback" }` | +| Returns | `{ "validation_state", "current_version", "is_testing", "is_valid", "boot_count", "build_date", "ota_channel", "startup_retry_count", "max_startup_retries", "runtime_failure_count", "max_runtime_failures", "backup_version", "backup_is_valid", "can_commit", "can_rollback", "runtime_timeout_ms"? }` | + +`startup_retry_count`, `runtime_failure_count`, and the backup partition fields are the OTA rollback safety-net's internal counters — previously only visible via serial/SD log output, now queryable remotely. Useful for diagnosing why a device rolled back an update. `runtime_timeout_ms` is only present while `is_testing` is true. ```json { "v": 2, "cmd": "firmware.status" } @@ -701,6 +703,38 @@ Set log verbosity per output channel. Level 0 = off, 5 = verbose. --- +### `logs.list` + +List day-rotated SD log files (`/logs/YYYY-MM-DD.log`). Requires an SD card — returns an error on boards without one. + +| | | +|---|---| +| Returns | `{ "files": [{ "name": "2026-07-14.log", "size": 1234 }, ...] }` | + +```json +{ "v": 2, "cmd": "logs.list" } +``` + +--- + +### `logs.download` + +Read a bounded chunk of a log file. Responses are capped at 4096 bytes regardless of file size — callers loop, feeding `next_offset` back in as `offset`, until `eof` is `true`. Requires an SD card. + +| | | +|---|---| +| Required | `file` (string) — bare filename as returned by `logs.list`, no path separators | +| Optional | `offset` (int, default `0`) | +| Returns | `{ "file", "data", "next_offset", "eof" }` | + +```json +{ "v": 2, "cmd": "logs.download", "contents": { "file": "2026-07-14.log", "offset": 0 } } +``` + +Loop example: keep calling with `contents.offset = ` until the response has `"eof": true`. + +--- + ## RF Remote Namespace — `RFRemoteHandler` > Available on hardware variants with `HAS_RF=1` (e.g. Vesper, Vesper+). @@ -954,6 +988,11 @@ On recovery: `state` values: `WARNING` | `CRITICAL` | `FAILED` | `CLEARED` +A fault-class boot reset also publishes here — `subsystem: "System"`, e.g.: +```json +{ "subsystem": "System", "state": "WARNING", "msg": "Device reset due to fault: TASK_WATCHDOG" } +``` + ### Info Payload (`vesper/{id}/status/info`) Published on significant device state changes. `type` identifies the event; `payload` is event-specific. @@ -961,8 +1000,11 @@ Published on significant device state changes. `type` identifies the event; `pay ```json { "type": "playback_started", "payload": { "pid": "ormilia_1_8" } } { "type": "playback_stopped", "payload": {} } +{ "type": "boot_reason", "payload": { "reason": "POWERON" } } ``` +`boot_reason` is published once, the first time MQTT connects after boot — only for expected reset reasons (`POWERON`, `SOFTWARE`, `DEEPSLEEP_WAKE`, `EXTERNAL_PIN`, `SDIO`, `UNKNOWN`). Fault reasons (`PANIC`, `TASK_WATCHDOG`, `INTERRUPT_WATCHDOG`, `OTHER_WATCHDOG`, `BROWNOUT`) go to `status/alerts` instead (see above). + --- ## Legacy Compatibility (v1) diff --git a/src/Communication/Handlers/FirmwareHandler/FirmwareHandler.cpp b/src/Communication/Handlers/FirmwareHandler/FirmwareHandler.cpp index a835f70..d617bfa 100644 --- a/src/Communication/Handlers/FirmwareHandler/FirmwareHandler.cpp +++ b/src/Communication/Handlers/FirmwareHandler/FirmwareHandler.cpp @@ -39,6 +39,7 @@ CommandResult FirmwareHandler::execute(const CommandEnvelope& envelope) { CommandResult FirmwareHandler::handleFirmwareStatus(const CommandEnvelope& e) { auto validationState = _firmwareValidator.getValidationState(); auto currentInfo = _firmwareValidator.getCurrentFirmwareInfo(); + auto backupInfo = _firmwareValidator.getBackupFirmwareInfo(); auto config = _firmwareValidator.getValidationConfig(); static const char* stateNames[] = { @@ -56,6 +57,14 @@ CommandResult FirmwareHandler::handleFirmwareStatus(const CommandEnvelope& e) { doc["build_date"] = currentInfo.buildDate; doc["ota_channel"] = _configManager.getOtaChannel(); + // Rollback safety-net diagnostics — previously logged only, not queryable remotely. + doc["startup_retry_count"] = _firmwareValidator.getStartupRetryCount(); + doc["max_startup_retries"] = config.maxStartupRetries; + doc["runtime_failure_count"] = _firmwareValidator.getRuntimeFailureCount(); + doc["max_runtime_failures"] = config.maxRuntimeFailures; + doc["backup_version"] = backupInfo.version; + doc["backup_is_valid"] = backupInfo.isValid; + bool inTesting = _firmwareValidator.isInTestingMode(); doc["can_commit"] = inTesting; doc["can_rollback"] = (validationState != FirmwareValidationState::VALIDATED); diff --git a/src/FirmwareValidator/FirmwareValidator.hpp b/src/FirmwareValidator/FirmwareValidator.hpp index f67f181..664b9cf 100644 --- a/src/FirmwareValidator/FirmwareValidator.hpp +++ b/src/FirmwareValidator/FirmwareValidator.hpp @@ -262,6 +262,12 @@ public: */ bool isNewFirmwarePending() const; + /** @brief Number of startup validation retries consumed so far this cycle */ + uint8_t getStartupRetryCount() const { return _startupRetryCount; } + + /** @brief Number of runtime validation failures consumed so far this cycle */ + uint8_t getRuntimeFailureCount() const { return _runtimeFailureCount; } + private: // ═══════════════════════════════════════════════════════════════════════════════ // PRIVATE MEMBERS diff --git a/src/FirmwareValidator/README.md b/src/FirmwareValidator/README.md index 48bd602..ea8a7ae 100644 --- a/src/FirmwareValidator/README.md +++ b/src/FirmwareValidator/README.md @@ -25,6 +25,8 @@ FirmwareValidator implements a two-phase OTA safety gate for the Vesper firmware | `const esp_partition_t* getRunningPartition() const` | Returns the ESP-IDF partition descriptor for the currently executing partition. | | `const esp_partition_t* getBackupPartition() const` | Returns the ESP-IDF partition descriptor for the inactive OTA partition. | | `bool isNewFirmwarePending() const` | Returns `true` if validation has not yet completed (`STARTUP_PENDING`, `STARTUP_RUNNING`, or `RUNTIME_TESTING`). | +| `uint8_t getStartupRetryCount() const` | Number of startup validation retries consumed so far this cycle. Previously logged internally only — now exposed via `firmware.status`. | +| `uint8_t getRuntimeFailureCount() const` | Number of runtime validation failures consumed so far this cycle. Previously logged internally only — now exposed via `firmware.status`. | --- @@ -91,7 +93,7 @@ These commands are dispatched through the communication layer and map directly t | Command | Description | |---|---| -| `firmware.status` | Returns current validation state, version, boot count, and whether commit/rollback are available. | +| `firmware.status` | Returns current validation state, version, boot count, rollback safety-net diagnostics (`startup_retry_count`, `max_startup_retries`, `runtime_failure_count`, `max_runtime_failures`, `backup_version`, `backup_is_valid`), and whether commit/rollback are available. | | `firmware.commit` | Manually commits firmware. Returns an error if not in testing mode. | | `firmware.rollback` | Forces immediate rollback. Device will reboot. |