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);
}