feat(Telemetry): expose SD boot history via telemetry.get_boot_history, fix counter drift

The SD-based boot history (logBootEvent() -> /telemetry_boot_log.json)
was write-only: nothing in the firmware ever read it back, and its
"boot" field was a locally-tallied counter (only advanced on the
NTP-gated write path) that could silently drift from the new
lifetime_boot_count added in the previous commit.

- logBootEvent() now stamps each entry with getLifetimeBootCount()
  directly instead of its own total_boots tally, so the SD history's
  "boot" numbers always agree with what MQTT boot_report and
  telemetry.get_metrics/system.get_telemetry report. The old
  total_boots JSON key is no longer written (old files may still have
  it; current firmware ignores it).
- Each entry now also carries crash detail (task/pc/exc_cause/
  exc_vaddr) when a coredump was captured for that boot, same shape
  as the MQTT boot_report's crash object.
- New Telemetry::getBootHistory() + telemetry.get_boot_history command
  actually exposes the file: optional {"limit": N} (clamped 1-200),
  returns {"count", "boots": [...]}. Returns an error response (not a
  crash or empty success) when there's no SD/FileManager or the file
  doesn't exist yet — expected on agnus (no-SD) variants or before a
  device's first NTP sync.

Full request/response contract documented in Telemetry's README and
feature-catalog.md F-053, written for direct consumption by whoever
builds the console-side retrieval UI.

