From 829ae23f09b76a84c6aac4755d54c41c3a1bb63d Mon Sep 17 00:00:00 2001 From: bonamin Date: Thu, 16 Jul 2026 11:17:41 +0300 Subject: [PATCH] feat(Telemetry,CommunicationRouter): lifetime boot counter + coredump crash detail over MQTT MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Investigating the F-051 TelemetryTask crash surfaced two gaps: the console only ever saw a coarse "Device reset due to fault: PANIC" alert, none of the serial monitor's task-name/register detail; and there was no automatic per-boot report a console could use to count reboots without polling. Adds Telemetry::getLifetimeBootCount() — a new NVS-backed counter (namespace "vesper_boot") that increments once per boot, works on every board variant (SD or not), and is reliable regardless of NTP sync status. Deliberately kept separate from FirmwareValidator's existing NVS boot_count (scoped to boots-since-this-OTA-slot-was- flashed, feeds rollback-safety retry logic — left untouched) and Telemetry's existing SD-based total_boots (repositioned as history- only; unreliable as a counter since it's SD/NTP-dependent). Adds Telemetry::captureCrashReport(), which reads the ESP-IDF coredump summary (esp_core_dump_get_summary) once at begin(). The coredump partition and CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH were already present/enabled in this project's stock min_spiffs.csv and precompiled Arduino-ESP32 core — no partition table or SDK config change needed. This is the official "user mode" retrieval API, safe to call from ordinary application code after boot; no custom panic hook, nothing runs inside the panic handler itself. Extracts the faulting task name, PC, and exception cause/vaddr, then erases the dump so it's reported exactly once. CommunicationRouter::reportBootReasonOnce() (renamed reportBootOnce()) now always publishes a consolidated "boot_report" event to status/info on first MQTT connect — boot count, reset reason, free heap, and crash detail when available — alongside the existing fault-triggered status/alerts WARNING (unchanged). lifetime_boot_count also added to telemetry.get_metrics, system.get_telemetry, and system.get_all for on-demand polling. Verified: pio run on both vesper-std-v1 and agnus-v1 (no-SD variant). Co-Authored-By: Claude Sonnet 5 --- docs/features/feature-catalog.md | 47 +++++++++++++++- .../CommunicationRouter.cpp | 38 ++++++++++--- .../CommunicationRouter.hpp | 12 ++-- .../CommunicationRouter/README.md | 24 +++++++- .../Handlers/SystemHandler/SystemHandler.cpp | 2 + .../TelemetryHandler/TelemetryHandler.cpp | 1 + src/Telemetry/README.md | 20 ++++++- src/Telemetry/Telemetry.cpp | 56 +++++++++++++++++++ src/Telemetry/Telemetry.hpp | 46 ++++++++++++++- 9 files changed, 227 insertions(+), 19 deletions(-) diff --git a/docs/features/feature-catalog.md b/docs/features/feature-catalog.md index f98bd72..da08b32 100644 --- a/docs/features/feature-catalog.md +++ b/docs/features/feature-catalog.md @@ -61,6 +61,7 @@ Every feature — user-facing or significant internal mechanism — is listed he | F-049 | `firmware.status` rollback safety-net diagnostics (retry/failure counts, backup partition) | v2.1.2 | Stable | | F-050 | SD log lines prefixed with wall-clock date/time + uptime | v2.1.2 | Stable | | F-051 | Fix: TelemetryTask/HealthMonitor stack overflow — stack bump + deferred MQTT/SD logging queue | v2.0.3 | Stable | +| F-052 | Consolidated lifetime boot counter + coredump crash detail, published automatically over MQTT | v2.1.3 | Stable | --- @@ -460,7 +461,7 @@ New commands added to `TelemetryHandler`: | Command | Description | |---|---| -| `telemetry.get_metrics` | Returns `lifetime_runtime_seconds`, `session_runtime_seconds`, `total_playbacks`, `guard_enabled` | +| `telemetry.get_metrics` | Returns `lifetime_runtime_seconds`, `session_runtime_seconds`, `total_playbacks`, `guard_enabled`, `lifetime_boot_count` (F-052) | | `telemetry.reset_metrics` | Resets lifetime runtime and playback count to zero (persisted) | Subsystem: `src/Communication/Handlers/TelemetryHandler/` @@ -717,3 +718,47 @@ Implemented in `src/Logging/Logging.hpp` / `Logging.cpp`: RAM impact verified negligible via `pio run` (62980 vs. 62956 bytes static RAM; the 4096B task stack is allocated at runtime only if MQTT or SD logging is actually enabled). Subsystem: `src/Logging/Logging.hpp`, `src/Logging/Logging.cpp` + +--- + +### F-052 — Consolidated lifetime boot counter + coredump crash detail, published automatically over MQTT + +**Motivation:** Investigating the F-051 crash surfaced a gap — the console only ever saw `"Device reset due to fault: PANIC"`, a coarse `esp_reset_reason()` string, with none of the detail the serial monitor showed (faulting task name, program counter, register dump). Separately, there was no automatic per-boot report a console could use to count reboots ("did this device restart 50 times today?") without polling — the two existing boot counters (`FirmwareValidator`'s NVS `boot_count` and `Telemetry`'s SD-based `total_boots`) were both unsuited to that job for different reasons (see table below). + +**Three boot/crash mechanisms now coexist, deliberately kept separate:** + +| Mechanism | Storage | Scope | Survives SD failure? | +|---|---|---|---| +| `Telemetry::getLifetimeBootCount()` — **new, this feature** | NVS, namespace `vesper_boot` | Whole device lifetime | Yes | +| `FirmwareValidator::getBootCount()` — pre-existing, unchanged | NVS, namespace `fw_validator` | Boots since this firmware image was flashed (rollback-safety bookkeeping) | Yes | +| `Telemetry::logBootEvent()` → SD `/telemetry_boot_log.json` — pre-existing, unchanged | SD card, rotating array (200 entries) | Timestamped history of recent boots | No — silently empty without SD or before NTP sync | + +`FirmwareValidator`'s counter was deliberately left untouched rather than repurposed — it's load-bearing for startup/runtime validation retry logic and scoped to "since this OTA slot was flashed," not the device's lifetime. The SD-based log is repositioned as a *history* (useful for browsing recent boots with timestamps), not a counter — its `total_boots` field was never reliable as one (no-SD `agnus` variants get nothing from it, and it's silently skipped before NTP sync). + +**Coredump-based crash detail (`Telemetry::captureCrashReport()`):** ESP-IDF's panic handler already writes a coredump to flash on every crash — this project's stock `min_spiffs.csv` partition table already reserves a 64KB `coredump` partition, and the precompiled Arduino-ESP32 core already has `CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH` enabled. Neither needed to change. `captureCrashReport()` calls the official, documented "user mode" retrieval API (`esp_core_dump_image_check()` + `esp_core_dump_get_summary()`) once at `begin()` — no custom panic hook, nothing runs inside the panic handler itself, so there's no risk to the crash path. If a coredump is present, it extracts the faulting task name, program counter, Xtensa exception cause, and faulting virtual address into a `CrashReport` struct, then erases the coredump from flash (`esp_core_dump_image_erase()`) so it's reported exactly once, not re-sent on every subsequent boot. + +A custom RTC-noinit-memory panic hook was considered and rejected — the coredump API already gives strictly more detail (task name + PC + backtrace vs. just a reason string) with less risk (no code runs during the crash itself), for free, since the partition and SDK support already existed. + +**MQTT reporting (`CommunicationRouter::reportBootOnce()`, renamed from `reportBootReasonOnce()`):** fires once per boot, on first MQTT connect. Fault resets still additionally publish the existing `status/alerts` WARNING (unchanged trigger/topic). A new consolidated `boot_report` event is **always** published to `vesper/{uid}/status/info`, fault or not: + +```json +{ + "type": "boot_report", + "boot_count": 47, + "reset_reason": "PANIC", + "is_fault": true, + "free_heap": 187234, + "crash": { + "task": "TelemetryTask", + "pc": 1074111832, + "exc_cause": 1, + "exc_vaddr": 0 + } +} +``` + +The `crash` object is present only when `CrashReport::available` is true (a coredump was actually found — e.g. absent on a brownout reset, which doesn't produce one). + +**On-demand access:** `lifetime_boot_count` was also added to `telemetry.get_metrics`, `system.get_telemetry`, and `system.get_all` responses, so a console can poll the same counter without waiting for the next reboot. + +Subsystem: `src/Telemetry/Telemetry.hpp`, `src/Telemetry/Telemetry.cpp`, `src/Communication/CommunicationRouter/CommunicationRouter.cpp`, `src/Communication/Handlers/TelemetryHandler/TelemetryHandler.cpp`, `src/Communication/Handlers/SystemHandler/SystemHandler.cpp` diff --git a/src/Communication/CommunicationRouter/CommunicationRouter.cpp b/src/Communication/CommunicationRouter/CommunicationRouter.cpp index 2b04b74..143d4c1 100644 --- a/src/Communication/CommunicationRouter/CommunicationRouter.cpp +++ b/src/Communication/CommunicationRouter/CommunicationRouter.cpp @@ -130,7 +130,7 @@ void CommunicationRouter::begin() { Logging::setSubsystemMqttLevel("OTAManager", Logging::INFO); // update events important _mqttClient.setOnConnectCallback([this](bool /*sessionPresent*/) { - reportBootReasonOnce(); + reportBootOnce(); }); LOG_INFO(TAG, "MQTT transport initialised"); @@ -500,21 +500,43 @@ void CommunicationRouter::publishAlert(const String& subsystem, const String& ne LOG_DEBUG(TAG, "Alert published: %s → %s", subsystem.c_str(), newState.c_str()); } -void CommunicationRouter::reportBootReasonOnce() { +void CommunicationRouter::reportBootOnce() { if (_bootReasonReported || !_telemetry) return; _bootReasonReported = true; String reason = _telemetry->getResetReasonString(); + bool isFault = _telemetry->isFaultReset(); - if (_telemetry->isFaultReset()) { + // Existing fault alert — unchanged trigger condition and topic, so consoles + // already handling this WARNING keep working as-is. + if (isFault) { publishAlert("System", "WARNING", "Device reset due to fault: " + reason); LOG_WARNING(TAG, "Fault reset reported: %s", reason.c_str()); - } else { - JsonDocument payload; - payload["reason"] = reason; - publishInfo("boot_reason", payload); - LOG_INFO(TAG, "Boot reason reported: %s", reason.c_str()); } + + // Consolidated boot report — always published, fault or not. Single place + // a console needs to watch for "device rebooted" plus everything useful + // about why: lifetime boot count, reset reason, and (if the last reset was + // a crash with a coredump available) the faulting task/PC/exception detail. + JsonDocument payload; + payload["boot_count"] = _telemetry->getLifetimeBootCount(); + payload["reset_reason"] = reason; + payload["is_fault"] = isFault; + payload["free_heap"] = (uint32_t)ESP.getFreeHeap(); + + const CrashReport& crash = _telemetry->getCrashReport(); + if (crash.available) { + JsonObject crashObj = payload["crash"].to(); + crashObj["task"] = crash.taskName; + crashObj["pc"] = crash.pc; + crashObj["exc_cause"] = crash.excCause; + crashObj["exc_vaddr"] = crash.excVaddr; + } + + publishInfo("boot_report", payload); + LOG_INFO(TAG, "Boot report published: count=%lu reason=%s%s", + _telemetry->getLifetimeBootCount(), reason.c_str(), + crash.available ? " (crash detail included)" : ""); } void CommunicationRouter::publishInfo(const String& type, const JsonDocument& payload) { diff --git a/src/Communication/CommunicationRouter/CommunicationRouter.hpp b/src/Communication/CommunicationRouter/CommunicationRouter.hpp index 6d0b63b..168d4c2 100644 --- a/src/Communication/CommunicationRouter/CommunicationRouter.hpp +++ b/src/Communication/CommunicationRouter/CommunicationRouter.hpp @@ -138,11 +138,13 @@ public: void onNetworkDisconnected(); private: - // Reports the boot reset reason once, the first time MQTT connects after - // startup. Fault reasons (panic/watchdog/brownout) go to status/alerts; - // expected reasons (power-on, software reset, deep sleep wake) go to - // status/info. Registered as MQTTDriver's onConnect callback in begin(). - void reportBootReasonOnce(); + // Reports boot state once, the first time MQTT connects after startup: + // lifetime boot count, reset reason, and (if the last reset was a crash) + // the coredump summary — faulting task name, PC, exception cause/vaddr. + // Fault reasons additionally go to status/alerts (existing WARNING alert, + // unchanged); this consolidated report always goes to status/info, + // fault or not. Registered as MQTTDriver's onConnect callback in begin(). + void reportBootOnce(); bool _bootReasonReported = false; // ── External dependencies (injected) ──────────────────────────────────── diff --git a/src/Communication/CommunicationRouter/README.md b/src/Communication/CommunicationRouter/README.md index db3e492..e9e04f4 100644 --- a/src/Communication/CommunicationRouter/README.md +++ b/src/Communication/CommunicationRouter/README.md @@ -49,8 +49,8 @@ | `void broadcastToAllWebSocketClients(const JsonDocument& msg)` | Serialises then sends to all WebSocket clients. | | `void publishToMqtt(const String& data)` | Publishes to the device data topic. No-op if MQTT is not connected. | | `void sendBellOverloadNotification(const std::vector& bells, const std::vector& loads, const String& severity)` | Builds and broadcasts a structured `bell_overload` INFO event. | -| `void publishAlert(const String& subsystem, const String& newState, const String& message)` | Publishes a subsystem state-change event to `vesper/{uid}/status/alerts` (QoS 1). `newState` is one of `"WARNING"`, `"CRITICAL"`, `"FAILED"`, or `"CLEARED"`. Called automatically by the HealthMonitor alert callback registered in `begin()`, and by `reportBootReasonOnce()` for fault reset reasons. No-op if MQTT is not connected. | -| `void publishInfo(const String& type, const JsonDocument& payload)` | Publishes a general device state event to `vesper/{uid}/status/info` (QoS 0). No-op if MQTT is not connected. Used for e.g. `"boot_reason"` events on expected resets. | +| `void publishAlert(const String& subsystem, const String& newState, const String& message)` | Publishes a subsystem state-change event to `vesper/{uid}/status/alerts` (QoS 1). `newState` is one of `"WARNING"`, `"CRITICAL"`, `"FAILED"`, or `"CLEARED"`. Called automatically by the HealthMonitor alert callback registered in `begin()`, and by `reportBootOnce()` for fault reset reasons. No-op if MQTT is not connected. | +| `void publishInfo(const String& type, const JsonDocument& payload)` | Publishes a general device state event to `vesper/{uid}/status/info` (QoS 0). No-op if MQTT is not connected. Used for e.g. the `"boot_report"` event published once per boot — see below. | ### Network callbacks (called by Networking) @@ -118,6 +118,24 @@ If any required reference is null when `registerHandlers()` runs (inside `begin( - **`server.begin()` is deferred**: The `AsyncWebServer` is not started inside `begin()` — it is started in the `onNetworkConnected` callback in `main.cpp`. This prevents a port 80 conflict when WiFiManager's captive portal is active. - **`loop()` must be called**: `UARTTransport` is the only transport that requires polling. `CommunicationRouter::loop()` delegates to it. All other transports are fully event-driven. - **MQTT log suppression**: During `begin()`, the subsystem MQTT log levels for `"MQTTClient"` and `"CommRouter"` are explicitly suppressed to `NONE` and `WARNING` respectively to prevent feedback loops when MQTT is used as a log sink. -- **Boot reason reporting**: `begin()` registers a one-shot `onConnect` callback on `MQTTDriver` (`reportBootReasonOnce()`) that fires the first time MQTT connects after startup (including the very first connection). It reads `Telemetry::getResetReasonString()`/`isFaultReset()` and routes to `publishAlert` (fault reasons: panic, watchdog, brownout) or `publishInfo` (expected reasons: power-on, software reset, deep sleep wake). Guarded by `_bootReasonReported` so it only fires once per boot, not on every reconnect. +- **Boot reporting**: `begin()` registers a one-shot `onConnect` callback on `MQTTDriver` (`reportBootOnce()`) that fires the first time MQTT connects after startup (including the very first connection). Guarded by `_bootReasonReported` so it only fires once per boot, not on every reconnect. It does two things: + 1. If `Telemetry::isFaultReset()` is true (panic, watchdog, brownout), publishes the existing fault alert via `publishAlert("System", "WARNING", "Device reset due to fault: " + reason)` — unchanged behavior/topic from before. + 2. **Always** — fault or not — publishes a consolidated `"boot_report"` event via `publishInfo` to `vesper/{uid}/status/info`: + ```json + { + "type": "boot_report", + "boot_count": 47, + "reset_reason": "PANIC", + "is_fault": true, + "free_heap": 187234, + "crash": { + "task": "TelemetryTask", + "pc": 1074111832, + "exc_cause": 1, + "exc_vaddr": 0 + } + } + ``` + `boot_count` is `Telemetry::getLifetimeBootCount()` — see [Telemetry's Boot tracking section](../../Telemetry/README.md#boot-tracking) for why this is a separate counter from `FirmwareValidator`'s NVS `boot_count`. The `crash` object is present only when a coredump was found for the crash that caused this boot (`CrashReport::available == true`) — omitted entirely on a clean/expected reset, or when no coredump was captured for a fault reset (e.g. a brownout, which doesn't produce one). - **Broadcast vs CommandBus broadcast**: The `broadcastXxx()` helpers on this class send raw pre-serialised strings. `CommandBus::broadcast()` serialises a `CommandResult` and fans it out. They are separate paths; subsystems outside the communication layer use the router's helpers. - **Handler skipping is silent to clients**: If a reference is null and a handler is not registered, the bus returns `{"status":"ERROR","type":"unknown","message":"Unknown command: ..."}`. There is no boot-time safeguard beyond the `LOG_ERROR` in `registerHandlers()`. diff --git a/src/Communication/Handlers/SystemHandler/SystemHandler.cpp b/src/Communication/Handlers/SystemHandler/SystemHandler.cpp index 4873287..285e550 100644 --- a/src/Communication/Handlers/SystemHandler/SystemHandler.cpp +++ b/src/Communication/Handlers/SystemHandler/SystemHandler.cpp @@ -177,6 +177,7 @@ CommandResult SystemHandler::handleGetTelemetry(const CommandEnvelope& e) { doc["lifetime_runtime_seconds"] = _telemetry.getLifetimeRuntimeSeconds(); doc["session_runtime_seconds"] = _telemetry.getCurrentSessionSeconds(); doc["total_playbacks"] = _telemetry.getTotalPlaybackCount(); + doc["lifetime_boot_count"] = _telemetry.getLifetimeBootCount(); // Device uptime doc["uptime_ms"] = millis(); @@ -227,6 +228,7 @@ CommandResult SystemHandler::handleGetAll(const CommandEnvelope& e) { telemetry["lifetime_runtime_seconds"] = _telemetry.getLifetimeRuntimeSeconds(); telemetry["session_runtime_seconds"] = _telemetry.getCurrentSessionSeconds(); telemetry["total_playbacks"] = _telemetry.getTotalPlaybackCount(); + telemetry["lifetime_boot_count"] = _telemetry.getLifetimeBootCount(); // ── Player status ────────────────────────────────────────────────────── JsonObject player = doc["player"].to(); diff --git a/src/Communication/Handlers/TelemetryHandler/TelemetryHandler.cpp b/src/Communication/Handlers/TelemetryHandler/TelemetryHandler.cpp index 9133ffa..a282046 100644 --- a/src/Communication/Handlers/TelemetryHandler/TelemetryHandler.cpp +++ b/src/Communication/Handlers/TelemetryHandler/TelemetryHandler.cpp @@ -99,6 +99,7 @@ CommandResult TelemetryHandler::handleGetMetrics(const CommandEnvelope& e) { doc["session_runtime_seconds"] = _telemetry.getCurrentSessionSeconds(); doc["total_playbacks"] = _telemetry.getTotalPlaybackCount(); doc["guard_enabled"] = _telemetry.isGuardEnabled(); + doc["lifetime_boot_count"] = _telemetry.getLifetimeBootCount(); return CommandResult::ok("telemetry.get_metrics", doc); } diff --git a/src/Telemetry/README.md b/src/Telemetry/README.md index 137deef..f2c80a4 100644 --- a/src/Telemetry/README.md +++ b/src/Telemetry/README.md @@ -29,6 +29,8 @@ Telemetry tracks per-bell strike counts and thermal load to protect actuators fr | `esp_reset_reason_t getResetReason() const` | Returns the ESP32 reset reason captured once at `begin()`, via `esp_reset_reason()`. | | `bool isFaultReset() const` | Returns `true` if the captured reset reason indicates a fault: `ESP_RST_PANIC`, `ESP_RST_INT_WDT`, `ESP_RST_TASK_WDT`, `ESP_RST_WDT`, or `ESP_RST_BROWNOUT`. `false` for expected resets (power-on, software reset/OTA, deep sleep wake, etc). | | `String getResetReasonString() const` | Human-readable reset reason, e.g. `"PANIC"`, `"POWERON"`, `"TASK_WATCHDOG"`. | +| `uint32_t getLifetimeBootCount() const` | NVS-backed count of every boot this device has ever done. The authoritative counter — see [Boot tracking](#boot-tracking) below for why this exists alongside two other, narrower counters. | +| `const CrashReport& getCrashReport() const` | Coredump summary from the most recent crash, if one was found at `begin()`. `.available` is `false` when the last reset wasn't a crash, or no coredump was present for one that was. | --- @@ -69,6 +71,8 @@ communication.setTelemetryReference(&telemetry); | `Logging` | Required | All log output | | FreeRTOS | Required | `xTaskCreatePinnedToCore`, `portMUX_TYPE` spinlock | | ArduinoJson | Required | JSON serialisation for SD persistence | +| NVS (`nvs.h`) | Required | Lifetime boot counter (`vesper_boot` namespace) — works even without SD | +| ESP-IDF coredump (`esp_core_dump.h`) | Required | Reads the crash coredump summary already written to the `coredump` flash partition by the panic handler. Requires `CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH` and a `coredump` partition table entry — both present by default in this project's `min_spiffs.csv` and precompiled Arduino-ESP32 core. No custom panic hook involved. | --- @@ -86,7 +90,21 @@ communication.setTelemetryReference(&telemetry); **Heat model.** The thermal model is a simple increment/decrement counter, not a physical model. One strike adds 1 unit of load; 1 unit decays per second. A bell with `maxLoad = 200` (the default) tolerates sustained rates up to ~200 strikes per second before triggering overload, which is far beyond any realistic bell schedule. The threshold is more useful as a runaway-loop guard than a true thermal limit. Adjust per-bell thresholds via `setBellMaxLoad()` if tighter protection is needed for a specific installation. -**Reset reason capture.** `resetReason` is read once at the very top of `begin()`, before anything else can crash again this boot. It's included in the boot log entry written by `logBootEvent()` (field `"reason"`) so it's available on SD even for offline devices. For online devices, `CommunicationRouter` reports it once, the first time MQTT connects after boot: fault reasons go to `vesper/{uid}/status/alerts` (via `publishAlert`), expected reasons go to `vesper/{uid}/status/info` (via `publishInfo`, event type `"boot_reason"`). See [CommunicationRouter](../Communication/CommunicationRouter/README.md). +**Reset reason capture.** `resetReason` is read once at the very top of `begin()`, before anything else can crash again this boot. It's included in the boot log entry written by `logBootEvent()` (field `"reason"`) so it's available on SD even for offline devices. For online devices, `CommunicationRouter::reportBootOnce()` publishes a consolidated report the first time MQTT connects after boot — see [Boot tracking](#boot-tracking) and [CommunicationRouter](../Communication/CommunicationRouter/README.md). + +### Boot tracking + +There are three separate, intentionally-distinct boot/crash mechanisms in the firmware. They look similar and are easy to conflate — here's what each one is actually for: + +| Mechanism | Storage | Scope | Survives SD failure? | Use it for | +|---|---|---|---|---| +| `Telemetry::getLifetimeBootCount()` | NVS, namespace `vesper_boot` | Whole device lifetime | Yes | **The authoritative answer to "how many times has this device rebooted, ever."** Used by `CommunicationRouter::reportBootOnce()` and exposed via `telemetry.get_metrics` / `system.get_telemetry` / `system.get_all`. | +| `FirmwareValidator::getBootCount()` | NVS, namespace `fw_validator` | Boots since this firmware image was flashed (feeds rollback-safety logic) | Yes | Firmware-validation decisions only (`firmware.status`'s `boot_count`). Do not use this as a lifetime counter — it's scoped to the current OTA slot's validation window, not the device's history. | +| `Telemetry::logBootEvent()` → `/telemetry_boot_log.json` | SD card, rotating array (last 200 entries) | Timestamped history of recent boots | **No** — silently produces no entry without an SD card or before NTP sync | Browsing recent boot history with timestamps (e.g. "show me the last 10 reboots and when"). Its own `total_boots` field is **not** a reliable counter — use `getLifetimeBootCount()` instead. | + +**Coredump-based crash detail.** `captureCrashReport()` runs once at `begin()`, right after `initBootTracking()`. It calls `esp_core_dump_image_check()` — if the last reset left a coredump in the `coredump` flash partition (written automatically by the ESP-IDF panic handler; this is stock ESP-IDF behavior already enabled in this project, not something this firmware added), it reads the summary via `esp_core_dump_get_summary()` into `CrashReport` (faulting task name, program counter, Xtensa exception cause and faulting virtual address — the same information the serial monitor prints as a register dump at the moment of the crash, but retrievable in code after reboot). The dump is erased from flash immediately after reading (`esp_core_dump_image_erase()`) so it's reported exactly once, not re-sent on every subsequent boot. + +This required no custom panic hook — `esp_core_dump_get_summary()` is a documented, "user mode" API safe to call from ordinary application code after boot; nothing runs inside the panic handler itself. **Remote commands (via TelemetryHandler).** The following v2 commands are handled by `TelemetryHandler` and routed through `CommunicationRouter`: diff --git a/src/Telemetry/Telemetry.cpp b/src/Telemetry/Telemetry.cpp index 02a0d01..51275b8 100644 --- a/src/Telemetry/Telemetry.cpp +++ b/src/Telemetry/Telemetry.cpp @@ -2,11 +2,15 @@ #define TAG "Telemetry" #include +#include void Telemetry::begin() { resetReason = esp_reset_reason(); LOG_INFO(TAG, "Reset reason: %s%s", getResetReasonString().c_str(), isFaultReset() ? " (FAULT)" : ""); + initBootTracking(); + captureCrashReport(); + for (uint8_t i = 0; i < 16; i++) { strikeCounters[i] = 0; bellLoad[i] = 0; @@ -57,6 +61,58 @@ String Telemetry::getResetReasonString() const { } } +// ════════════════════════════════════════════════════════════════════════════ +// BOOT TRACKING — lifetime counter + crash coredump summary +// ════════════════════════════════════════════════════════════════════════════ + +void Telemetry::initBootTracking() { + // Separate NVS namespace from FirmwareValidator's "fw_validator" — this + // counter tracks the device's whole lifetime, not boots-since-this-firmware- + // image-was-flashed, so it must not share storage or reset semantics. + esp_err_t err = nvs_open("vesper_boot", NVS_READWRITE, &_bootNvsHandle); + if (err != ESP_OK) { + LOG_ERROR(TAG, "Failed to open boot-tracking NVS namespace: %s", esp_err_to_name(err)); + return; + } + + uint32_t count = 0; + nvs_get_u32(_bootNvsHandle, "lifetime_boots", &count); // defaults to 0 if key absent + count++; + nvs_set_u32(_bootNvsHandle, "lifetime_boots", count); + nvs_commit(_bootNvsHandle); + + lifetimeBootCount = count; + LOG_INFO(TAG, "Lifetime boot count: %lu", lifetimeBootCount); +} + +void Telemetry::captureCrashReport() { + if (esp_core_dump_image_check() != ESP_OK) { + return; // no coredump present — expected on a non-crash reset + } + + esp_core_dump_summary_t summary; + if (esp_core_dump_get_summary(&summary) != ESP_OK) { + LOG_WARNING(TAG, "Coredump present but summary read failed"); + esp_core_dump_image_erase(); // don't leave a dump we can't parse sitting in flash + return; + } + + crashReport.available = true; + strncpy(crashReport.taskName, summary.exc_task, sizeof(crashReport.taskName) - 1); + crashReport.taskName[sizeof(crashReport.taskName) - 1] = '\0'; + crashReport.pc = summary.exc_pc; + crashReport.excCause = summary.ex_info.exc_cause; + crashReport.excVaddr = summary.ex_info.exc_vaddr; + + LOG_WARNING(TAG, "Crash coredump found — task '%s', PC 0x%08lX, cause %lu, vaddr 0x%08lX", + crashReport.taskName, crashReport.pc, crashReport.excCause, crashReport.excVaddr); + + // Erase immediately after reading — this is a one-shot report. Without this, + // the same coredump would be re-reported on every subsequent boot until the + // next crash overwrites it. + esp_core_dump_image_erase(); +} + void Telemetry::setPlayerReference(bool* isPlayingPtr) { playerIsPlayingPtr = isPlayingPtr; LOG_DEBUG(TAG, "Player reference set"); diff --git a/src/Telemetry/Telemetry.hpp b/src/Telemetry/Telemetry.hpp index 55a52e5..6417c69 100644 --- a/src/Telemetry/Telemetry.hpp +++ b/src/Telemetry/Telemetry.hpp @@ -55,11 +55,29 @@ #include #include +#include #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "../Logging/Logging.hpp" #include "../FileManager/FileManager.hpp" +// Coredump summary retrieval (esp_core_dump_get_summary) — populated by the ESP-IDF +// panic handler automatically on every crash (already enabled in this project's SDK +// build; no custom panic hook needed). See CrashReport below. +#include + +// Most recent crash's coredump summary, captured once at begin() and erased from +// flash immediately after reading so it's reported exactly once. Empty/zeroed +// fields when no coredump was present (e.g. expected reset, or reset predates +// coredump support). +struct CrashReport { + bool available = false; + char taskName[16] = {0}; // esp_core_dump_summary_t::exc_task + uint32_t pc = 0; // Program counter at exception + uint32_t excCause = 0; // Xtensa exception cause code + uint32_t excVaddr = 0; // Faulting virtual address +}; + // Maximum number of boot log entries retained on SD (rotating) static constexpr uint16_t BOOT_LOG_MAX_ENTRIES = 200; // Runtime flush interval in milliseconds (10 minutes) @@ -96,6 +114,20 @@ private: // Reset reason, captured once at begin() esp_reset_reason_t resetReason = ESP_RST_UNKNOWN; + // Lifetime boot counter — separate from FirmwareValidator's NVS boot_count + // (which tracks boots-since-this-firmware-was-flashed for rollback safety). + // This one is the device's whole-life reboot count, the single source of + // truth for "how many times has this device rebooted, ever." See + // docs/features/feature-catalog.md for why two counters exist. + nvs_handle_t _bootNvsHandle = 0; + uint32_t lifetimeBootCount = 0; + + // Most recent crash's coredump summary, if any — read once at begin(). + CrashReport crashReport; + + void initBootTracking(); // opens NVS namespace, increments+persists lifetimeBootCount + void captureCrashReport(); // reads+erases the coredump summary, if present + public: // Initialization void begin(); @@ -136,9 +168,21 @@ public: uint32_t getCurrentSessionSeconds() const { return (millis() - sessionStartMs) / 1000; } void flushRuntimeToSD(); - // Boot log + // Boot log — rotating SD-side history of recent boots (timestamp + reason). + // NOT the authoritative boot counter (SD-only, silently skipped without NTP + // or on no-SD variants) — use getLifetimeBootCount() for that. void logBootEvent(uint32_t bootTimestamp); + // Lifetime boot counter — NVS-backed, works on every variant (SD or not), + // reliable regardless of NTP sync status. The single source of truth for + // "how many times has this device rebooted, ever." + uint32_t getLifetimeBootCount() const { return lifetimeBootCount; } + + // Most recent crash's coredump summary (task name, PC, exception cause/vaddr), + // if one was captured. available == false when the last reset wasn't a crash, + // or no coredump was found for one that was. + const CrashReport& getCrashReport() const { return crashReport; } + // Reset reason (captured once at begin(), before anything else can crash again) esp_reset_reason_t getResetReason() const { return resetReason; } // True if the reset reason indicates a fault (panic, watchdog, brownout) rather