feat(Telemetry,CommunicationRouter): lifetime boot counter + coredump crash detail over MQTT

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 <noreply@anthropic.com>
This commit is contained in:
2026-07-16 11:17:41 +03:00
co-authored by Claude Sonnet 5
parent 381465cfe4
commit 829ae23f09
9 changed files with 227 additions and 19 deletions
@@ -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<JsonObject>();
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) {
@@ -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) ────────────────────────────────────
@@ -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<uint8_t>& bells, const std::vector<uint16_t>& 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()`.
@@ -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<JsonObject>();
@@ -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);
}
+19 -1
View File
@@ -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`:
+56
View File
@@ -2,11 +2,15 @@
#define TAG "Telemetry"
#include <ArduinoJson.h>
#include <cstring>
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");
+45 -1
View File
@@ -55,11 +55,29 @@
#include <Arduino.h>
#include <esp_system.h>
#include <nvs.h>
#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 <esp_core_dump.h>
// 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