Files
project-vesper/src/Telemetry/Telemetry.hpp
T
bonamin f41332a771 feat(Telemetry,FileManager,LoggingHandler): QA-to-shipping stats reset — telemetry.reset_boot_data + logs.clear
Console wants a "reset device stats before shipping" button for staff to
clear QA-bench data (test reboots, debug log spam) without wiping actual
device configuration. telemetry.reset_strikes and telemetry.reset_metrics
already covered bell strikes and runtime/playback counters — this adds the
two gaps: lifetime boot count + SD boot history, and SD debug logs.

Deliberately does not touch FirmwareValidator's NVS namespace (rollback
safety state, not history) or device identity NVS (serial/hw_family).

Verified: pio run on all four board variants.
2026-07-17 14:14:55 +03:00

302 lines
13 KiB
C++

/*
* ═══════════════════════════════════════════════════════════════════════════════════
* TELEMETRY.HPP - System Monitoring and Analytics Engine
* ═══════════════════════════════════════════════════════════════════════════════════
*
* 📊 THE SYSTEM WATCHDOG OF VESPER 📊
*
* This class provides comprehensive system monitoring, performance tracking,
* and safety management. It continuously monitors bell usage, load conditions,
* and system health to ensure safe and optimal operation.
*
* 🏗️ MONITORING ARCHITECTURE:
* • Real-time bell load tracking and thermal management
* • Strike counting for warranty and maintenance tracking
* • Performance metrics collection and analysis
* • System health monitoring and alerting
* • Thread-safe operation with spinlock protection
*
* 🔔 BELL MONITORING:
* • Individual bell strike counting (warranty tracking)
* • Load accumulation and thermal modeling
* • Overload detection and protection
* • Configurable thresholds per bell
* • Automatic cooling period management
*
* 🔥 THERMAL PROTECTION:
* • Real-time load calculation based on activation duration
* • Thermal decay modeling for cooling
* • Overload prevention with automatic cooling
* • Emergency stop capability for safety
* • System-wide thermal state tracking
*
* 📊 ANALYTICS & REPORTING:
* • Performance metrics collection
* • Usage pattern analysis
* • Health status reporting
* • Predictive maintenance indicators
* • Historical data tracking
*
* ⚙️ SAFETY FEATURES:
* • Automatic system protection from overload
* • Force stop callback for emergency situations
* • Comprehensive bounds checking
* • Fail-safe operation modes
* • Graceful degradation under stress
*
* 📋 VERSION: 2.0 (Enhanced monitoring and safety)
* 📅 DATE: 2025
* 👨‍💻 AUTHOR: Advanced Bell Systems
* ═══════════════════════════════════════════════════════════════════════════════════
*/
#ifndef TELEMETRY_HPP
#define TELEMETRY_HPP
#include <Arduino.h>
#include <esp_system.h>
#include <nvs.h>
#include <ArduinoJson.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "../Logging/Logging.hpp"
#include "../FileManager/FileManager.hpp"
// Coredump summary retrieval (esp_core_dump_get_summary) — populated by the ESP-IDF
// panic handler automatically on every crash (already enabled in this project's SDK
// build; no custom panic hook needed). See CrashReport below.
#include <esp_core_dump.h>
// Most recent crash's coredump summary, captured once at begin() and erased from
// flash immediately after reading so it's reported exactly once. Empty/zeroed
// fields when no coredump was present (e.g. expected reset, or reset predates
// coredump support).
struct CrashReport {
bool available = false;
char taskName[16] = {0}; // esp_core_dump_summary_t::exc_task
uint32_t pc = 0; // Program counter at exception
uint32_t excCause = 0; // Xtensa exception cause code
uint32_t excVaddr = 0; // Faulting virtual address
};
// Maximum number of boot log entries retained on SD (rotating)
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
uint32_t strikeCounters[16] = {0}; // Total strikes per bell (warranty tracking)
uint16_t bellLoad[16] = {0}; // Current heat load per bell
uint16_t bellMaxLoad[16] = {60}; // Max load threshold per bell
bool coolingActive = false; // System-wide cooling flag
bool guardEnabled = true; // Bell load guard enable/disable
// Runtime tracking
uint32_t lifetimeRuntimeSeconds = 0; // Cumulative powered-on seconds (loaded from SD)
uint32_t sessionStartMs = 0; // millis() at boot — used to compute current session
uint32_t lastRuntimeFlushMs = 0; // Last time runtime was flushed to SD
uint32_t totalPlaybackCount = 0; // Total melodies played (lifetime, persisted)
// Task handle
TaskHandle_t telemetryTaskHandle = NULL;
// External references (to be set via setters)
bool* playerIsPlayingPtr = nullptr;
FileManager* fileManager = nullptr;
// Spinlock for critical sections
portMUX_TYPE telemetrySpinlock = portMUX_INITIALIZER_UNLOCKED;
// Pause flag for OTA freeze mode
volatile bool isPaused = false;
// Reset reason, captured once at begin()
esp_reset_reason_t resetReason = ESP_RST_UNKNOWN;
// Lifetime boot counter — separate from FirmwareValidator's NVS boot_count
// (which tracks boots-since-this-firmware-was-flashed for rollback safety).
// This one is the device's whole-life reboot count, the single source of
// truth for "how many times has this device rebooted, ever." See
// docs/features/feature-catalog.md for why two counters exist.
nvs_handle_t _bootNvsHandle = 0;
uint32_t lifetimeBootCount = 0;
// 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
public:
// Initialization
void begin();
// Set external references
void setPlayerReference(bool* isPlayingPtr);
void setFileManager(FileManager* fm);
// Bell strike handling (call this on every hammer strike)
void recordBellStrike(uint8_t bellIndex);
// Strike counter management (warranty tracking)
uint32_t getStrikeCount(uint8_t bellIndex);
void resetStrikeCounters(); // User-requested reset (per bell or all)
// Persistence methods
void saveStrikeCounters();
void loadStrikeCounters();
// Bell load management
uint16_t getBellLoad(uint8_t bellIndex);
uint16_t getBellMaxLoad(uint8_t bellIndex);
void setBellMaxLoad(uint8_t bellIndex, uint16_t maxLoad);
bool isOverloaded(uint8_t bellIndex);
bool isCoolingActive(); // Check if system needs cooling
// Bell guard enable/disable
bool isGuardEnabled() const { return guardEnabled; }
void setGuardEnabled(bool enabled) { guardEnabled = enabled; }
// Playback counter
void recordPlayback();
uint32_t getTotalPlaybackCount() const { return totalPlaybackCount; }
void resetMetrics();
// Runtime metrics
uint32_t getLifetimeRuntimeSeconds() const { return lifetimeRuntimeSeconds; }
uint32_t getCurrentSessionSeconds() const { return (millis() - sessionStartMs) / 1000; }
void flushRuntimeToSD();
// Boot log — rotating SD-side history of recent boots (timestamp + reason).
// NOT the authoritative boot counter (SD-only, silently skipped without NTP
// 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."
uint32_t getLifetimeBootCount() const { return lifetimeBootCount; }
// Resets the lifetime boot counter (NVS) to 0 and deletes the SD boot
// history log — used before shipping a device to a customer, to clear
// reboot counts accumulated during QA/bench testing. Does NOT touch
// FirmwareValidator's separate "fw_validator" NVS namespace (rollback
// safety state, not history). Returns false if the NVS write failed;
// the SD-side deletion is always best-effort and doesn't affect the
// return value.
bool resetBootData();
// Most recent crash's coredump summary (task name, PC, exception cause/vaddr),
// if one was captured. available == false when the last reset wasn't a crash,
// or no coredump was found for one that was.
const CrashReport& getCrashReport() const { return crashReport; }
// Reset reason (captured once at begin(), before anything else can crash again)
esp_reset_reason_t getResetReason() const { return resetReason; }
// True if the reset reason indicates a fault (panic, watchdog, brownout) rather
// than an expected reset (power-on, software reset/OTA, deep sleep wake).
bool isFaultReset() const;
String getResetReasonString() const;
// Data collection (future expansion)
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)());
// Pause/Resume for OTA freeze mode (stops SD writes during firmware update)
void pause() { isPaused = true; }
void resume() { isPaused = false; }
bool isHealthy() const;
// Static task function
static void telemetryTask(void* parameter);
private:
void (*forceStopCallback)() = nullptr;
void checkBellLoads();
void loadMetrics();
void saveMetrics();
};
#endif