Files
project-vesper/src/Telemetry/Telemetry.hpp
T
bonaminandClaude Sonnet 4.6 e90771a539 feat(comms): bidirectional device control — bells master switch, guard toggle, runtime tracking, system aggregate commands
Adds full bidirectional remote control across all major subsystems,
establishing the device as the single source of truth for all settings.

New firmware features (F-029 to F-037):
- bells.enable / bells.disable: master ON/OFF for all playback and clock
  alerts (relay.test_output intentionally unaffected)
- telemetry.set_guard_enabled: enable/disable thermal protection at runtime
  without touching thresholds
- telemetry.set_max_loads: set bellMaxLoad per-bell or globally via command
- Device runtime tracking: lifetime seconds flushed to SD every 10 min,
  boot log (up to 200 entries, rotating) written after first NTP sync
- Total playback counter persisted to SD, increments on every play()
- telemetry.get_metrics / telemetry.reset_metrics: new aggregate read + reset
- system.get_config (replaces system.get_settings, old name still accepted),
  system.get_all (everything in one call), system.get_telemetry
- log.get_config, mqtt.get_config, bells.get_config: new getters for
  previously write-only subsystems
- network.status now includes ssid, mac, hostname
- BellsHandler: new handler registered on CommandBus
- LegacyAdapter updated with all new command mappings

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-10 18:46:18 +03:00

162 lines
6.1 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 "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "../Logging/Logging.hpp"
#include "../FileManager/FileManager.hpp"
// 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;
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
void logBootEvent(uint32_t bootTimestamp);
// 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