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>
12 KiB
Telemetry
Telemetry tracks per-bell strike counts and thermal load to protect actuators from overuse and enable warranty/maintenance reporting. Each hammer activation increments both a persistent strike counter and an in-memory heat accumulator; a background FreeRTOS task decays the heat values every second and triggers a force-stop via callback if any bell crosses its maximum load threshold. Strike counters survive reboots by persisting to /telemetry_data.json on the SD card. The subsystem is intentionally lightweight — it owns no network or UI logic; external subsystems (BellEngine, TelemetryHandler) read from it and act on its state.
Public API
| Method | Description |
|---|---|
void begin() |
Initializes arrays, loads persisted strike counters from SD (if available), and starts TelemetryTask on Core 1 at priority 2. |
void setPlayerReference(bool* isPlayingPtr) |
Provides a pointer to Player::isPlaying so the background task can skip processing when no playback is active. Must be called before begin(). |
void setFileManager(FileManager* fm) |
Provides the FileManager used for SD persistence. Optional — if not set, save/load calls are silently skipped. |
void setForceStopCallback(void (*callback)()) |
Registers a zero-argument callback invoked when any bell's load exceeds its maximum. In production this calls player.forceStop(). |
void recordBellStrike(uint8_t bellIndex) |
Increments strikeCounters[bellIndex] and bellLoad[bellIndex] by 1 under spinlock. Sets the system-wide coolingActive flag. Called by BellEngine on every hammer activation. |
uint32_t getStrikeCount(uint8_t bellIndex) |
Returns the cumulative strike count for a bell (0–15). Returns 0 for out-of-range indices. |
void resetStrikeCounters() |
Zeroes all 16 strike counters under spinlock. Does not reset bell loads. Does not auto-save; the caller is responsible for persistence if needed. |
void saveStrikeCounters() |
Serialises strike counters to /telemetry_data.json via FileManager. Called by Player on melody end and on forced stop. |
void loadStrikeCounters() |
Deserialises strike counters from /telemetry_data.json. Called automatically during begin(). |
uint16_t getBellLoad(uint8_t bellIndex) |
Returns the current heat accumulator value for a bell. Decremented by 1 per second by the background task. |
void setBellMaxLoad(uint8_t bellIndex, uint16_t maxLoad) |
Overrides the per-bell overload threshold (default: 200). |
bool isOverloaded(uint8_t bellIndex) |
Returns true when bellLoad[bellIndex] > bellMaxLoad[bellIndex]. |
bool isCoolingActive() |
Returns true if any bell still has residual heat (i.e. bellLoad > 0 for at least one bell). |
void pause() |
Suspends the background task's processing loop. Called by OTAManager before a firmware flash to prevent SD writes mid-update. |
void resume() |
Re-enables background task processing after OTA completes or aborts. |
bool isHealthy() const |
Returns true if the task is running, the player reference is set, and no bell is currently overloaded. Polled by HealthMonitor. |
void logTemperature(float temperature) |
Stub — logs value to serial only. No persistent storage or analysis yet. |
void logVibration(float vibration) |
Stub — logs value to serial only. No persistent storage or analysis yet. |
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 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. |
Initialization
Setup order in main.cpp:
// 1. Provide dependencies BEFORE begin()
telemetry.setPlayerReference(&player.isPlaying); // must exist before begin()
telemetry.setForceStopCallback([]() { player.forceStop(); });
telemetry.setFileManager(&fileManager); // optional but needed for persistence
// 2. Start the subsystem
telemetry.begin(); // loads counters from SD, spawns TelemetryTask
// 3. Register with HealthMonitor
healthMonitor.setTelemetry(&telemetry);
// 4. OTAManager receives the pointer for freeze mode
otaManager.setTelemetry(&telemetry);
// 5. CommunicationRouter receives the pointer for handler registration
communication.setTelemetryReference(&telemetry);
FileManager does not need to be fully initialised before begin() is called — the load attempt inside begin() silently exits if the file is missing or the FileManager pointer is null. The Player object must exist at the time setPlayerReference is called, but player.begin() can happen after telemetry.begin().
Dependencies
| Dependency | Required | Purpose |
|---|---|---|
FileManager |
Optional | Read/write /telemetry_data.json on SD card |
Player::isPlaying (bool*) |
Required | Gates background processing to active playback / cooling |
| Force-stop callback | Required for overload protection | Calls player.forceStop() on overload |
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. |
Gotchas / Notes
Thread safety. recordBellStrike(), resetStrikeCounters(), saveStrikeCounters(), and loadStrikeCounters() all use a portMUX_TYPE spinlock (portENTER_CRITICAL / portEXIT_CRITICAL). These are safe to call from any task or ISR context. getBellLoad(), isOverloaded(), and isCoolingActive() are not spinlock-protected and are intended for read-only polling from a single task (BellEngine or TelemetryHandler); concurrent writes from checkBellLoads() are unlikely to cause corruption but are not formally atomic.
Background task. TelemetryTask runs on Core 1 at priority 2 with a 4096-byte stack. It wakes every 1000 ms. Processing is skipped entirely when isPaused is set (OTA freeze mode) or when neither isPlaying nor coolingActive is true. This means load decay halts if no strike has occurred since the last play session — load values will be stale until the next play starts.
Overload detection and force-stop. When checkBellLoads() finds any bell with load > maxLoad, it invokes the force-stop callback. The callback runs in the context of TelemetryTask on Core 1. Ensure the callback (player.forceStop()) is safe to call from Core 1.
Save timing. Strike counters are saved to SD by Player at melody end and forced stop — not by Telemetry itself on a timer. If power is lost mid-melody, the current session's strikes are lost. There is no periodic auto-save.
SD dependency at boot. If the SD card is absent at boot, loadStrikeCounters() silently succeeds with all-zero counters — there is no warning that previously persisted data is unavailable.
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::reportBootOnce() publishes a consolidated report the first time MQTT connects after boot — see Boot tracking and CommunicationRouter.
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:
| Command | Description |
|---|---|
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 |
Example requests:
{ "v": 2, "cmd": "telemetry.get_strikes", "contents": {} }
{ "v": 2, "cmd": "telemetry.get_loads", "contents": {} }
{ "v": 2, "cmd": "telemetry.reset_strikes", "contents": {} }