# 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](#boot-tracking) below for why this exists alongside two other, narrower counters. | | `bool resetBootData()` | Zeroes the lifetime boot counter (NVS `vesper_boot`) and deletes the SD boot history log (`/telemetry_boot_log.json`). Used by `telemetry.reset_boot_data` — a QA-to-shipping reset, see F-057 in the [feature catalog](../../docs/features/feature-catalog.md). Does NOT touch `FirmwareValidator`'s separate NVS namespace. Returns `false` only if the NVS write itself failed; the SD deletion is always best-effort. | | `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. | | `void sampleDiagnosticsIfDue()` | Called from `TelemetryTask`'s existing 1s loop. Reads `temperatureRead()` every `DIAGNOSTICS_SAMPLE_INTERVAL_MS` (15s) and folds it into `temperatureStats`. See [Diagnostics reporting](#diagnostics-reporting) below. | | `const RunningStats& getTemperatureStats() const` | Current accumulated min/max/avg temperature since the last `resetDiagnosticsStats()`. | | `void writeTemperatureStats(JsonDocument&) const` | Writes the `cpu_temp` object into the given document without resetting the accumulator (a peek, not a consuming read) — used by `telemetry.get_diagnostics`. Omits the field entirely if no samples exist yet. | | `void resetDiagnosticsStats()` | Zeroes the temperature accumulator. Called after each periodic diagnostics report, not after an on-demand `telemetry.get_diagnostics` read. | | `static void registerTaskForStackMonitoring(const char*, TaskHandle_t)` | Registers a task for stack-headroom reporting in future diagnostics reports. Call once per task, any time after creation — a `nullptr` handle is silently ignored. Fixed 8-slot registry (this codebase's established no-dynamic-allocation style). | | `static void writeStackHighWaterMarks(JsonObject&)` | Writes `{"TaskName": bytesFree, ...}` for every registered task. Bytes, not words — converts `uxTaskGetStackHighWaterMark()`'s word count via `sizeof(StackType_t)` so callers don't need to know the platform word size. | --- ## Initialization Setup order in `main.cpp`: ```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](#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, 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 | |---------|-------------| | `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 } } { "v": 2, "cmd": "telemetry.get_diagnostics", "contents": {} } ``` ### Diagnostics reporting A second, lower-frequency reporting mechanism alongside boot tracking above — see F-056 in the [feature catalog](../../docs/features/feature-catalog.md) for full design rationale. Where boot tracking answers "when did this device restart and why," diagnostics reporting answers "how is this device doing right now" across four dimensions that don't belong on the 30s heartbeat (too heavy/low-value at that frequency) but also shouldn't wait indefinitely for an on-demand poll (a real problem could be missed between polls): | Field | Source | Sampling behaviour | |---|---|---| | `cpu_temp` | `Telemetry` (`temperatureRead()`, ESP32 die sensor) | Sampled locally every 15s, reduced to min/max/avg via `RunningStats`, reset after each periodic report | | `wifi_reconnects` | `Networking` | Cumulative lifetime-this-boot counter + last disconnect reason/time — read once per report, monotonic so no samples are lost between reports | | `ota` | `OTAManager` | Current/available version, update-available flag, last check time, last error — read once per report, changes rarely | | `stack_high_water` | `Telemetry`'s static task registry | FreeRTOS's own low-water-mark tracking already does the "don't miss a dip" job — a single read at report time is exactly as informative as continuous polling | **Why temperature alone needs local sampling, and the other three don't:** temperature genuinely fluctuates between reports — a short thermal spike (e.g. a burst of relay activity) could occur and fully subside within the 5-minute gap between two reports, and a device reporting only its *current* value at report time would simply never see it. The other three fields are all monotonic or self-tracking (a reconnect counter only grows; `uxTaskGetStackHighWaterMark()` is itself already a running minimum since task start; OTA state changes only around an actual update) — reading them more often than once per report cannot reveal information a less-frequent read would miss. **Publish cadence.** `CommunicationRouter::reportDiagnosticsIfDue()` checks a `millis()`-diff every main-loop iteration (same lightweight pattern as this class's own `RUNTIME_FLUSH_INTERVAL_MS` check — no new FreeRTOS timer) and publishes to `vesper/{uid}/system/metrics` every `DIAGNOSTICS_REPORT_INTERVAL_MS` (5 minutes) once `_telemetry` is set. Also includes per-bell strike/load data (via `getStrikeCount()`/`getBellLoad()`/`isCoolingActive()`) since moving to the `system/metrics` topic — see [CommunicationRouter's README](../Communication/CommunicationRouter/README.md) for the full payload shape. **On-demand vs. periodic — the accumulator reset distinction.** `telemetry.get_diagnostics` (`TelemetryHandler`) returns the identical shape but calls `writeTemperatureStats()` — a peek — instead of resetting the accumulator afterward. This means polling the command doesn't rob the next scheduled periodic report of samples it would otherwise have seen; only the periodic path's own `resetDiagnosticsStats()` call clears the window. **Stack monitoring coverage.** Only tasks that keep a stored `TaskHandle_t` can be registered — several short-lived tasks in this firmware (`mqttRecon`, `mqttHB`, `mqttConnect`, `netRecon`, `PlayerCtrl`, `MelodyDL`, `ntpSync`) are created with `xTaskCreate(..., NULL)` and discard their handle immediately, so they cannot be monitored this way. Currently registered: `TelemetryTask` (registered in `Telemetry::begin()`) and `HealthMonitor`'s monitoring task (registered in `HealthMonitor::begin()`) — the two tasks F-051's stack-overflow incident named directly. Additional tasks can be added by calling `Telemetry::registerTaskForStackMonitoring()` from their own `begin()`, once a handle exists.