feat(Telemetry,Networking,OTAManager,CommunicationRouter): diagnostics report — CPU temp, WiFi reconnects, OTA state, stack high-water mark

Console requested four more Health-tab metrics beyond F-054's free_heap/ping
work. None needed 30s heartbeat freshness, so this adds a separate low-frequency
report instead of growing the heartbeat further: published every 5 min to
status/info (diagnostics_report) and queryable on-demand via a new
telemetry.get_diagnostics command.

Only CPU temperature needs local sampling (15s, via a min/max/avg RunningStats
accumulator on Telemetry) — a thermal spike could occur and subside entirely
within a 5-minute gap. The other three fields are monotonic/self-tracking
(WiFi reconnect counter, FreeRTOS's own stack high-water mark, rarely-changing
OTA state) so a single read at report time loses no information.

Verified: pio run on all four board variants.
This commit is contained in:
2026-07-17 13:09:16 +03:00
parent 9cd6b142ef
commit 959cb77d81
14 changed files with 388 additions and 9 deletions
@@ -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<TelemetryHandler>(*_telemetry));
_bus.registerHandler(std::make_unique<TelemetryHandler>(*_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<JsonObject>();
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<JsonObject>();
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<JsonObject>();
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;
@@ -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;
@@ -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()`.
@@ -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<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_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<JsonObject>();
wifiObj["lifetime_count"] = _networking.getReconnectCount();
wifiObj["last_reason"] = _networking.getLastDisconnectReason();
wifiObj["last_at_uptime_ms"] = _networking.getLastDisconnectUptimeMs();
JsonObject otaObj = doc["ota"].to<JsonObject>();
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<JsonObject>();
Telemetry::writeStackHighWaterMarks(stackObj);
return CommandResult::ok("telemetry.get_diagnostics", doc);
}
@@ -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<String> 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);
};