Verified: pio run on 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:41:17 +03:00
co-authored by Claude Sonnet 5
parent 829ae23f09
commit 957c283788
6 changed files with 156 additions and 6 deletions
+32
View File
@@ -62,6 +62,7 @@ Every feature — user-facing or significant internal mechanism — is listed he
| 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 |
| F-053 | `telemetry.get_boot_history` command + fixed boot-log counter drift + crash detail in SD history | v2.1.3 | Stable |
---
@@ -762,3 +763,34 @@ The `crash` object is present only when `CrashReport::available` is true (a core
**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`
---
### F-053 — `telemetry.get_boot_history` command + fixed boot-log counter drift + crash detail in SD history
**Context — direct follow-up to F-052.** F-052 added an NVS-backed lifetime boot counter and coredump crash capture, reported automatically over MQTT. That work surfaced that the pre-existing SD-based boot history (`Telemetry::logBootEvent()` → `/telemetry_boot_log.json`, written once per boot from `ntpSyncTask` in `main.cpp`) had two problems worth fixing rather than leaving alone:
1. **It was write-only.** Nothing in the firmware ever read `/telemetry_boot_log.json` back — not the firmware itself, not any command handler, not `logs.list`/`logs.download` (which only serve the unrelated day-rotated plain-text `/logs/YYYY-MM-DD.log` files). 200 entries of real boot history were accumulating on every SD-equipped device with no way for a console to ever retrieve them.
2. **Its `"boot"` counter had silently drifted from the new authoritative one.** The file kept its own local tally (`total_boots` in the JSON, incremented only inside `logBootEvent()`) instead of using F-052's new `Telemetry::getLifetimeBootCount()`. Because `logBootEvent()` only runs after a successful NTP sync for that boot (see the NTP-gated gotcha below), a device with intermittent connectivity would have this file's counter fall behind the NVS counter's true value — two numbers that look like they should agree, quietly telling different stories.
**Fix 1 — `logBootEvent()` now uses `lifetimeBootCount` directly** ([Telemetry.cpp](../../src/Telemetry/Telemetry.cpp)) instead of computing its own `doc["total_boots"] + 1`. Every entry's `"boot"` field is now guaranteed consistent with the same counter reported via MQTT `boot_report` and `telemetry.get_metrics`/`system.get_telemetry`/`system.get_all`. The old top-level `"total_boots"` key is no longer written; files from older firmware may still have it lying around — current firmware ignores it, consumers can ignore or discard it.
**Fix 2 — crash detail is now included in each SD history entry** when available, using the same `CrashReport` populated by F-052's `captureCrashReport()`:
```json
{ "ts": 1752600000, "boot": 47, "reason": "PANIC", "crash": { "task": "TelemetryTask", "pc": 1074111832, "exc_cause": 1, "exc_vaddr": 0 } }
```
Same shape as the MQTT `boot_report`'s `crash` object (see F-052) — present only when a coredump was found for that specific boot.
**Fix 3 — new command, `telemetry.get_boot_history`** ([TelemetryHandler.cpp](../../src/Communication/Handlers/TelemetryHandler/TelemetryHandler.cpp)), backed by a new `Telemetry::getBootHistory(JsonDocument&, uint16_t maxEntries)` ([Telemetry.hpp](../../src/Telemetry/Telemetry.hpp)) that reads the file and returns up to N most recent entries. Request takes an optional `{ "limit": N }` (clamped to `[1, 200]`, defaults to all 200). Response: `{ "count": <int>, "boots": [ ...entries, oldest of the selection first... ] }`. Returns a `CommandResult::err` — not a crash or empty success — when there's no SD card, no FileManager, or the file has never been written (expected on `agnus` no-SD variants, or any device that hasn't completed its first NTP sync yet). See [Telemetry's README](../../src/Telemetry/README.md#boot-tracking) for the full request/response contract, including the NTP-gating gotcha (a boot that never reaches NTP sync produces **no entry at all**, not a zeroed one — so this file's entry count can run behind `lifetime_boot_count` on flaky-network devices; that's expected, not a bug).
**Three boot mechanisms remain deliberately separate** (see F-052's table, now joined by this file's corrected role):
| Mechanism | Now used for |
|---|---|
| `Telemetry::getLifetimeBootCount()` (NVS) | The authoritative "how many times, ever" — MQTT `boot_report`, `telemetry.get_metrics`, `system.get_telemetry`, `system.get_all`. |
| `FirmwareValidator::getBootCount()` (NVS, separate namespace) | Unchanged — rollback-safety bookkeeping only, scoped to boots since this OTA slot was flashed. Exposed via `firmware.status`. |
| `Telemetry::logBootEvent()` / `getBootHistory()` (SD) | Timestamped, per-boot history with reason + crash detail — retrievable via `telemetry.get_boot_history`. Its `"boot"` field now just mirrors the NVS counter; it is not an independent count. |
Verified: `pio run` on both `vesper-std-v1` and `agnus-v1` (no-SD variant, where `getBootHistory()` correctly returns `false`/the command returns its error response).
Subsystem: `src/Telemetry/Telemetry.hpp`, `src/Telemetry/Telemetry.cpp`, `src/Communication/Handlers/TelemetryHandler/TelemetryHandler.hpp`, `src/Communication/Handlers/TelemetryHandler/TelemetryHandler.cpp`
@@ -10,7 +10,8 @@ std::vector<String> TelemetryHandler::commands() const {
return {
"telemetry.get_strikes", "telemetry.reset_strikes", "telemetry.get_loads",
"telemetry.set_max_loads", "telemetry.set_guard_enabled",
"telemetry.get_metrics", "telemetry.reset_metrics"
"telemetry.get_metrics", "telemetry.reset_metrics",
"telemetry.get_boot_history"
};
}
@@ -22,6 +23,7 @@ CommandResult TelemetryHandler::execute(const CommandEnvelope& envelope) {
if (envelope.command == "telemetry.set_guard_enabled") return handleSetGuardEnabled(envelope);
if (envelope.command == "telemetry.get_metrics") return handleGetMetrics(envelope);
if (envelope.command == "telemetry.reset_metrics") return handleResetMetrics(envelope);
if (envelope.command == "telemetry.get_boot_history") return handleGetBootHistory(envelope);
return CommandResult::err(envelope.command, "Unknown telemetry command");
}
@@ -108,3 +110,21 @@ CommandResult TelemetryHandler::handleResetMetrics(const CommandEnvelope& e) {
LOG_WARNING(TAG, "Telemetry metrics reset by command");
return CommandResult::ok("telemetry.reset_metrics", "Lifetime runtime and playback count reset to zero");
}
CommandResult TelemetryHandler::handleGetBootHistory(const CommandEnvelope& e) {
// Optional "limit" — defaults to the full 200-entry cap. Clamped to
// [1, BOOT_LOG_MAX_ENTRIES] so a bad value can't return zero entries
// or force reading past what's actually stored.
uint16_t limit = BOOT_LOG_MAX_ENTRIES;
if (e.contents["limit"].is<uint16_t>()) {
uint16_t requested = e.contents["limit"].as<uint16_t>();
limit = (requested == 0) ? 1 : (requested > BOOT_LOG_MAX_ENTRIES ? BOOT_LOG_MAX_ENTRIES : requested);
}
JsonDocument doc;
if (!_telemetry.getBootHistory(doc, limit)) {
return CommandResult::err("telemetry.get_boot_history",
"No boot history available (no SD card, or no boot has completed NTP sync yet)");
}
return CommandResult::ok("telemetry.get_boot_history", doc);
}
@@ -22,4 +22,5 @@ private:
CommandResult handleSetGuardEnabled(const CommandEnvelope& e);
CommandResult handleGetMetrics(const CommandEnvelope& e);
CommandResult handleResetMetrics(const CommandEnvelope& e);
CommandResult handleGetBootHistory(const CommandEnvelope& e);
};
+59 -1
View File
@@ -100,12 +100,35 @@ There are three separate, intentionally-distinct boot/crash mechanisms in the fi
|---|---|---|---|---|
| `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. |
| `Telemetry::logBootEvent()` → `/telemetry_boot_log.json` | SD card, rotating array (last 200 entries) | Timestamped history of recent boots, retrievable via `telemetry.get_boot_history` | **No** — silently produces no entry without an SD card or before NTP sync | Browsing recent boot history with timestamps and (when available) crash detail, e.g. "show me the last 10 reboots, when, and why." Each entry's `"boot"` field is `getLifetimeBootCount()`'s value at the time — **not** a separately-tallied counter (see below). |
**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.
**Boot log entry shape.** Each entry `logBootEvent()` appends to `/telemetry_boot_log.json`'s `"boots"` array:
```json
{
"ts": 1752600000,
"boot": 47,
"reason": "PANIC",
"crash": {
"task": "TelemetryTask",
"pc": 1074111832,
"exc_cause": 1,
"exc_vaddr": 0
}
}
```
- `ts` — Unix timestamp (seconds), from `Timekeeper::getTime()` at the point `logBootEvent()` ran (after NTP sync completed for this boot — see the gotcha below).
- `boot` — `getLifetimeBootCount()`'s value for this boot. Fixed as of this firmware version (F-053) — previously this field was a locally-tallied counter scoped to this file alone (only incremented on the NTP-gated write path), which could silently drift from the NVS-backed `lifetime_boot_count` reported elsewhere (MQTT `boot_report`, `telemetry.get_metrics`). Files written by firmware predating F-053 may contain a `"total_boots"` top-level field alongside `"boots"` — that field is no longer written or read by current firmware and can be ignored/removed by consumers.
- `reason` — same reset-reason string as `getResetReasonString()` / the MQTT `boot_report`'s `reset_reason`.
- `crash` — present only when a coredump was found for the crash that produced this boot (same shape as `boot_report`'s `crash` object over MQTT — see [CommunicationRouter](../Communication/CommunicationRouter/README.md)). Omitted on a clean/expected reset or a fault reset with no coredump (e.g. brownout).
**Gotcha: entries are NTP-gated.** `logBootEvent()` is only called from `ntpSyncTask` in `main.cpp`, after a successful NTP sync for that boot (see `main.cpp`'s `ntpSyncTask`). A boot that never gets network/NTP (offline device, WiFi failure, AP-mode fallback) produces **no entry at all** for that boot — not an entry with a zeroed timestamp. This means the history can have gaps, and the entry count in the file will be less than `lifetime_boot_count` on a device with spotty connectivity. `lifetime_boot_count` (NVS) is unaffected by this — it always increments, network or not.
**Remote commands (via TelemetryHandler).** The following v2 commands are handled by `TelemetryHandler` and routed through `CommunicationRouter`:
| Command | Description |
@@ -113,10 +136,45 @@ This required no custom panic hook — `esp_core_dump_get_summary()` is a docume
| `telemetry.get_strikes` | Returns strike counts for all 16 bells |
| `telemetry.reset_strikes` | Resets all counters to 0 (all-at-once; per-bell reset not yet implemented) |
| `telemetry.get_loads` | Returns current load values, `cooling_active` flag, and list of overloaded bell indices |
| `telemetry.get_boot_history` | Returns recent entries from `/telemetry_boot_log.json` — see below |
**`telemetry.get_boot_history` in detail:**
Request contents (all optional):
```json
{ "limit": 20 }
```
- `limit` — how many of the most recent entries to return, oldest-of-the-selection-first (i.e. still chronological order, just truncated from the front). Omit for the full stored history (up to 200 entries). Clamped server-side to `[1, 200]` — a `0` or missing value is treated as "no limit" (200), and anything above 200 is capped at 200.
Success response:
```json
{
"status": "SUCCESS",
"type": "telemetry.get_boot_history",
"data": {
"count": 3,
"boots": [
{ "ts": 1752599000, "boot": 45, "reason": "POWERON" },
{ "ts": 1752599800, "boot": 46, "reason": "SOFTWARE" },
{ "ts": 1752600000, "boot": 47, "reason": "PANIC", "crash": { "task": "TelemetryTask", "pc": 1074111832, "exc_cause": 1, "exc_vaddr": 0 } }
]
}
}
```
- `count` — number of entries in this response (i.e. `boots.length`), not the total ever recorded.
- `boots` — array of entries in the shape documented above, oldest first, most recent last.
Error response — returned when there's no FileManager reference, no SD card present/initialized, or the file has never been written (e.g. this device has never completed an NTP sync):
```json
{ "status": "ERROR", "type": "telemetry.get_boot_history", "message": "No boot history available (no SD card, or no boot has completed NTP sync yet)" }
```
A console should treat this error as "no history yet," not as a fault — it's an expected, normal response for an `agnus` (no-SD) device, or any device on its very first boot before NTP has synced.
Example requests:
```json
{ "v": 2, "cmd": "telemetry.get_strikes", "contents": {} }
{ "v": 2, "cmd": "telemetry.get_loads", "contents": {} }
{ "v": 2, "cmd": "telemetry.reset_strikes", "contents": {} }
{ "v": 2, "cmd": "telemetry.get_boot_history", "contents": {} }
{ "v": 2, "cmd": "telemetry.get_boot_history", "contents": { "limit": 20 } }
```
+36 -4
View File
@@ -360,20 +360,52 @@ void Telemetry::logBootEvent(uint32_t bootTimestamp) {
entries = doc["boots"].as<JsonArray>();
}
uint32_t bootNum = (uint32_t)(doc["total_boots"] | 0) + 1;
// "boot" is the same lifetime_boot_count reported over MQTT (boot_report,
// telemetry.get_metrics, etc.) — NOT a locally-tallied total_boots. The two
// used to be separate counters that could silently drift apart (this file
// previously only advanced its own counter here, gated on NTP success,
// while the NVS counter increments on every boot regardless of network).
// See docs/features/feature-catalog.md F-053.
JsonObject entry = entries.add<JsonObject>();
entry["ts"] = bootTimestamp;
entry["boot"] = bootNum;
entry["boot"] = lifetimeBootCount;
entry["reason"] = getResetReasonString();
doc["total_boots"] = bootNum;
if (crashReport.available) {
JsonObject crash = entry["crash"].to<JsonObject>();
crash["task"] = crashReport.taskName;
crash["pc"] = crashReport.pc;
crash["exc_cause"] = crashReport.excCause;
crash["exc_vaddr"] = crashReport.excVaddr;
}
if (!fileManager->writeJsonFile("/telemetry_boot_log.json", doc)) {
LOG_WARNING(TAG, "Failed to write boot log");
} else {
LOG_INFO(TAG, "Boot #%u logged at timestamp %u", bootNum, bootTimestamp);
LOG_INFO(TAG, "Boot #%lu logged at timestamp %u", lifetimeBootCount, bootTimestamp);
}
}
bool Telemetry::getBootHistory(JsonDocument& outEntries, uint16_t maxEntries) {
if (!fileManager) return false;
JsonDocument doc;
if (!fileManager->readJsonFile("/telemetry_boot_log.json", doc)) {
return false; // no SD, or file doesn't exist yet (e.g. NTP never synced)
}
JsonArray entries = doc["boots"].as<JsonArray>();
if (entries.isNull()) return false;
JsonArray out = outEntries["boots"].to<JsonArray>();
size_t total = entries.size();
size_t start = (total > maxEntries) ? (total - maxEntries) : 0;
for (size_t i = start; i < total; i++) {
out.add(entries[i]);
}
outEntries["count"] = out.size();
return true;
}
void Telemetry::loadMetrics() {
if (!fileManager) return;
+7
View File
@@ -173,6 +173,13 @@ public:
// or on no-SD variants) — use getLifetimeBootCount() for that.
void logBootEvent(uint32_t bootTimestamp);
// Reads /telemetry_boot_log.json and populates outEntries with up to
// maxEntries of the most recent boot records (each: ts, boot, reason,
// and optionally crash — see logBootEvent()). Returns false (outEntries
// left untouched) if there's no FileManager, no SD card, or no boot log
// file yet written. Used by telemetry.get_boot_history.
bool getBootHistory(JsonDocument& outEntries, uint16_t maxEntries = BOOT_LOG_MAX_ENTRIES);
// 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."