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>
217 lines
8.9 KiB
C++
217 lines
8.9 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 "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;
|
|
|
|
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;
|
|
|
|
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);
|
|
|
|
// 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; }
|
|
|
|
// 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);
|
|
|
|
// 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
|