diff --git a/docs/features/feature-catalog.md b/docs/features/feature-catalog.md index e708886..e0fc099 100644 --- a/docs/features/feature-catalog.md +++ b/docs/features/feature-catalog.md @@ -65,6 +65,7 @@ Every feature — user-facing or significant internal mechanism — is listed he | F-053 | `telemetry.get_boot_history` command + fixed boot-log counter drift + crash detail in SD history | v2.1.3 | Stable | | F-054 | Console Health tab support — `free_heap` on heartbeat + `ping` round-trip timestamp echo | v2.1.4 | Stable | | F-055 | Fix: heap-exhaustion abort() under rapid MQTT command bursts — free-heap guard on publish + command intake | v2.1.4 | Stable | +| F-056 | Diagnostics report — CPU temperature, WiFi reconnects, OTA state, stack high-water mark, published automatically every 5 min + on-demand via `telemetry.get_diagnostics` | v2.1.5 | Stable | --- @@ -854,3 +855,48 @@ xtensa-esp32-elf-addr2line.exe -pfiaC -e .pio/build/vesper-std-v1/firmware.elf 0 Verified: `pio run` on both `vesper-std-v1` and `agnus-v1`. Subsystem: `src/Communication/Drivers/MQTTDriver/MQTTDriver.hpp`, `src/Communication/Drivers/MQTTDriver/MQTTDriver.cpp`, `src/Communication/Transport/MQTTTransport/MQTTTransport.cpp` + +--- + +### F-056 — Diagnostics report: CPU temperature, WiFi reconnects, OTA state, stack high-water mark + +Second console-requested addition to the Health tab (after F-054's `free_heap`/`ping` work). The console wanted four more metrics — CPU temperature, WiFi reconnect count, firmware/OTA state, and per-task stack headroom — but none of them belonged on the 30s heartbeat: the heartbeat fires forever, per device, at fleet scale, and none of these four need 30-second freshness. Instead, this adds a new low-frequency **diagnostics report**, published every 5 minutes to `status/info` (same transport pattern as F-052's `boot_report`) and additionally queryable on-demand via a new `telemetry.get_diagnostics` command. + +**Local sampling vs. batch send — why they differ per metric.** The console's initial ask was "read everything every 5 minutes." That's fine for three of the four metrics but wrong for temperature: + +| Metric | Behaviour between reports | Sampling strategy | +|---|---|---| +| CPU temperature | Fluctuates continuously — a thermal spike can be short-lived (e.g. a burst of relay activity) and gone by the time a slow report fires | Sampled locally every 15s ([`Telemetry::sampleDiagnosticsIfDue()`](../../src/Telemetry/Telemetry.cpp), called from `TelemetryTask`'s existing 1s loop), reduced to a `RunningStats` min/max/avg accumulator (O(1) per sample, no per-sample storage), reset after each 5-minute report | +| WiFi reconnects | Monotonic counter — only ever increases | Single read at report time. No information is lost by infrequent reads; the counter already remembers every increment | +| Stack high-water mark | `uxTaskGetStackHighWaterMark()` is itself a running low-water-mark maintained by FreeRTOS since the task started — it only ever goes down | Single read at report time — reading more often cannot reveal a lower value than the task's own internal tracking already has | +| OTA state | Changes only around an actual update attempt (rare) | Single read at report time | + +Only temperature needed the local-sampling treatment; over-engineering a sampling buffer for three values that are already monotonic/self-tracking would have added complexity with no benefit. + +**1. CPU temperature.** [Telemetry.hpp](../../src/Telemetry/Telemetry.hpp)/[.cpp](../../src/Telemetry/Telemetry.cpp) add a `RunningStats` accumulator (`sum`/`min`/`max`/`count`, `addSample()`/`average()`/`reset()`) and `sampleDiagnosticsIfDue()`, which reads `temperatureRead()` (ESP32 Arduino core's built-in die-temperature sensor) every `DIAGNOSTICS_SAMPLE_INTERVAL_MS` (15s) and folds it into the accumulator. **Caveat carried into the wire format's docs:** the ESP32's internal sensor reads die temperature, not ambient, and is not a calibrated instrument — useful as a coarse "is this thing running hot" trend, not a precise reading. `logTemperature(float)` (the pre-existing stub noted in Telemetry's own README as "no persistent storage or analysis yet") is untouched — this is a new, separate mechanism, not an implementation of that stub. + +**2. Stack high-water mark.** New static registry in `Telemetry` (`registerTaskForStackMonitoring(name, handle)` / `writeStackHighWaterMarks(JsonObject&)`), backed by a fixed 8-slot array (this codebase's established style — see `strikeCounters[16]` — avoids dynamic allocation). Only tasks that already keep a stored `TaskHandle_t` can be monitored this way; short-lived fire-and-forget tasks created with `xTaskCreate(..., NULL)` (`mqttRecon`, `mqttHB`, `mqttConnect`, `netRecon`, `PlayerCtrl`, `MelodyDL`, `ntpSync`) don't keep a handle and can't be queried. Registered at `begin()` time: `TelemetryTask` itself ([Telemetry.cpp](../../src/Telemetry/Telemetry.cpp)) and `HealthMonitor`'s monitoring task ([HealthMonitor.cpp](../../src/HealthMonitor/HealthMonitor.cpp)) — the two tasks F-051's stack-overflow incident specifically named. Reports bytes free (`uxTaskGetStackHighWaterMark()`'s words-remaining × `sizeof(StackType_t)`), not words, so the console doesn't need to know the platform's word size. + +**3. WiFi reconnect count + last disconnect reason.** [Networking.hpp](../../src/Networking/Networking.hpp)/[.cpp](../../src/Networking/Networking.cpp) add `_reconnectCount` (incremented in `onWiFiConnected()`, guarded by `_bootSequenceComplete` so the initial boot-time connection isn't counted as a "reconnect" — only connects *after* that first one are) and `_lastDisconnectReason`/`_lastDisconnectUptimeMs`, captured in `networkEventHandler()`'s `ARDUINO_EVENT_WIFI_STA_DISCONNECTED` case via the event's `info.wifi_sta_disconnected.reason` field and Arduino-ESP32's own `WiFi.disconnectReasonName()` helper (already shipped in this SDK — no new lookup table needed). Both are in-memory only, reset on reboot by design: a fresh boot legitimately starts a new "how flaky has this session been" count, distinct from the lifetime boot counter (F-052) which already answers "how many times has this device restarted, ever." + +**4. OTA / firmware state.** [OTAManager.hpp](../../src/OTAManager/OTAManager.hpp)/[.cpp](../../src/OTAManager/OTAManager.cpp) add `_lastCheckUptimeMs` (set at the top of `checkForUpdates(channel)`, the single call site both the scheduled and emergency check paths funnel through) and `errorCodeToString(ErrorCode)`. `OTAManager::getStatus()`, `getLastError()`, `getAvailableVersion()`, and `isUpdateAvailable()` already existed but were never wired into any command response before this — `firmware.status` (F-049) only surfaced `FirmwareValidator`'s rollback-safety data, a separate concern (see F-052's boot-counter table for why these two subsystems are kept deliberately distinct). + +**Publishing.** [CommunicationRouter.cpp](../../src/Communication/CommunicationRouter/CommunicationRouter.cpp)'s `reportDiagnosticsIfDue()` — checked from the existing `loop()` (a `millis()`-diff check every main-loop iteration, same lightweight style as `Telemetry`'s own `RUNTIME_FLUSH_INTERVAL_MS` check, not a new FreeRTOS timer) — assembles all four into one payload and calls the existing `publishInfo("diagnostics_report", payload)`: +```json +{ + "type": "diagnostics_report", + "payload": { + "cpu_temp": { "avg": 47.1, "min": 44.8, "max": 52.8, "samples": 20 }, + "wifi_reconnects": { "lifetime_count": 2, "last_reason": "AUTH_EXPIRE", "last_at_uptime_ms": 3600000 }, + "ota": { "current_version": "2.7.3", "update_available": false, "last_check_uptime_ms": 180000, "last_error": "NONE" }, + "stack_high_water": { "TelemetryTask": 1024, "HealthMonitor": 890 } + } +} +``` +`cpu_temp` is omitted entirely if no samples were taken (e.g. the very first report shortly after boot, before 15s has elapsed). + +**On-demand access.** [TelemetryHandler.hpp](../../src/Communication/Handlers/TelemetryHandler/TelemetryHandler.hpp)/[.cpp](../../src/Communication/Handlers/TelemetryHandler/TelemetryHandler.cpp) gain `telemetry.get_diagnostics`, returning the identical shape (unwrapped, per the standard `CommandResult::ok(type, doc)` response envelope — no `"payload"` nesting, unlike the MQTT `status/info` publish). `TelemetryHandler`'s constructor now also takes `OTAManager&` and `Networking&` (previously `Telemetry&` only) — its single construction call site in `CommunicationRouter::registerHandlers()` was updated accordingly. Critically, the on-demand path does **not** reset the temperature accumulator (`Telemetry::writeTemperatureStats()` peeks without consuming) — it's a read, not a report cycle, so a console polling this command doesn't rob the next scheduled 5-minute report of its sampling window. + +**Scope note (RTC/SD independence):** unlike F-054's `ping` addition, none of these four metrics depend on `#if HAS_RTC` or SD-card presence — `temperatureRead()`, `uxTaskGetStackHighWaterMark()`, WiFi events, and `OTAManager` are all available on every board variant. Verified via `pio run` on all four environments (`vesper-std-v1`, `agnus-v1`, `agnus-mini-v1`, `bespoke-rs485-v1`). + +Subsystem: `src/Telemetry/Telemetry.hpp`, `src/Telemetry/Telemetry.cpp`, `src/Networking/Networking.hpp`, `src/Networking/Networking.cpp`, `src/OTAManager/OTAManager.hpp`, `src/OTAManager/OTAManager.cpp`, `src/HealthMonitor/HealthMonitor.cpp`, `src/Communication/CommunicationRouter/CommunicationRouter.hpp`, `src/Communication/CommunicationRouter/CommunicationRouter.cpp`, `src/Communication/Handlers/TelemetryHandler/TelemetryHandler.hpp`, `src/Communication/Handlers/TelemetryHandler/TelemetryHandler.cpp` diff --git a/src/Communication/CommunicationRouter/CommunicationRouter.cpp b/src/Communication/CommunicationRouter/CommunicationRouter.cpp index 143d4c1..0350e91 100644 --- a/src/Communication/CommunicationRouter/CommunicationRouter.cpp +++ b/src/Communication/CommunicationRouter/CommunicationRouter.cpp @@ -185,6 +185,7 @@ void CommunicationRouter::loop() { #if HAS_UART _uartTransport.loop(); #endif + reportDiagnosticsIfDue(); } // ───────────────────────────────────────────────────────────────────────────── @@ -297,7 +298,7 @@ void CommunicationRouter::registerHandlers() { // Telemetry if (_telemetry) { - _bus.registerHandler(std::make_unique(*_telemetry)); + _bus.registerHandler(std::make_unique(*_telemetry, _otaManager, _networking)); } // MQTT control (enable / disable / get_config) @@ -539,6 +540,57 @@ void CommunicationRouter::reportBootOnce() { crash.available ? " (crash detail included)" : ""); } +// Diagnostics report — batched every DIAGNOSTICS_REPORT_INTERVAL_MS (5 min). +// Deliberately separate from the 30s heartbeat: temperature/stack/WiFi- +// reconnect/OTA state don't need 30s freshness, and the heartbeat already +// fires forever, per device, at fleet scale — adding heavier/rarer-need +// fields there is a permanent cost paid whether or not anyone's watching. +// Temperature is locally sampled every 15s by Telemetry::sampleDiagnosticsIfDue() +// (called from TelemetryTask's own loop) and reduced to min/max/avg here, so a +// short-lived spike between two 5-minute reports still gets caught — the other +// three fields (stack high-water, WiFi reconnects, OTA state) are monotonic/ +// cumulative counters where a single read at report time is exactly as +// informative as continuous sampling would be. See docs/features/feature-catalog.md. +void CommunicationRouter::reportDiagnosticsIfDue() { + if (!_telemetry) return; + uint32_t now = millis(); + if (now - _lastDiagnosticsReportMs < DIAGNOSTICS_REPORT_INTERVAL_MS) return; + _lastDiagnosticsReportMs = now; + + JsonDocument payload; + + // CPU temperature — min/max/avg since the last report. Captured before + // reset() so this report gets the full accumulated window. + uint16_t tempSampleCount = _telemetry->getTemperatureStats().count; + _telemetry->writeTemperatureStats(payload); + _telemetry->resetDiagnosticsStats(); + + // WiFi reconnects — lifetime this boot, plus last disconnect reason/time. + JsonObject wifiObj = payload["wifi_reconnects"].to(); + wifiObj["lifetime_count"] = _networking.getReconnectCount(); + wifiObj["last_reason"] = _networking.getLastDisconnectReason(); + wifiObj["last_at_uptime_ms"] = _networking.getLastDisconnectUptimeMs(); + + // OTA — current/available version, update-available flag, last check, last error. + JsonObject otaObj = payload["ota"].to(); + otaObj["current_version"] = _otaManager.getCurrentVersion().toString(); + otaObj["update_available"] = _otaManager.isUpdateAvailable(); + if (_otaManager.isUpdateAvailable()) { + otaObj["available_version"] = _otaManager.getAvailableVersion().toString(); + } + otaObj["last_check_uptime_ms"] = _otaManager.getLastCheckUptimeMs(); + otaObj["last_error"] = OTAManager::errorCodeToString(_otaManager.getLastError()); + + // Stack high-water mark — bytes free, per registered task (TelemetryTask, + // HealthMonitor, etc. — see Telemetry::registerTaskForStackMonitoring()). + JsonObject stackObj = payload["stack_high_water"].to(); + Telemetry::writeStackHighWaterMarks(stackObj); + + publishInfo("diagnostics_report", payload); + LOG_INFO(TAG, "Diagnostics report published (temp samples=%u, wifi_reconnects=%lu)", + tempSampleCount, _networking.getReconnectCount()); +} + void CommunicationRouter::publishInfo(const String& type, const JsonDocument& payload) { if (!_mqttClient.isConnected()) return; diff --git a/src/Communication/CommunicationRouter/CommunicationRouter.hpp b/src/Communication/CommunicationRouter/CommunicationRouter.hpp index 168d4c2..7ca6ebf 100644 --- a/src/Communication/CommunicationRouter/CommunicationRouter.hpp +++ b/src/Communication/CommunicationRouter/CommunicationRouter.hpp @@ -36,9 +36,10 @@ #endif #include "../Transport/WebServerTransport/WebServerTransport.hpp" +#include "../../OTAManager/OTAManager.hpp" // needed for OTAManager::ErrorCode in otaErrorCodeToString() + // Forward declarations — resolved in .cpp class ConfigManager; -class OTAManager; class Player; class FileManager; #if HAS_RTC @@ -147,6 +148,15 @@ private: void reportBootOnce(); bool _bootReasonReported = false; + // Publishes a consolidated diagnostics_report to status/info every + // DIAGNOSTICS_REPORT_INTERVAL_MS (5 min) — CPU temperature (min/max/avg + // since last report), WiFi reconnect count + last disconnect reason, OTA + // check/update state, and per-task stack high-water marks. Checked from + // loop() (millis()-diff, same style as Telemetry's own flush-interval + // check) rather than a FreeRTOS timer. No-ops until _telemetry is set. + void reportDiagnosticsIfDue(); + uint32_t _lastDiagnosticsReportMs = 0; + // ── External dependencies (injected) ──────────────────────────────────── ConfigManager& _configManager; OTAManager& _otaManager; diff --git a/src/Communication/CommunicationRouter/README.md b/src/Communication/CommunicationRouter/README.md index e9e04f4..b781ae4 100644 --- a/src/Communication/CommunicationRouter/README.md +++ b/src/Communication/CommunicationRouter/README.md @@ -137,5 +137,16 @@ If any required reference is null when `registerHandlers()` runs (inside `begin( } ``` `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). +- **Diagnostics reporting**: `loop()` calls `reportDiagnosticsIfDue()` every main-loop iteration, which no-ops until `DIAGNOSTICS_REPORT_INTERVAL_MS` (5 minutes, `Telemetry.hpp`) has elapsed and `_telemetry` is set. Unlike `reportBootOnce()` (a one-shot MQTT-onConnect callback), this is a plain `millis()`-diff check — same style as `Telemetry`'s own `RUNTIME_FLUSH_INTERVAL_MS` check — so it fires on a fixed wall-clock cadence regardless of MQTT connection churn (a no-op `publishInfo()` call if disconnected, same as any other info event). Publishes a consolidated `"diagnostics_report"` event to `vesper/{uid}/status/info`: + ```json + { + "type": "diagnostics_report", + "cpu_temp": { "avg": 47.1, "min": 44.8, "max": 52.8, "samples": 20 }, + "wifi_reconnects": { "lifetime_count": 2, "last_reason": "AUTH_EXPIRE", "last_at_uptime_ms": 3600000 }, + "ota": { "current_version": "2.7.3", "update_available": false, "last_check_uptime_ms": 180000, "last_error": "NONE" }, + "stack_high_water": { "TelemetryTask": 1024, "HealthMonitor": 890 } + } + ``` + `cpu_temp` pulls from `Telemetry::writeTemperatureStats()` then calls `resetDiagnosticsStats()` — the accumulator is consumed on the periodic path (unlike the on-demand `telemetry.get_diagnostics` command, which peeks without resetting). `wifi_reconnects`/`ota` read directly from the router's own `_networking`/`_otaManager` references (constructor-injected, not late-bound — no null guard needed). `stack_high_water` comes from `Telemetry::writeStackHighWaterMarks()`'s static task registry — see [Telemetry's Diagnostics reporting section](../../Telemetry/README.md#diagnostics-reporting) for the full design rationale (F-056 in the feature catalog), including why temperature alone needs local 15s sampling while the other three fields are read once per report. - **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()`. diff --git a/src/Communication/Handlers/TelemetryHandler/TelemetryHandler.cpp b/src/Communication/Handlers/TelemetryHandler/TelemetryHandler.cpp index 4905dc5..a8a32ff 100644 --- a/src/Communication/Handlers/TelemetryHandler/TelemetryHandler.cpp +++ b/src/Communication/Handlers/TelemetryHandler/TelemetryHandler.cpp @@ -1,17 +1,20 @@ #include "TelemetryHandler.hpp" #include "../../../Telemetry/Telemetry.hpp" +#include "../../../OTAManager/OTAManager.hpp" +#include "../../../Networking/Networking.hpp" #include "../../../Logging/Logging.hpp" #define TAG "TelemetryHandler" -TelemetryHandler::TelemetryHandler(Telemetry& telemetry) : _telemetry(telemetry) {} +TelemetryHandler::TelemetryHandler(Telemetry& telemetry, OTAManager& otaManager, Networking& networking) + : _telemetry(telemetry), _otaManager(otaManager), _networking(networking) {} std::vector 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_boot_history" + "telemetry.get_boot_history", "telemetry.get_diagnostics" }; } @@ -24,6 +27,7 @@ CommandResult TelemetryHandler::execute(const CommandEnvelope& 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); + if (envelope.command == "telemetry.get_diagnostics") return handleGetDiagnostics(envelope); return CommandResult::err(envelope.command, "Unknown telemetry command"); } @@ -128,3 +132,33 @@ CommandResult TelemetryHandler::handleGetBootHistory(const CommandEnvelope& e) { } return CommandResult::ok("telemetry.get_boot_history", doc); } + +CommandResult TelemetryHandler::handleGetDiagnostics(const CommandEnvelope& e) { + // On-demand mirror of CommunicationRouter::reportDiagnosticsIfDue()'s + // periodic diagnostics_report — same fields, same shape. Deliberately + // does NOT reset the temperature accumulator (unlike the periodic + // report) — this is a peek, not a consuming read, so the next scheduled + // 5-minute report still sees the full sampling window. + JsonDocument doc; + + _telemetry.writeTemperatureStats(doc); + + JsonObject wifiObj = doc["wifi_reconnects"].to(); + wifiObj["lifetime_count"] = _networking.getReconnectCount(); + wifiObj["last_reason"] = _networking.getLastDisconnectReason(); + wifiObj["last_at_uptime_ms"] = _networking.getLastDisconnectUptimeMs(); + + JsonObject otaObj = doc["ota"].to(); + otaObj["current_version"] = _otaManager.getCurrentVersion().toString(); + otaObj["update_available"] = _otaManager.isUpdateAvailable(); + if (_otaManager.isUpdateAvailable()) { + otaObj["available_version"] = _otaManager.getAvailableVersion().toString(); + } + otaObj["last_check_uptime_ms"] = _otaManager.getLastCheckUptimeMs(); + otaObj["last_error"] = OTAManager::errorCodeToString(_otaManager.getLastError()); + + JsonObject stackObj = doc["stack_high_water"].to(); + Telemetry::writeStackHighWaterMarks(stackObj); + + return CommandResult::ok("telemetry.get_diagnostics", doc); +} diff --git a/src/Communication/Handlers/TelemetryHandler/TelemetryHandler.hpp b/src/Communication/Handlers/TelemetryHandler/TelemetryHandler.hpp index 72ac00f..96cdd77 100644 --- a/src/Communication/Handlers/TelemetryHandler/TelemetryHandler.hpp +++ b/src/Communication/Handlers/TelemetryHandler/TelemetryHandler.hpp @@ -4,16 +4,22 @@ #include "../ICommandHandler.hpp" class Telemetry; +class OTAManager; +class Networking; class TelemetryHandler : public ICommandHandler { public: - explicit TelemetryHandler(Telemetry& telemetry); + // otaManager/networking are needed only for telemetry.get_diagnostics — + // the on-demand mirror of CommunicationRouter's periodic diagnostics_report. + TelemetryHandler(Telemetry& telemetry, OTAManager& otaManager, Networking& networking); std::vector commands() const override; CommandResult execute(const CommandEnvelope& envelope) override; private: Telemetry& _telemetry; + OTAManager& _otaManager; + Networking& _networking; CommandResult handleGetStrikes(const CommandEnvelope& e); CommandResult handleResetStrikes(const CommandEnvelope& e); @@ -23,4 +29,5 @@ private: CommandResult handleGetMetrics(const CommandEnvelope& e); CommandResult handleResetMetrics(const CommandEnvelope& e); CommandResult handleGetBootHistory(const CommandEnvelope& e); + CommandResult handleGetDiagnostics(const CommandEnvelope& e); }; diff --git a/src/HealthMonitor/HealthMonitor.cpp b/src/HealthMonitor/HealthMonitor.cpp index 6c8e29a..ad2a43d 100644 --- a/src/HealthMonitor/HealthMonitor.cpp +++ b/src/HealthMonitor/HealthMonitor.cpp @@ -54,6 +54,7 @@ bool HealthMonitor::begin() { ); if (_monitoringTaskHandle != nullptr) { + Telemetry::registerTaskForStackMonitoring("HealthMonitor", _monitoringTaskHandle); LOG_INFO(TAG, "✅ Health Monitor initialized with automatic monitoring"); return true; } else { diff --git a/src/Networking/Networking.cpp b/src/Networking/Networking.cpp index 6ed68a2..a6d056c 100644 --- a/src/Networking/Networking.cpp +++ b/src/Networking/Networking.cpp @@ -371,9 +371,18 @@ void Networking::onEthernetDisconnected() { void Networking::onWiFiConnected() { LOG_INFO(TAG, "WiFi connected successfully - IP: %s", WiFi.localIP().toString().c_str()); + + // A "reconnect" is any successful connect AFTER the initial boot-time + // connection — _bootSequenceComplete is only true once that first + // connection has already happened, so this correctly excludes it. + if (_bootSequenceComplete) { + _reconnectCount++; + LOG_INFO(TAG, "WiFi reconnected (lifetime count this boot: %lu)", _reconnectCount); + } + setState(NetworkState::CONNECTED_WIFI); setActiveConnection(ConnectionType::WIFI); - + // Reset failure/phase counters on successful connection _wifiConnectionFailures = 0; _triedSavedCredentials = false; @@ -512,10 +521,15 @@ void Networking::networkEventHandler(arduino_event_id_t event, arduino_event_inf _instance->onWiFiConnected(); break; - case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: - LOG_WARNING(TAG, "WiFi Disconnected"); + case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: { + wifi_err_reason_t reason = (wifi_err_reason_t)info.wifi_sta_disconnected.reason; + const char* reasonName = WiFi.disconnectReasonName(reason); + LOG_WARNING(TAG, "WiFi Disconnected (reason: %s)", reasonName); + _instance->_lastDisconnectReason = reasonName; + _instance->_lastDisconnectUptimeMs = millis(); _instance->onWiFiDisconnected(); break; + } case ARDUINO_EVENT_WIFI_STA_CONNECTED: LOG_DEBUG(TAG, "WiFi STA Connected"); diff --git a/src/Networking/Networking.hpp b/src/Networking/Networking.hpp index 6f0eeba..9104465 100644 --- a/src/Networking/Networking.hpp +++ b/src/Networking/Networking.hpp @@ -113,7 +113,21 @@ public: /** @brief Check if Networking is in healthy state */ bool isHealthy() const; - + + // ═══════════════════════════════════════════════════════════════════════════════ + // DIAGNOSTICS — lifetime WiFi reconnect count + last disconnect reason + // ═══════════════════════════════════════════════════════════════════════════════ + // Cumulative, in-memory only (resets on reboot — a fresh boot legitimately + // starts a new "how flaky has this session been" count; lifetime boot + // count already answers "how many times has this device restarted, ever"). + + uint32_t getReconnectCount() const { return _reconnectCount; } + // Human-readable reason for the most recent disconnect, e.g. "AUTH_EXPIRE" + // (via WiFi.disconnectReasonName()). Empty string if no disconnect yet this boot. + String getLastDisconnectReason() const { return _lastDisconnectReason; } + // millis() at the time of the most recent disconnect, or 0 if none yet this boot. + uint32_t getLastDisconnectUptimeMs() const { return _lastDisconnectUptimeMs; } + // Static instance for callbacks static Networking* _instance; @@ -133,6 +147,11 @@ private: bool _ethernetCableConnected; int _wifiConnectionFailures; // Track consecutive WiFi failures bool _triedSavedCredentials; // True once saved-creds phase has been exhausted + + // Diagnostics — see getReconnectCount() etc. above + uint32_t _reconnectCount = 0; + String _lastDisconnectReason = ""; + uint32_t _lastDisconnectUptimeMs = 0; // Callbacks std::function _onNetworkConnected; diff --git a/src/OTAManager/OTAManager.cpp b/src/OTAManager/OTAManager.cpp index b5712a8..994edca 100644 --- a/src/OTAManager/OTAManager.cpp +++ b/src/OTAManager/OTAManager.cpp @@ -9,6 +9,25 @@ #include #include +const char* OTAManager::errorCodeToString(ErrorCode code) { + switch (code) { + case ErrorCode::NONE: return "NONE"; + case ErrorCode::HTTP_ERROR: return "HTTP_ERROR"; + case ErrorCode::VERSION_CHECK_FAILED: return "VERSION_CHECK_FAILED"; + case ErrorCode::DOWNLOAD_FAILED: return "DOWNLOAD_FAILED"; + case ErrorCode::INSUFFICIENT_SPACE: return "INSUFFICIENT_SPACE"; + case ErrorCode::WRITE_FAILED: return "WRITE_FAILED"; + case ErrorCode::VERIFICATION_FAILED: return "VERIFICATION_FAILED"; + case ErrorCode::CHECKSUM_MISMATCH: return "CHECKSUM_MISMATCH"; + case ErrorCode::METADATA_PARSE_FAILED: return "METADATA_PARSE_FAILED"; + case ErrorCode::SIZE_MISMATCH: return "SIZE_MISMATCH"; + case ErrorCode::VERSION_TOO_LOW: return "VERSION_TOO_LOW"; + case ErrorCode::CHANNEL_MISMATCH: return "CHANNEL_MISMATCH"; + case ErrorCode::PLAYER_ACTIVE: return "PLAYER_ACTIVE"; + default: return "UNKNOWN"; + } +} + OTAManager::OTAManager(ConfigManager& configManager) : _configManager(configManager) , _fileManager(nullptr) @@ -225,6 +244,7 @@ void OTAManager::checkForUpdates(const String& channel) { } setStatus(Status::CHECKING_VERSION); + _lastCheckUptimeMs = millis(); LOG_INFO(TAG, "Checking for firmware updates in %s channel for %s...", channel.c_str(), _configManager.getHardwareVariant().c_str()); diff --git a/src/OTAManager/OTAManager.hpp b/src/OTAManager/OTAManager.hpp index 069d449..0bab495 100644 --- a/src/OTAManager/OTAManager.hpp +++ b/src/OTAManager/OTAManager.hpp @@ -103,6 +103,13 @@ public: SemVer getCurrentVersion() const; SemVer getAvailableVersion() const { return _availableVersion; } bool isUpdateAvailable() const { return _updateAvailable; } + // millis() at the start of the most recent update-check attempt (scheduled, + // emergency, or manual), or 0 if no check has run yet this boot. + uint32_t getLastCheckUptimeMs() const { return _lastCheckUptimeMs; } + + // Human-readable name for an ErrorCode, e.g. "DOWNLOAD_FAILED". Used by + // diagnostics_report and telemetry.get_diagnostics. + static const char* errorCodeToString(ErrorCode code); // Callbacks void setProgressCallback(ProgressCallback callback) { _progressCallback = callback; } @@ -129,6 +136,7 @@ private: SemVer _minVersion; size_t _expectedFileSize; // NEW: Expected firmware file size bool _updateAvailable; + uint32_t _lastCheckUptimeMs = 0; // See getLastCheckUptimeMs() String _availableChecksum; String _availableDownloadPath; // Relative path from backend (e.g. /api/firmware/.../firmware.bin) String _updateChannel; diff --git a/src/Telemetry/README.md b/src/Telemetry/README.md index 1e52d74..494d224 100644 --- a/src/Telemetry/README.md +++ b/src/Telemetry/README.md @@ -31,6 +31,12 @@ Telemetry tracks per-bell strike counts and thermal load to protect actuators fr | `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. | +| `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. | --- @@ -177,4 +183,24 @@ Example requests: { "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}/status/info` every `DIAGNOSTICS_REPORT_INTERVAL_MS` (5 minutes) once `_telemetry` is set. 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. diff --git a/src/Telemetry/Telemetry.cpp b/src/Telemetry/Telemetry.cpp index f2868ba..5a80d99 100644 --- a/src/Telemetry/Telemetry.cpp +++ b/src/Telemetry/Telemetry.cpp @@ -28,6 +28,7 @@ void Telemetry::begin() { // (512B format buffer + MQTT publish String + AsyncMqttClient::publish()) on this // task's own stack. 4096 overflowed the canary in production — see stack-audit notes. xTaskCreatePinnedToCore(telemetryTask, "TelemetryTask", 8192, this, 2, &telemetryTaskHandle, 1); + registerTaskForStackMonitoring("TelemetryTask", telemetryTaskHandle); LOG_INFO(TAG, "Telemetry initialized"); } @@ -206,6 +207,64 @@ void Telemetry::logVibration(float vibration) { LOG_INFO(TAG, "Vibration: %.2f", vibration); } +// ════════════════════════════════════════════════════════════════════════════ +// DIAGNOSTICS REPORT — local temperature sampling + stack high-water registry +// ════════════════════════════════════════════════════════════════════════════ + +void Telemetry::sampleDiagnosticsIfDue() { + uint32_t now = millis(); + if (now - lastDiagnosticsSampleMs < DIAGNOSTICS_SAMPLE_INTERVAL_MS) return; + lastDiagnosticsSampleMs = now; + + // ESP32's built-in die temperature sensor (temperatureRead(), Arduino-ESP32 + // core). Coarse and reads die temp rather than ambient — useful as a "is + // this thing running hot" trend signal, not a calibrated instrument. + float tempC = temperatureRead(); + temperatureStats.addSample(tempC); +} + +// Fixed-size registry — matches this codebase's avoid-dynamic-allocation +// style elsewhere (e.g. strikeCounters[16]). 8 slots comfortably covers every +// task with a stored TaskHandle_t today (TelemetryTask, HealthMonitor, +// TimeKeeper, OutputManager, FirmwareValidator, Logging, BellEngine, +// InputManager) with room to spare; short-lived fire-and-forget tasks like +// mqttRecon/netRecon don't keep a handle at all and can't be monitored this way. +namespace { + struct StackMonitorEntry { + const char* name = nullptr; + TaskHandle_t handle = nullptr; + }; + constexpr size_t MAX_STACK_MONITOR_ENTRIES = 8; + StackMonitorEntry stackMonitorRegistry[MAX_STACK_MONITOR_ENTRIES]; + size_t stackMonitorCount = 0; +} + +void Telemetry::registerTaskForStackMonitoring(const char* name, TaskHandle_t handle) { + if (handle == nullptr) return; + if (stackMonitorCount >= MAX_STACK_MONITOR_ENTRIES) { + LOG_WARNING(TAG, "Stack monitor registry full — '%s' not registered", name); + return; + } + stackMonitorRegistry[stackMonitorCount++] = { name, handle }; +} + +void Telemetry::writeStackHighWaterMarks(JsonObject& out) { + for (size_t i = 0; i < stackMonitorCount; i++) { + const auto& entry = stackMonitorRegistry[i]; + UBaseType_t wordsFree = uxTaskGetStackHighWaterMark(entry.handle); + out[entry.name] = (uint32_t)(wordsFree * sizeof(StackType_t)); + } +} + +void Telemetry::writeTemperatureStats(JsonDocument& doc) const { + if (temperatureStats.count == 0) return; + JsonObject tempObj = doc["cpu_temp"].to(); + tempObj["avg"] = temperatureStats.average(); + tempObj["min"] = temperatureStats.min; + tempObj["max"] = temperatureStats.max; + tempObj["samples"] = temperatureStats.count; +} + void Telemetry::checkBellLoads() { if (!guardEnabled) { // Guard disabled — still decay loads for accurate reporting, but never force-stop @@ -292,6 +351,9 @@ void Telemetry::telemetryTask(void* parameter) { telemetry->flushRuntimeToSD(); telemetry->lastRuntimeFlushMs = now; } + + // Diagnostics: local temperature sampling (own throttle, ~15s) + telemetry->sampleDiagnosticsIfDue(); } vTaskDelay(pdMS_TO_TICKS(1000)); diff --git a/src/Telemetry/Telemetry.hpp b/src/Telemetry/Telemetry.hpp index b294dad..d0c94e4 100644 --- a/src/Telemetry/Telemetry.hpp +++ b/src/Telemetry/Telemetry.hpp @@ -56,6 +56,7 @@ #include #include #include +#include #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "../Logging/Logging.hpp" @@ -83,6 +84,34 @@ static constexpr uint16_t BOOT_LOG_MAX_ENTRIES = 200; // Runtime flush interval in milliseconds (10 minutes) static constexpr uint32_t RUNTIME_FLUSH_INTERVAL_MS = 10 * 60 * 1000UL; +// Diagnostics report — local sampling + batch-send intervals (see +// docs/features/feature-catalog.md for why these differ). Temperature is +// sampled locally every DIAGNOSTICS_SAMPLE_INTERVAL_MS and reduced to +// min/max/avg; the batch is sent every DIAGNOSTICS_REPORT_INTERVAL_MS by +// CommunicationRouter::reportDiagnosticsOnce()-equivalent periodic call. +static constexpr uint32_t DIAGNOSTICS_SAMPLE_INTERVAL_MS = 15 * 1000UL; +static constexpr uint32_t DIAGNOSTICS_REPORT_INTERVAL_MS = 5 * 60 * 1000UL; + +// Running min/max/avg accumulator for a value sampled many times between +// reports, then reset. Avoids storing every raw sample — O(1) per sample. +struct RunningStats { + float sum = 0; + float min = 0; + float max = 0; + uint16_t count = 0; + + void reset() { sum = 0; min = 0; max = 0; count = 0; } + + void addSample(float value) { + if (count == 0) { min = value; max = value; } + else { if (value < min) min = value; if (value > max) max = value; } + sum += value; + count++; + } + + float average() const { return count > 0 ? (sum / count) : 0; } +}; + class Telemetry { private: // Bell tracking @@ -125,6 +154,14 @@ private: // Most recent crash's coredump summary, if any — read once at begin(). CrashReport crashReport; + // Diagnostics — CPU temperature sampled locally every 15s, reduced to + // min/max/avg between 5-minute batch reports. See RunningStats above for + // why only temperature needs local sampling (stack high-water and the + // WiFi reconnect count are both monotonic/cumulative — a single read at + // report time is exactly as informative as reading them continuously). + RunningStats temperatureStats; + uint32_t lastDiagnosticsSampleMs = 0; + void initBootTracking(); // opens NVS namespace, increments+persists lifetimeBootCount void captureCrashReport(); // reads+erases the coredump summary, if present @@ -201,6 +238,38 @@ public: void logTemperature(float temperature); void logVibration(float vibration); + // ─── Diagnostics report (temperature, stack high-water, etc.) ────────── + // See docs/features/feature-catalog.md and Telemetry/README.md "Diagnostics + // reporting" section for the full design rationale. + + // Called from telemetryTask's existing 1s loop. Internally no-ops unless + // DIAGNOSTICS_SAMPLE_INTERVAL_MS has elapsed since the last sample. + void sampleDiagnosticsIfDue(); + + // Current accumulated min/max/avg since the last resetDiagnosticsStats(). + const RunningStats& getTemperatureStats() const { return temperatureStats; } + void resetDiagnosticsStats() { temperatureStats.reset(); } + + // Registers a task handle (with a short display name, e.g. "TelemetryTask") + // to be included in diagnostics_report's stack_high_water object. Call once + // per task, any time after the task is created — typically from that + // subsystem's begin(). A handle of nullptr is silently ignored (lets + // callers register unconditionally without an extra null check). + static void registerTaskForStackMonitoring(const char* name, TaskHandle_t handle); + + // Writes {"TaskName": bytesFree, ...} for every registered task into the + // given JsonObject. Bytes, not words — uxTaskGetStackHighWaterMark() + // returns words remaining; multiplied by sizeof(StackType_t) here so the + // console doesn't need to know the platform's word size. + static void writeStackHighWaterMarks(JsonObject& out); + + // Writes this instance's cpu_temp {avg,min,max,samples} object into the + // given JsonDocument, IF resetStats is false (peek without consuming the + // accumulator — used by the on-demand telemetry.get_diagnostics command, + // which shouldn't reset what the next scheduled 5-minute report will see). + // Omits the field entirely if no samples have been taken yet. + void writeTemperatureStats(JsonDocument& doc) const; + // Force stop callback (to be set by main application) void setForceStopCallback(void (*callback)());