refactor: Fixed the file hierarchy and switched to platform.io
This commit is contained in:
@@ -0,0 +1,446 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* BELLENGINE.CPP - High-Precision Bell Timing Engine Implementation
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* This file contains the implementation of the BellEngine class - the core
|
||||
* precision timing system that controls bell activation with microsecond accuracy.
|
||||
*
|
||||
* 🔥 CRITICAL PERFORMANCE SECTION 🔥
|
||||
*
|
||||
* The code in this file is performance-critical and runs on a dedicated
|
||||
* FreeRTOS task with maximum priority on Core 1. Any modifications should
|
||||
* be thoroughly tested for timing impact.
|
||||
*
|
||||
* 📋 VERSION: 2.0 (Rewritten for modular architecture)
|
||||
* 📅 DATE: 2025
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
// DEPENDENCY INCLUDES - Required system components
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
#include "BellEngine.hpp" // Header file with class definition
|
||||
|
||||
#define TAG "BellEngine"
|
||||
#include "../Player/Player.hpp" // Melody playback controller
|
||||
#include "../ConfigManager/ConfigManager.hpp" // Configuration and settings
|
||||
#include "../Telemetry/Telemetry.hpp" // System monitoring and analytics
|
||||
#include "../OutputManager/OutputManager.hpp" // Hardware abstraction layer
|
||||
#include "../Communication/CommunicationRouter/CommunicationRouter.hpp" // Communication system for notifications
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
// CONSTRUCTOR & DESTRUCTOR IMPLEMENTATION
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Constructor - Initialize BellEngine with dependency injection
|
||||
*
|
||||
* Sets up all dependency references and initializes the OutputManager integration.
|
||||
* Note: The OutputManager now handles all relay duration tracking, providing
|
||||
* clean separation of concerns and hardware abstraction.
|
||||
*/
|
||||
BellEngine::BellEngine(Player& player, ConfigManager& configManager, Telemetry& telemetry, OutputManager& outputManager)
|
||||
: _player(player) // Reference to melody playback controller
|
||||
, _configManager(configManager) // Reference to configuration manager
|
||||
, _telemetry(telemetry) // Reference to system monitoring
|
||||
, _outputManager(outputManager) // 🔥 Reference to hardware abstraction layer
|
||||
, _communicationManager(nullptr) { // Initialize communication manager to nullptr
|
||||
|
||||
// 🏗️ ARCHITECTURAL NOTE:
|
||||
// OutputManager now handles all relay duration tracking automatically!
|
||||
// This provides clean separation of concerns and hardware abstraction.
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Destructor - Ensures safe cleanup
|
||||
*
|
||||
* Automatically calls emergencyShutdown() to ensure all relays are turned off
|
||||
* and the system is in a safe state before object destruction.
|
||||
*/
|
||||
BellEngine::~BellEngine() {
|
||||
emergencyShutdown(); // 🚑 Ensure safe shutdown on destruction
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
// CORE INITIALIZATION IMPLEMENTATION
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Initialize the BellEngine system
|
||||
*
|
||||
* Creates the high-priority timing task on Core 1 with maximum priority.
|
||||
* This task provides the microsecond-precision timing that makes the
|
||||
* bell system so accurate and reliable.
|
||||
*
|
||||
*/
|
||||
void BellEngine::begin() {
|
||||
LOG_DEBUG(TAG, "Initializing BellEngine...");
|
||||
|
||||
// Create engine task with HIGHEST priority on dedicated Core 1
|
||||
// This ensures maximum performance and timing precision
|
||||
xTaskCreatePinnedToCore(
|
||||
engineTask, // 📋 Task function pointer
|
||||
"BellEngine", // 🏷️ Task name for debugging
|
||||
12288, // 💾 Stack size (12KB - increased for safety)
|
||||
this, // 🔗 Parameter (this instance)
|
||||
6, // ⚡ HIGHEST Priority (0-7, 7 is highest)
|
||||
&_engineTaskHandle, // 💼 Task handle storage
|
||||
1 // 💻 Pin to Core 1 (dedicated)
|
||||
);
|
||||
|
||||
LOG_INFO(TAG, "BellEngine initialized !");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Set Communication manager reference for bell notifications
|
||||
*/
|
||||
void BellEngine::setCommunicationManager(CommunicationRouter* commManager) {
|
||||
_communicationManager = commManager;
|
||||
LOG_DEBUG(TAG, "BellEngine: Communication manager %s",
|
||||
commManager ? "connected" : "disconnected");
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
// ENGINE CONTROL IMPLEMENTATION (Thread-safe)
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Start the precision timing engine
|
||||
*
|
||||
* Activates the high-precision timing loop. Requires melody data to be
|
||||
* loaded via setMelodyData() before calling. Uses atomic operations
|
||||
* for thread-safe state management.
|
||||
*
|
||||
* @note Will log error and return if no melody data is available
|
||||
*/
|
||||
void BellEngine::start() {
|
||||
// Validate that melody data is ready before starting
|
||||
if (!_melodyDataReady.load()) {
|
||||
LOG_ERROR(TAG, "Cannot start BellEngine: No melody data loaded");
|
||||
return; // ⛔ Early exit if no melody data
|
||||
}
|
||||
|
||||
LOG_INFO(TAG, "🚀 BellEngine Ignition - Starting precision playback");
|
||||
_emergencyStop.store(false); // ✅ Clear any emergency stop state
|
||||
_engineRunning.store(true); // ✅ Activate the engine atomically
|
||||
}
|
||||
|
||||
void BellEngine::stop() {
|
||||
LOG_INFO(TAG, "BellEngine - Stopping Gracefully");
|
||||
_engineRunning.store(false);
|
||||
}
|
||||
|
||||
void BellEngine::emergencyStop() {
|
||||
LOG_INFO(TAG, "BellEngine - 🛑 Forcing Stop Immediately");
|
||||
_emergencyStop.store(true);
|
||||
_engineRunning.store(false);
|
||||
emergencyShutdown();
|
||||
}
|
||||
|
||||
void BellEngine::setMelodyData(const std::vector<uint16_t>& melodySteps) {
|
||||
portENTER_CRITICAL(&_melodyMutex);
|
||||
_melodySteps = melodySteps;
|
||||
_melodyDataReady.store(true);
|
||||
portEXIT_CRITICAL(&_melodyMutex);
|
||||
LOG_DEBUG(TAG, "BellEngine - Loaded melody: %d steps", melodySteps.size());
|
||||
}
|
||||
|
||||
void BellEngine::clearMelodyData() {
|
||||
portENTER_CRITICAL(&_melodyMutex);
|
||||
_melodySteps.clear();
|
||||
_melodyDataReady.store(false);
|
||||
portEXIT_CRITICAL(&_melodyMutex);
|
||||
LOG_DEBUG(TAG, "BellEngine - Melody data cleared");
|
||||
}
|
||||
|
||||
// ================== CRITICAL TIMING SECTION ==================
|
||||
// This is where the magic happens! Maximum precision required !
|
||||
|
||||
void BellEngine::engineTask(void* parameter) {
|
||||
BellEngine* engine = static_cast<BellEngine*>(parameter);
|
||||
LOG_DEBUG(TAG, "BellEngine - 🔥 Engine task started on Core %d with MAXIMUM priority", xPortGetCoreID());
|
||||
|
||||
while (true) {
|
||||
if (engine->_engineRunning.load() && !engine->_emergencyStop.load()) {
|
||||
engine->engineLoop();
|
||||
} else {
|
||||
// Low-power wait when not running
|
||||
vTaskDelay(pdMS_TO_TICKS(10));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void BellEngine::engineLoop() {
|
||||
uint64_t loopStartTime = getMicros();
|
||||
|
||||
// Safety check. Stop if Emergency Stop is Active
|
||||
if (_emergencyStop.load()) {
|
||||
emergencyShutdown();
|
||||
return;
|
||||
}
|
||||
|
||||
playbackLoop();
|
||||
|
||||
// Check telemetry for overloads and send notifications if needed
|
||||
checkAndNotifyOverloads();
|
||||
|
||||
// Pause handling AFTER complete loop - never interrupt mid-melody!
|
||||
while (_player.isPaused && _player.isPlaying && !_player.hardStop) {
|
||||
LOG_VERBOSE(TAG, "BellEngine - ⏸️ Pausing between melody loops");
|
||||
vTaskDelay(pdMS_TO_TICKS(10)); // Wait during pause
|
||||
}
|
||||
|
||||
uint64_t loopEndTime = getMicros();
|
||||
uint32_t loopTime = (uint32_t)(loopEndTime - loopStartTime);
|
||||
}
|
||||
|
||||
void BellEngine::playbackLoop() {
|
||||
// Check if player wants us to run
|
||||
if (!_player.isPlaying || _player.hardStop) {
|
||||
_engineRunning.store(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get melody data safely
|
||||
portENTER_CRITICAL(&_melodyMutex);
|
||||
auto melodySteps = _melodySteps; // Fast copy
|
||||
portEXIT_CRITICAL(&_melodyMutex);
|
||||
|
||||
if (melodySteps.empty()) {
|
||||
LOG_ERROR(TAG, "BellEngine - ❌ Empty melody in playback loop!");
|
||||
return;
|
||||
}
|
||||
|
||||
LOG_DEBUG(TAG, "BellEngine - 🎵 Starting melody loop (%d steps)", melodySteps.size());
|
||||
|
||||
// CRITICAL TIMING LOOP - Complete the entire melody without interruption
|
||||
for (uint16_t note : melodySteps) {
|
||||
// Emergency exit check (only emergency stops can interrupt mid-loop)
|
||||
if (_emergencyStop.load() || _player.hardStop) {
|
||||
LOG_DEBUG(TAG, "BellEngine - Emergency exit from playback loop");
|
||||
return;
|
||||
}
|
||||
|
||||
// Activate note with MAXIMUM PRECISION
|
||||
activateNote(note);
|
||||
|
||||
// Precise timing delay - validate speed to prevent division by zero
|
||||
// I THINK this should be moved outside the Bell Engine
|
||||
if (_player.speed == 0) {
|
||||
LOG_ERROR(TAG, "BellEngine - ❌ Invalid Speed (0) detected, stopping playback");
|
||||
_player.hardStop = true;
|
||||
_engineRunning.store(false);
|
||||
return;
|
||||
}
|
||||
|
||||
uint32_t tempoMicros = _player.speed * 1000; // Convert ms to microseconds
|
||||
preciseDelay(tempoMicros);
|
||||
}
|
||||
|
||||
// Mark segment completion and notify Player
|
||||
_player.segmentCmpltTime = millis();
|
||||
_player.onMelodyLoopCompleted(); // 🔥 Notify Player that melody actually finished!
|
||||
if ((_player.continuous_loop && _player.segment_duration == 0) || _player.total_duration == 0) {
|
||||
vTaskDelay(pdMS_TO_TICKS(500)); //Give Player time to pause/stop
|
||||
LOG_VERBOSE(TAG, "BellEngine - Loop completed in SINGLE Mode - waiting for Player to handle pause/stop");
|
||||
}
|
||||
LOG_DEBUG(TAG, "BellEngine - 🎵 Melody loop completed with PRECISION");
|
||||
|
||||
}
|
||||
|
||||
void BellEngine::activateNote(uint16_t note) {
|
||||
// Track which bells we've already added to prevent duplicates
|
||||
bool bellFired[16] = {false};
|
||||
std::vector<std::pair<uint8_t, uint16_t>> bellDurations; // For batch firing
|
||||
std::vector<uint8_t> firedBellIndices; // Track which bells were fired for notification
|
||||
|
||||
// Iterate through each bit position (note index)
|
||||
for (uint8_t noteIndex = 0; noteIndex < 16; noteIndex++) {
|
||||
if (note & (1 << noteIndex)) {
|
||||
// Get bell mapping (noteAssignments stored as 1-indexed)
|
||||
uint8_t bellConfig = _player.noteAssignments[noteIndex];
|
||||
|
||||
// Skip if no bell assigned
|
||||
if (bellConfig == 0) continue;
|
||||
|
||||
// Convert 1-indexed config to 0-indexed bellIndex
|
||||
uint8_t bellIndex = bellConfig - 1;
|
||||
|
||||
// Additional safety check to prevent underflow crashes
|
||||
if (bellIndex >= 255) {
|
||||
LOG_ERROR(TAG, "BellEngine - 🚨 UNDERFLOW ERROR: bellIndex underflow for noteIndex %d", noteIndex);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Bounds check (CRITICAL SAFETY)
|
||||
if (bellIndex >= 16) {
|
||||
LOG_ERROR(TAG, "BellEngine - 🚨 BOUNDS ERROR: bellIndex %d >= 16", bellIndex);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check for duplicate bell firing in this note
|
||||
if (bellFired[bellIndex]) {
|
||||
LOG_DEBUG(TAG, "BellEngine - ⚠️ DUPLICATE BELL: Skipping duplicate firing of bell %d for note %d", bellIndex, noteIndex);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check if bell is configured (OutputManager will validate this)
|
||||
uint8_t physicalOutput = _outputManager.getPhysicalOutput(bellIndex);
|
||||
if (physicalOutput == 255) {
|
||||
LOG_DEBUG(TAG, "BellEngine - ⚠️ UNCONFIGURED: Bell %d not configured, skipping", bellIndex);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Mark this bell as fired
|
||||
bellFired[bellIndex] = true;
|
||||
|
||||
// Get duration from config
|
||||
uint16_t durationMs = _configManager.getBellDuration(bellIndex);
|
||||
|
||||
// Add to batch firing list
|
||||
bellDurations.push_back({physicalOutput, durationMs});
|
||||
|
||||
// Add to notification list (convert to 1-indexed for display)
|
||||
firedBellIndices.push_back(bellIndex + 1);
|
||||
|
||||
// Record telemetry
|
||||
_telemetry.recordBellStrike(bellIndex);
|
||||
|
||||
LOG_VERBOSE(TAG, "BellEngine - 🔨 STRIKE! Note:%d → Bell:%d for %dms", noteIndex, bellIndex, durationMs);
|
||||
}
|
||||
}
|
||||
|
||||
// 🚀 FIRE ALL BELLS SIMULTANEOUSLY!
|
||||
if (!bellDurations.empty()) {
|
||||
_outputManager.fireOutputsBatchForDuration(bellDurations);
|
||||
LOG_VERBOSE(TAG, "BellEngine - 🔥 Batch Fired %d bells Simultaneously !", bellDurations.size());
|
||||
|
||||
// 🔔 NOTIFY WEBSOCKET CLIENTS OF BELL DINGS!
|
||||
// * deactivated currently, since unstable and causes performance issues *
|
||||
// notifyBellsFired(firedBellIndices);
|
||||
}
|
||||
}
|
||||
|
||||
void BellEngine::preciseDelay(uint32_t microseconds) {
|
||||
uint64_t start = getMicros();
|
||||
uint64_t target = start + microseconds;
|
||||
|
||||
// For delays > 1ms, use task delay for most of it
|
||||
if (microseconds > 1000) {
|
||||
uint32_t taskDelayMs = (microseconds - 500) / 1000; // Leave 500µs for busy wait
|
||||
vTaskDelay(pdMS_TO_TICKS(taskDelayMs));
|
||||
}
|
||||
|
||||
// Busy wait for final precision
|
||||
while (getMicros() < target) {
|
||||
// Tight loop for maximum precision
|
||||
asm volatile("nop");
|
||||
}
|
||||
}
|
||||
|
||||
void BellEngine::emergencyShutdown() {
|
||||
LOG_INFO(TAG, "BellEngine - 🚨 Emergency Shutdown - Notifying OutputManager");
|
||||
_outputManager.emergencyShutdown();
|
||||
}
|
||||
|
||||
void BellEngine::notifyBellsFired(const std::vector<uint8_t>& bellIndices) {
|
||||
if (!_communicationManager || bellIndices.empty()) {
|
||||
|
||||
return; // No communication manager or no bells fired
|
||||
}
|
||||
|
||||
try {
|
||||
// Create notification message
|
||||
StaticJsonDocument<256> dingMsg;
|
||||
dingMsg["status"] = "INFO";
|
||||
dingMsg["type"] = "ding";
|
||||
|
||||
// Create payload array with fired bell numbers (1-indexed for display)
|
||||
JsonArray bellsArray = dingMsg["payload"].to<JsonArray>();
|
||||
for (uint8_t bellIndex : bellIndices) {
|
||||
bellsArray.add(bellIndex); // Already converted to 1-indexed in activateNote
|
||||
}
|
||||
|
||||
// Send notification to WebSocket clients only (not MQTT)
|
||||
_communicationManager->broadcastToAllWebSocketClients(dingMsg);
|
||||
|
||||
LOG_DEBUG(TAG, "BellEngine - 🔔 DING notification sent for %d bells", bellIndices.size());
|
||||
|
||||
} catch (...) {
|
||||
LOG_WARNING(TAG, "BellEngine - ❌ Failed to send ding notification");
|
||||
}
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// HEALTH CHECK IMPLEMENTATION
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
bool BellEngine::isHealthy() const {
|
||||
// Check if engine task is created and running
|
||||
if (_engineTaskHandle == NULL) {
|
||||
LOG_DEBUG(TAG, "BellEngine: Unhealthy - Task not created");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if task is still alive
|
||||
eTaskState taskState = eTaskGetState(_engineTaskHandle);
|
||||
if (taskState == eDeleted || taskState == eInvalid) {
|
||||
LOG_DEBUG(TAG, "BellEngine: Unhealthy - Task deleted or invalid");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if OutputManager is properly connected and healthy
|
||||
if (!_outputManager.isInitialized()) {
|
||||
LOG_DEBUG(TAG, "BellEngine: Unhealthy - OutputManager not initialized");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void BellEngine::checkAndNotifyOverloads() {
|
||||
if (!_communicationManager) {
|
||||
return; // No communication manager available
|
||||
}
|
||||
|
||||
// Collect overloaded bells from telemetry
|
||||
std::vector<uint8_t> criticalBells;
|
||||
std::vector<uint16_t> criticalLoads;
|
||||
std::vector<uint8_t> warningBells;
|
||||
std::vector<uint16_t> warningLoads;
|
||||
|
||||
bool hasOverload = false;
|
||||
|
||||
for (uint8_t i = 0; i < 16; i++) {
|
||||
uint16_t load = _telemetry.getBellLoad(i);
|
||||
if (load == 0) continue; // Skip inactive bells
|
||||
|
||||
if (_telemetry.isOverloaded(i)) {
|
||||
criticalBells.push_back(i);
|
||||
criticalLoads.push_back(load);
|
||||
hasOverload = true;
|
||||
} else {
|
||||
// Check thresholds - get max load for this bell (assume 60 default)
|
||||
uint16_t criticalThreshold = 54; // 90% of 60
|
||||
uint16_t warningThreshold = 36; // 60% of 60
|
||||
|
||||
if (load > criticalThreshold) {
|
||||
criticalBells.push_back(i);
|
||||
criticalLoads.push_back(load);
|
||||
} else if (load > warningThreshold) {
|
||||
warningBells.push_back(i);
|
||||
warningLoads.push_back(load);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Send notifications if needed
|
||||
if (!criticalBells.empty()) {
|
||||
String severity = hasOverload ? "critical" : "warning";
|
||||
_communicationManager->sendBellOverloadNotification(criticalBells, criticalLoads, severity);
|
||||
} else if (!warningBells.empty()) {
|
||||
_communicationManager->sendBellOverloadNotification(warningBells, warningLoads, "warning");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* BELLENGINE.HPP - High-Precision Bell Timing Engine
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 🔥 THE HEART OF THE VESPER SYSTEM 🔥
|
||||
*
|
||||
* This is the core precision timing engine that controls bell activation with
|
||||
* microsecond accuracy. It runs on a dedicated FreeRTOS task with maximum
|
||||
* priority on Core 1 to ensure no timing interference.
|
||||
*
|
||||
* 🏗️ ARCHITECTURE:
|
||||
* • Completely thread-safe with atomic operations
|
||||
* • Hardware-agnostic through OutputManager abstraction
|
||||
* • High-precision timing using ESP32 microsecond timers
|
||||
* • Comprehensive performance monitoring
|
||||
* • Emergency stop mechanisms for safety
|
||||
*
|
||||
* ⚡ PERFORMANCE FEATURES:
|
||||
* • Dedicated Core 1 execution (no interruption)
|
||||
* • Priority 6 FreeRTOS task (highest available)
|
||||
* • Microsecond-precision delays
|
||||
* • Atomic state management
|
||||
* • Lock-free melody data handling
|
||||
*
|
||||
* 🔒 THREAD SAFETY:
|
||||
* All public methods are thread-safe. Melody data is protected by
|
||||
* critical sections, and engine state uses atomic operations.
|
||||
*
|
||||
* 🚑 EMERGENCY FEATURES:
|
||||
* • Instant emergency stop capability
|
||||
* • Hardware shutdown through OutputManager
|
||||
* • Safe state transitions
|
||||
* • Graceful task cleanup
|
||||
*
|
||||
* 📋 VERSION: 2.0 (Rewritten for modular architecture)
|
||||
* 📅 DATE: 2025
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
// SYSTEM INCLUDES - Core libraries for high-precision timing
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
#include <Arduino.h> // Arduino core functionality
|
||||
#include <vector> // STL vector for melody data storage
|
||||
#include <atomic> // Atomic operations for thread safety
|
||||
#include "freertos/FreeRTOS.h" // FreeRTOS kernel
|
||||
#include "freertos/task.h" // FreeRTOS task management
|
||||
#include "esp_timer.h" // ESP32 high-precision timers
|
||||
#include "../Logging/Logging.hpp" // Centralized logging system
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
// FORWARD DECLARATIONS - Dependencies injected at runtime
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
// These classes are injected via constructor to maintain clean architecture
|
||||
class Player; // Melody playback controller
|
||||
class ConfigManager; // Configuration and settings management
|
||||
class Telemetry; // System monitoring and analytics
|
||||
class OutputManager; // Hardware abstraction layer
|
||||
class CommunicationRouter; // Communication system for notifications
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
// ARCHITECTURE MIGRATION NOTE
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
// BellEngine no longer tracks relay durations - OutputManager handles that now!
|
||||
// This provides clean separation of concerns and hardware abstraction.
|
||||
|
||||
/**
|
||||
* @class BellEngine
|
||||
* @brief High-precision bell timing and control engine
|
||||
*
|
||||
* The BellEngine is the core component responsible for microsecond-precision
|
||||
* bell activation timing. It runs on a dedicated FreeRTOS task with maximum
|
||||
* priority to ensure no timing interference from other system components.
|
||||
*
|
||||
* Key features:
|
||||
* - Thread-safe operation with atomic state management
|
||||
* - Hardware-agnostic through OutputManager abstraction
|
||||
* - Microsecond-precision timing using ESP32 timers
|
||||
* - Comprehensive performance monitoring
|
||||
* - Emergency stop capabilities
|
||||
* - Dedicated Core 1 execution for maximum performance
|
||||
*/
|
||||
class BellEngine {
|
||||
public:
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// CONSTRUCTOR & DESTRUCTOR
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Construct BellEngine with dependency injection
|
||||
* @param player Reference to melody player for coordination
|
||||
* @param configManager Reference to configuration manager for settings
|
||||
* @param telemetry Reference to telemetry system for monitoring
|
||||
* @param outputManager Reference to hardware abstraction layer
|
||||
*
|
||||
* Uses dependency injection pattern for clean architecture and testability.
|
||||
* All dependencies must be valid for the lifetime of this object.
|
||||
*/
|
||||
BellEngine(Player& player, ConfigManager& configManager, Telemetry& telemetry, OutputManager& outputManager);
|
||||
|
||||
/**
|
||||
* @brief Destructor - ensures clean shutdown
|
||||
*
|
||||
* Automatically calls emergencyShutdown() to ensure all relays are
|
||||
* turned off and tasks are properly cleaned up.
|
||||
*/
|
||||
~BellEngine();
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// CORE INITIALIZATION
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Initialize the BellEngine system
|
||||
*
|
||||
* Creates the high-priority timing task on Core 1 with maximum priority.
|
||||
* This task will remain dormant until start() is called, but the
|
||||
* infrastructure is set up for immediate precision timing.
|
||||
*
|
||||
* Task configuration:
|
||||
* - Priority: 6 (highest available)
|
||||
* - Core: 1 (dedicated)
|
||||
* - Stack: 12KB (increased for safety)
|
||||
* - Name: "BellEngine"
|
||||
*
|
||||
*/
|
||||
void begin();
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// ENGINE CONTROL (THREAD-SAFE)
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Start the precision timing engine
|
||||
*
|
||||
* Activates the high-precision timing loop. Requires melody data to be
|
||||
* loaded via setMelodyData() before calling. Uses atomic operations
|
||||
* for thread-safe state management.
|
||||
*
|
||||
* @note Will log error and return if no melody data is available
|
||||
*/
|
||||
void start();
|
||||
|
||||
/**
|
||||
* @brief Stop the timing engine gracefully
|
||||
*
|
||||
* Signals the engine to stop at the next safe opportunity.
|
||||
* Uses atomic flag for thread-safe coordination.
|
||||
*/
|
||||
void stop();
|
||||
|
||||
/**
|
||||
* @brief Emergency stop - immediate shutdown
|
||||
*
|
||||
* Immediately stops all bell activity and shuts down the engine.
|
||||
* Calls emergencyShutdown() to ensure all relays are turned off.
|
||||
* Use this for safety-critical situations.
|
||||
*/
|
||||
void emergencyStop();
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// MELODY DATA INTERFACE (Called by Player)
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Load melody data for playback
|
||||
* @param melodySteps Vector of melody step data (each uint16_t represents note activations)
|
||||
*
|
||||
* Thread-safe method to load melody data. Uses critical sections to ensure
|
||||
* data consistency. The melody data is copied internally for safety.
|
||||
*
|
||||
* @note Each melody step is a bitmask where each bit represents a note/bell
|
||||
*/
|
||||
void setMelodyData(const std::vector<uint16_t>& melodySteps);
|
||||
|
||||
/**
|
||||
* @brief Clear loaded melody data
|
||||
*
|
||||
* Thread-safe method to clear melody data and mark engine as not ready.
|
||||
* Useful for cleanup and preparing for new melody loading.
|
||||
*/
|
||||
void clearMelodyData();
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// STATUS QUERIES (Thread-safe)
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Check if engine is currently running
|
||||
* @return true if engine is actively processing melody data
|
||||
*
|
||||
* Thread-safe atomic read operation.
|
||||
*/
|
||||
bool isRunning() const { return _engineRunning.load(); }
|
||||
|
||||
/**
|
||||
* @brief Check if engine is in emergency stop state
|
||||
* @return true if emergency stop has been activated
|
||||
*
|
||||
* Thread-safe atomic read operation.
|
||||
*/
|
||||
bool isEmergencyStopped() const { return _emergencyStop.load(); }
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// PERFORMANCE MONITORING
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Get maximum measured loop execution time
|
||||
* @return Maximum loop time in microseconds
|
||||
*
|
||||
* Useful for performance tuning and ensuring timing requirements are met.
|
||||
*/
|
||||
uint32_t getMaxLoopTime() const { return _maxLoopTime; }
|
||||
|
||||
/**
|
||||
* @brief Set Communication manager reference for bell notifications
|
||||
* @param commManager Pointer to communication manager
|
||||
*/
|
||||
void setCommunicationManager(CommunicationRouter* commManager);
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// HEALTH CHECK METHOD
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/** @brief Check if BellEngine is in healthy state */
|
||||
bool isHealthy() const;
|
||||
|
||||
|
||||
private:
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// DEPENDENCY INJECTION - References to external systems
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
Player& _player; // Melody playback controller for coordination
|
||||
ConfigManager& _configManager; // Configuration manager for bell settings
|
||||
Telemetry& _telemetry; // System monitoring and strike tracking
|
||||
OutputManager& _outputManager; // 🔥 Hardware abstraction layer for relay control
|
||||
CommunicationRouter* _communicationManager; // Communication system for bell notifications
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// ENGINE STATE (Atomic for thread safety)
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
std::atomic<bool> _engineRunning{false}; // Engine active state flag
|
||||
std::atomic<bool> _emergencyStop{false}; // Emergency stop flag
|
||||
std::atomic<bool> _melodyDataReady{false}; // Melody data loaded and ready flag
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// MELODY DATA (Protected copy for thread safety)
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
std::vector<uint16_t> _melodySteps; // Local copy of melody data for safe access
|
||||
portMUX_TYPE _melodyMutex = portMUX_INITIALIZER_UNLOCKED; // Critical section protection for melody data
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// FREERTOS TASK MANAGEMENT
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
TaskHandle_t _engineTaskHandle = NULL; // Handle to high-priority timing task
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// PERFORMANCE MONITORING VARIABLES
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
uint32_t _maxLoopTime = 0; // Maximum measured loop execution time (microseconds) // Average loop execution time (microseconds)
|
||||
uint32_t _loopCount = 0; // Total number of loops executed
|
||||
uint64_t _totalLoopTime = 0; // Cumulative loop execution time (microseconds)
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// HIGH-PRECISION TIMING
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
esp_timer_handle_t _precisionTimer = nullptr; // ESP32 high-precision timer (currently unused)
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// CORE ENGINE FUNCTIONS (CRITICAL TIMING)
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Main engine timing loop
|
||||
*
|
||||
* Executes one complete timing cycle with performance monitoring.
|
||||
* Called continuously by the engine task.
|
||||
*/
|
||||
void engineLoop();
|
||||
|
||||
/**
|
||||
* @brief Execute melody playback with precision timing
|
||||
*
|
||||
* Processes all melody steps with microsecond-precision delays.
|
||||
* Handles pause states and emergency stops.
|
||||
*/
|
||||
void playbackLoop();
|
||||
|
||||
/**
|
||||
* @brief Activate bells for a specific note
|
||||
* @param note Bitmask representing which bells to activate
|
||||
*
|
||||
* Decodes the note bitmask and activates corresponding bells through
|
||||
* the OutputManager with configured durations.
|
||||
*/
|
||||
void activateNote(uint16_t note);
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// STATIC TASK FUNCTIONS
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Static entry point for FreeRTOS task
|
||||
* @param parameter Pointer to BellEngine instance
|
||||
*
|
||||
* Static function required by FreeRTOS. Casts parameter back to
|
||||
* BellEngine instance and runs the main timing loop.
|
||||
*/
|
||||
static void engineTask(void* parameter);
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// TIMING UTILITIES
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Get current time in microseconds
|
||||
* @return Current time from ESP32 high-precision timer
|
||||
*
|
||||
* Inline function for maximum performance in timing-critical code.
|
||||
*/
|
||||
uint64_t getMicros() const { return esp_timer_get_time(); }
|
||||
|
||||
/**
|
||||
* @brief Perform microsecond-precision delay
|
||||
* @param microseconds Delay duration in microseconds
|
||||
*
|
||||
* Combines FreeRTOS task delay with busy-waiting for maximum precision.
|
||||
* Uses task delay for bulk time, then busy-wait for final precision.
|
||||
*/
|
||||
void preciseDelay(uint32_t microseconds);
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// SAFETY FUNCTIONS
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Emergency hardware shutdown
|
||||
*
|
||||
* Immediately shuts down all relays through OutputManager.
|
||||
* Called during emergency stops and destructor cleanup.
|
||||
* Ensures safe state regardless of current engine state.
|
||||
*/
|
||||
void emergencyShutdown();
|
||||
|
||||
/**
|
||||
* @brief Check telemetry and send overload notifications
|
||||
*
|
||||
* Monitors telemetry for bell overloads and sends notifications
|
||||
* through Communication manager when thresholds are exceeded.
|
||||
* Called after each playback loop.
|
||||
*/
|
||||
void checkAndNotifyOverloads();
|
||||
|
||||
/**
|
||||
* @brief Notify WebSocket clients of fired bells
|
||||
* @param bellIndices Vector of bell indices that were fired (1-indexed)
|
||||
*
|
||||
* Sends INFO/ding message to WebSocket clients only (not MQTT)
|
||||
*/
|
||||
void notifyBellsFired(const std::vector<uint8_t>& bellIndices);
|
||||
};
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// END OF BELLENGINE.HPP
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
@@ -0,0 +1,579 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* BUILTINMELODIES.HPP - Firmware-Baked Melody Library
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 🎵 BUILT-IN MELODY LIBRARY FOR VESPER 🎵
|
||||
*
|
||||
* This file contains melodies baked directly into the firmware, eliminating
|
||||
* the need for SD card downloads. Each melody is stored in PROGMEM to save RAM.
|
||||
*
|
||||
* 🏗️ ARCHITECTURE:
|
||||
* • Melodies stored in PROGMEM (Flash memory, not RAM)
|
||||
* • Each melody step is 2 bytes (uint16_t bitmask)
|
||||
* • Metadata includes name, UID, default speed
|
||||
* • Easy to add new melodies
|
||||
*
|
||||
* 📦 STORAGE EFFICIENCY:
|
||||
* • Small melodies (~30 steps = 60 bytes)
|
||||
* • Large melodies (~200 steps = 400 bytes)
|
||||
* • 40 melodies average = ~6-10KB total (Flash, not RAM!)
|
||||
*
|
||||
* 🎶 MELODY FORMAT:
|
||||
* Each uint16_t is a bitmask:
|
||||
* - Bit 0-15: Which bells/notes to activate
|
||||
* - Example: 0x0001 = Bell 0, 0x0003 = Bells 0+1, 0x8000 = Bell 15
|
||||
*
|
||||
* 📋 VERSION: 1.0
|
||||
* 📅 DATE: 2025-12-28
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <vector>
|
||||
#include <pgmspace.h>
|
||||
|
||||
namespace BuiltInMelodies {
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
// MELODY METADATA STRUCTURE
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
struct MelodyInfo {
|
||||
const char* name; // Display name
|
||||
const char* uid; // Unique identifier
|
||||
const uint16_t* data; // Pointer to melody data in PROGMEM
|
||||
uint16_t stepCount; // Number of steps
|
||||
};
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
// BuiltIn Melodies // More can be added here
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
// 1 Bell Test Melody
|
||||
const uint16_t PROGMEM builtin_1bell_test[] = {
|
||||
0x0001, 0x0000, 0x0001, 0x0000
|
||||
};
|
||||
|
||||
// Doxology Traditional
|
||||
const uint16_t PROGMEM builtin_doxology_traditional[] = {
|
||||
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0000, 0x0000,
|
||||
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0008, 0x0000, 0x0000,
|
||||
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
|
||||
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0008, 0x0000, 0x0000
|
||||
};
|
||||
|
||||
// Doxology Alternative
|
||||
const uint16_t PROGMEM builtin_doxology_alternative[] = {
|
||||
0x0001, 0x0000, 0x0002, 0x0004, 0x0000, 0x0018, 0x0000, 0x0001,
|
||||
0x0000, 0x0002, 0x0004, 0x0000, 0x0018, 0x0000, 0x0001, 0x0000,
|
||||
0x0002, 0x0004, 0x0000, 0x0018, 0x0000, 0x0001, 0x0002, 0x0001,
|
||||
0x0002, 0x0004, 0x0000, 0x0018, 0x0000
|
||||
};
|
||||
|
||||
// Doxology Festive
|
||||
const uint16_t PROGMEM builtin_doxology_festive[] = {
|
||||
0x0002, 0x0004, 0x0009, 0x0004, 0x0002, 0x0004, 0x0011, 0x0004,
|
||||
0x0002, 0x0004, 0x0021, 0x0004, 0x0002, 0x0004, 0x0011, 0x0004
|
||||
};
|
||||
|
||||
// Vesper Traditional
|
||||
const uint16_t PROGMEM builtin_vesper_traditional[] = {
|
||||
0x0001, 0x0002, 0x0004, 0x0000, 0x0001, 0x0002, 0x0004, 0x0000,
|
||||
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0004, 0x0000
|
||||
};
|
||||
|
||||
// Vesper Alternative
|
||||
const uint16_t PROGMEM builtin_vesper_alternative[] = {
|
||||
0x0001, 0x0002, 0x0000, 0x0000, 0x0001, 0x0002, 0x0000, 0x0000,
|
||||
0x0001, 0x0004, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
|
||||
0x0001, 0x0002, 0x0000, 0x0000, 0x0001, 0x0002, 0x0000, 0x0000,
|
||||
0x0001, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
|
||||
0x0001, 0x0002, 0x0000, 0x0000, 0x0001, 0x0002, 0x0000, 0x0000,
|
||||
0x0001, 0x0002, 0x0000, 0x0000, 0x0001, 0x0002, 0x0000, 0x0000,
|
||||
0x0001, 0x0002, 0x0000, 0x0000, 0x0001, 0x0004, 0x0000, 0x0000,
|
||||
0x0001, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000
|
||||
};
|
||||
|
||||
// Catehetical
|
||||
const uint16_t PROGMEM builtin_catehetical[] = {
|
||||
0x0001, 0x0002, 0x0004, 0x0008, 0x0010
|
||||
};
|
||||
|
||||
// Orthros Traditional
|
||||
const uint16_t PROGMEM builtin_orthros_traditional[] = {
|
||||
0x0001, 0x0000, 0x0002, 0x0000, 0x0004, 0x0008, 0x0000, 0x0010,
|
||||
0x0000, 0x0020, 0x0000, 0x0040, 0x0080, 0x0000
|
||||
};
|
||||
|
||||
// Orthros Alternative
|
||||
const uint16_t PROGMEM builtin_orthros_alternative[] = {
|
||||
0x0001, 0x0000, 0x0002, 0x0001, 0x0000, 0x0002, 0x0000, 0x0001,
|
||||
0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0004, 0x0000
|
||||
};
|
||||
|
||||
// Mournfull Toll
|
||||
const uint16_t PROGMEM builtin_mournfull_toll[] = {
|
||||
0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001,
|
||||
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0004, 0x0000,
|
||||
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0004, 0x0000, 0x0000,
|
||||
0x0000, 0x0000, 0x0000, 0x0000, 0x0002, 0x0000, 0x0000, 0x0000,
|
||||
0x0000, 0x0000, 0x0000, 0x0002, 0x0000, 0x0000, 0x0000, 0x0000,
|
||||
0x0000, 0x0000, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
|
||||
0x0000, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000
|
||||
};
|
||||
|
||||
// Mournfull Toll Alternative
|
||||
const uint16_t PROGMEM builtin_mournfull_toll_alternative[] = {
|
||||
0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001,
|
||||
0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0004,
|
||||
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0004, 0x0004,
|
||||
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0002, 0x0000,
|
||||
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0002, 0x0002, 0x0000,
|
||||
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0008, 0x0000, 0x0000,
|
||||
0x0000, 0x0000, 0x0000, 0x0000, 0x0008, 0x0008, 0x0000, 0x0000,
|
||||
0x0000, 0x0000, 0x0000, 0x0000
|
||||
};
|
||||
|
||||
// Mournfull Toll Meg Par
|
||||
const uint16_t PROGMEM builtin_mournfull_toll_meg_par[] = {
|
||||
0x0001, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001,
|
||||
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0001, 0x0001,
|
||||
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0004, 0x0000,
|
||||
0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0004, 0x0000, 0x0000,
|
||||
0x0000, 0x0000, 0x0000, 0x0000, 0x0004, 0x0004, 0x0000, 0x0000,
|
||||
0x0000, 0x0000, 0x0000, 0x0000, 0x0002, 0x0000, 0x0000, 0x0000,
|
||||
0x0000, 0x0000, 0x0000, 0x0002, 0x0000, 0x0000, 0x0000, 0x0000,
|
||||
0x0000, 0x0000, 0x0002, 0x0002, 0x0000, 0x0000, 0x0000, 0x0000,
|
||||
0x0000, 0x0000, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
|
||||
0x0000, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
|
||||
0x0008, 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000
|
||||
};
|
||||
|
||||
// Sematron
|
||||
const uint16_t PROGMEM builtin_sematron[] = {
|
||||
0x0001, 0x0001, 0x0001, 0x0002, 0x0001, 0x0001, 0x0001, 0x0008,
|
||||
0x0001, 0x0001, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0008
|
||||
};
|
||||
|
||||
// Sematron Alternative
|
||||
const uint16_t PROGMEM builtin_sematron_alternative[] = {
|
||||
0x0001, 0x0001, 0x0001, 0x0002, 0x0001, 0x0001, 0x0001, 0x0008,
|
||||
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0001, 0x0001, 0x0008
|
||||
};
|
||||
|
||||
// Athonite 1 2 Voices
|
||||
const uint16_t PROGMEM builtin_athonite_1_2_voices[] = {
|
||||
0x0001, 0x0002, 0x0001, 0x0001, 0x0002, 0x0001, 0x0001, 0x0002,
|
||||
0x0001, 0x0001, 0x0002, 0x0001, 0x0002
|
||||
};
|
||||
|
||||
// Athonite 3 Voices
|
||||
const uint16_t PROGMEM builtin_athonite_3_voices[] = {
|
||||
0x0002, 0x0001, 0x0000, 0x0000, 0x0002, 0x0001, 0x0000, 0x0000,
|
||||
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
|
||||
0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
|
||||
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
|
||||
0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
|
||||
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004
|
||||
};
|
||||
|
||||
// Athonite 3 4 Voices
|
||||
const uint16_t PROGMEM builtin_athonite_3_4_voices[] = {
|
||||
0x0002, 0x0001, 0x0000, 0x0000, 0x0002, 0x0001, 0x0000, 0x0000,
|
||||
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
|
||||
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0000, 0x0005,
|
||||
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0002, 0x0005,
|
||||
0x0002, 0x0001, 0x0008, 0x0005, 0x0002, 0x0001, 0x0000, 0x0005,
|
||||
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0002, 0x0005,
|
||||
0x0002, 0x0001, 0x0009, 0x0002, 0x0001, 0x0005, 0x0002, 0x0001,
|
||||
0x000A, 0x0002, 0x0001, 0x0006, 0x0002, 0x0001, 0x0009, 0x0002,
|
||||
0x0001, 0x0005, 0x0002, 0x0001, 0x000A, 0x0002, 0x0001, 0x0006,
|
||||
0x0002, 0x0001, 0x0009
|
||||
};
|
||||
|
||||
// Athonite 4 8 Voices
|
||||
const uint16_t PROGMEM builtin_athonite_4_8_voices[] = {
|
||||
0x0002, 0x0001, 0x0000, 0x0000, 0x0002, 0x0001, 0x0000, 0x0000,
|
||||
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001,
|
||||
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0000, 0x0005,
|
||||
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0002, 0x0005,
|
||||
0x0002, 0x0001, 0x0008, 0x0005, 0x0002, 0x0001, 0x0000, 0x0005,
|
||||
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0002, 0x0005,
|
||||
0x0002, 0x0001, 0x0009, 0x0002, 0x0001, 0x0011, 0x0002, 0x0001,
|
||||
0x0022, 0x0002, 0x0001, 0x0081, 0x0002, 0x0001, 0x000A, 0x0002,
|
||||
0x0001, 0x0041, 0x0002, 0x0001, 0x0012, 0x0002, 0x0001, 0x0021,
|
||||
0x0002, 0x0001, 0x0082, 0x0002, 0x0001, 0x0009, 0x0002, 0x0001,
|
||||
0x0042, 0x0002, 0x0001, 0x0011, 0x0002, 0x0001, 0x0022, 0x0002,
|
||||
0x0001, 0x0081, 0x0002, 0x0001, 0x000A, 0x0002, 0x0001, 0x0041,
|
||||
0x0002, 0x0001, 0x0000, 0x0005, 0x0002, 0x0001, 0x0000, 0x0005,
|
||||
0x0002, 0x0001, 0x0002, 0x0005, 0x0002, 0x0001, 0x0000, 0x0000,
|
||||
0x0000
|
||||
};
|
||||
|
||||
// Onebyone 2 3 Voices
|
||||
const uint16_t PROGMEM builtin_onebyone_2_3_voices[] = {
|
||||
0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000,
|
||||
0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000,
|
||||
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
|
||||
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
|
||||
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
|
||||
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
|
||||
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
|
||||
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
|
||||
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
|
||||
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
|
||||
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
|
||||
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002
|
||||
};
|
||||
|
||||
// Onebyone 4 8 Voices
|
||||
const uint16_t PROGMEM builtin_onebyone_4_8_voices[] = {
|
||||
0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000,
|
||||
0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000,
|
||||
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
|
||||
0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
|
||||
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
|
||||
0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001, 0x0004,
|
||||
0x0002, 0x0004, 0x0008, 0x0004, 0x0002, 0x0011, 0x0002, 0x0004,
|
||||
0x0008, 0x0004, 0x0002, 0x0021, 0x0002, 0x0004, 0x0008, 0x0004,
|
||||
0x0002, 0x0041, 0x0002, 0x0004, 0x0008, 0x0004, 0x0002, 0x0081,
|
||||
0x0002, 0x0004, 0x0008, 0x0004, 0x0002, 0x0041, 0x0002, 0x0004,
|
||||
0x0008, 0x0004, 0x0002, 0x0021, 0x0002, 0x0004, 0x0008, 0x0004,
|
||||
0x0002, 0x0041, 0x0002, 0x0004, 0x0008, 0x0004, 0x0002, 0x0081,
|
||||
0x0002, 0x0004, 0x0008, 0x0004, 0x0002, 0x0041, 0x0002, 0x0004,
|
||||
0x0008, 0x0004, 0x0002, 0x0021, 0x0002, 0x0004, 0x0008, 0x0004,
|
||||
0x0002, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001,
|
||||
0x0004, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001,
|
||||
0x0004, 0x0001, 0x0002, 0x0001, 0x0004, 0x0001, 0x0002, 0x0001,
|
||||
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001,
|
||||
0x0002, 0x0001, 0x0000
|
||||
};
|
||||
|
||||
// Festive 1Voice
|
||||
const uint16_t PROGMEM builtin_festive_1voice[] = {
|
||||
0x0001, 0x0001, 0x0001, 0x0000, 0x0001, 0x0001, 0x0001, 0x0001,
|
||||
0x0000, 0x0001, 0x0000, 0x0001, 0x0001, 0x0001, 0x0000, 0x0001,
|
||||
0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0000, 0x0001, 0x0000
|
||||
};
|
||||
|
||||
// Festive 4Voices
|
||||
const uint16_t PROGMEM builtin_festive_4voices[] = {
|
||||
0x0001, 0x0002, 0x0004, 0x0009, 0x0002, 0x0001, 0x0004, 0x0009
|
||||
};
|
||||
|
||||
// Festive 5Voices
|
||||
const uint16_t PROGMEM builtin_festive_5voices[] = {
|
||||
0x0001, 0x0002, 0x0004, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
|
||||
0x0008, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0004, 0x0002,
|
||||
0x0001, 0x0002, 0x0001, 0x0002, 0x0010, 0x0002, 0x0001, 0x0002
|
||||
};
|
||||
|
||||
// Festive 5Voice Alternative
|
||||
const uint16_t PROGMEM builtin_festive_5voice_alternative[] = {
|
||||
0x0004, 0x0002, 0x0008, 0x0001, 0x0004, 0x0004, 0x0002, 0x0008,
|
||||
0x0001, 0x0010, 0x0004, 0x0002, 0x0008, 0x0001, 0x0004, 0x0004,
|
||||
0x0002, 0x0008, 0x0001, 0x0011, 0x0004, 0x0002, 0x0008, 0x0001,
|
||||
0x0004, 0x0004, 0x0002, 0x0008, 0x0001, 0x0011, 0x0004, 0x0002,
|
||||
0x0008, 0x0001, 0x0005, 0x0004, 0x0002, 0x0008, 0x0001, 0x0011,
|
||||
0x0004, 0x0002, 0x0008, 0x0001, 0x0005, 0x0004, 0x0002, 0x0008,
|
||||
0x0001, 0x0011, 0x0004, 0x0002, 0x0008, 0x0001, 0x0004, 0x0004,
|
||||
0x0002, 0x0008, 0x0001, 0x0010, 0x0004, 0x0002, 0x0008, 0x0001,
|
||||
0x0004, 0x0004, 0x0002, 0x0008, 0x0001, 0x0010
|
||||
};
|
||||
|
||||
// Festive 6Voices
|
||||
const uint16_t PROGMEM builtin_festive_6voices[] = {
|
||||
0x0001, 0x0002, 0x0004, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002,
|
||||
0x0008, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0004, 0x0002,
|
||||
0x0001, 0x0002, 0x0001, 0x0002, 0x0010, 0x0002, 0x0001, 0x0002,
|
||||
0x0001, 0x0002, 0x0009, 0x0002, 0x0001, 0x0002, 0x0011, 0x0002,
|
||||
0x0001, 0x0002, 0x0005, 0x0002, 0x0001, 0x0002, 0x0021, 0x0002,
|
||||
0x0001, 0x0002, 0x0009, 0x0002, 0x0001, 0x0002, 0x0011, 0x0002,
|
||||
0x0001, 0x0002, 0x0005, 0x0002, 0x0001, 0x0002, 0x0021, 0x0002,
|
||||
0x0001, 0x0002, 0x0009, 0x0002, 0x0001, 0x0002, 0x0011, 0x0002,
|
||||
0x0001, 0x0002, 0x0005, 0x0002, 0x0001, 0x0002, 0x0021, 0x0002,
|
||||
0x0001, 0x0002
|
||||
};
|
||||
|
||||
// Festive 8Voices
|
||||
const uint16_t PROGMEM builtin_festive_8voices[] = {
|
||||
0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080
|
||||
};
|
||||
|
||||
// Ormilia
|
||||
const uint16_t PROGMEM builtin_ormilia[] = {
|
||||
0x0002, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001,
|
||||
0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001,
|
||||
0x0002, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001,
|
||||
0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001,
|
||||
0x0002, 0x0001, 0x0000, 0x0001, 0x0002, 0x0001, 0x0000, 0x0001,
|
||||
0x0002, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001,
|
||||
0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001, 0x0002, 0x0001,
|
||||
0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001,
|
||||
0x0002, 0x0009, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001,
|
||||
0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001,
|
||||
0x0002, 0x0005, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001,
|
||||
0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001, 0x0000, 0x0001,
|
||||
0x0002, 0x0009, 0x0000, 0x0001, 0x0002, 0x0005, 0x0000, 0x0001,
|
||||
0x0002, 0x0009, 0x0000, 0x0001, 0x0002, 0x0005, 0x0000, 0x0001,
|
||||
0x0002, 0x0011, 0x0002, 0x0001, 0x0002, 0x0021, 0x0002, 0x0001,
|
||||
0x0002, 0x0011, 0x0002, 0x0001, 0x0002, 0x0021, 0x0002, 0x0041,
|
||||
0x0002, 0x0081, 0x0002, 0x0009, 0x0002, 0x0041, 0x0002, 0x0081,
|
||||
0x0002, 0x0009, 0x0002, 0x0041, 0x0002, 0x0081, 0x0002, 0x0005,
|
||||
0x0002, 0x0001, 0x0000
|
||||
};
|
||||
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
// MELODY LIBRARY - Array of all built-in melodies
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
const MelodyInfo MELODY_LIBRARY[] = {
|
||||
{
|
||||
"1 Bell Test",
|
||||
"builtin_1bell_test",
|
||||
builtin_1bell_test,
|
||||
sizeof(builtin_1bell_test) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Doxology Traditional",
|
||||
"builtin_doxology_traditional",
|
||||
builtin_doxology_traditional,
|
||||
sizeof(builtin_doxology_traditional) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Doxology Alternative",
|
||||
"builtin_doxology_alternative",
|
||||
builtin_doxology_alternative,
|
||||
sizeof(builtin_doxology_alternative) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Doxology Festive",
|
||||
"builtin_doxology_festive",
|
||||
builtin_doxology_festive,
|
||||
sizeof(builtin_doxology_festive) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Vesper Traditional",
|
||||
"builtin_vesper_traditional",
|
||||
builtin_vesper_traditional,
|
||||
sizeof(builtin_vesper_traditional) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Vesper Alternative",
|
||||
"builtin_vesper_alternative",
|
||||
builtin_vesper_alternative,
|
||||
sizeof(builtin_vesper_alternative) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Catehetical",
|
||||
"builtin_catehetical",
|
||||
builtin_catehetical,
|
||||
sizeof(builtin_catehetical) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Orthros Traditional",
|
||||
"builtin_orthros_traditional",
|
||||
builtin_orthros_traditional,
|
||||
sizeof(builtin_orthros_traditional) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Orthros Alternative",
|
||||
"builtin_orthros_alternative",
|
||||
builtin_orthros_alternative,
|
||||
sizeof(builtin_orthros_alternative) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Mournfull Toll",
|
||||
"builtin_mournfull_toll",
|
||||
builtin_mournfull_toll,
|
||||
sizeof(builtin_mournfull_toll) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Mournfull Toll Alternative",
|
||||
"builtin_mournfull_toll_alternative",
|
||||
builtin_mournfull_toll_alternative,
|
||||
sizeof(builtin_mournfull_toll_alternative) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Mournfull Toll Meg Par",
|
||||
"builtin_mournfull_toll_meg_par",
|
||||
builtin_mournfull_toll_meg_par,
|
||||
sizeof(builtin_mournfull_toll_meg_par) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Sematron",
|
||||
"builtin_sematron",
|
||||
builtin_sematron,
|
||||
sizeof(builtin_sematron) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Sematron Alternative",
|
||||
"builtin_sematron_alternative",
|
||||
builtin_sematron_alternative,
|
||||
sizeof(builtin_sematron_alternative) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Athonite 1 2 Voices",
|
||||
"builtin_athonite_1_2_voices",
|
||||
builtin_athonite_1_2_voices,
|
||||
sizeof(builtin_athonite_1_2_voices) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Athonite 3 Voices",
|
||||
"builtin_athonite_3_voices",
|
||||
builtin_athonite_3_voices,
|
||||
sizeof(builtin_athonite_3_voices) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Athonite 3 4 Voices",
|
||||
"builtin_athonite_3_4_voices",
|
||||
builtin_athonite_3_4_voices,
|
||||
sizeof(builtin_athonite_3_4_voices) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Athonite 4 8 Voices",
|
||||
"builtin_athonite_4_8_voices",
|
||||
builtin_athonite_4_8_voices,
|
||||
sizeof(builtin_athonite_4_8_voices) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Onebyone 2 3 Voices",
|
||||
"builtin_onebyone_2_3_voices",
|
||||
builtin_onebyone_2_3_voices,
|
||||
sizeof(builtin_onebyone_2_3_voices) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Onebyone 4 8 Voices",
|
||||
"builtin_onebyone_4_8_voices",
|
||||
builtin_onebyone_4_8_voices,
|
||||
sizeof(builtin_onebyone_4_8_voices) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Festive 1Voice",
|
||||
"builtin_festive_1voice",
|
||||
builtin_festive_1voice,
|
||||
sizeof(builtin_festive_1voice) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Festive 4Voices",
|
||||
"builtin_festive_4voices",
|
||||
builtin_festive_4voices,
|
||||
sizeof(builtin_festive_4voices) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Festive 5Voices",
|
||||
"builtin_festive_5voices",
|
||||
builtin_festive_5voices,
|
||||
sizeof(builtin_festive_5voices) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Festive 5Voice Alternative",
|
||||
"builtin_festive_5voice_alternative",
|
||||
builtin_festive_5voice_alternative,
|
||||
sizeof(builtin_festive_5voice_alternative) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Festive 6Voices",
|
||||
"builtin_festive_6voices",
|
||||
builtin_festive_6voices,
|
||||
sizeof(builtin_festive_6voices) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Festive 8Voices",
|
||||
"builtin_festive_8voices",
|
||||
builtin_festive_8voices,
|
||||
sizeof(builtin_festive_8voices) / sizeof(uint16_t)
|
||||
},
|
||||
{
|
||||
"Ormilia",
|
||||
"builtin_ormilia",
|
||||
builtin_ormilia,
|
||||
sizeof(builtin_ormilia) / sizeof(uint16_t)
|
||||
}
|
||||
};
|
||||
|
||||
const uint16_t MELODY_COUNT = sizeof(MELODY_LIBRARY) / sizeof(MelodyInfo);
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
// HELPER FUNCTIONS
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Check if a UID is a built-in melody
|
||||
* @param uid The melody UID to check
|
||||
* @return true if it's a built-in melody (starts with "builtin_")
|
||||
*/
|
||||
inline bool isBuiltInMelody(const String& uid) {
|
||||
return uid.startsWith("builtin_");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Find a built-in melody by UID
|
||||
* @param uid The melody UID to find
|
||||
* @return Pointer to MelodyInfo if found, nullptr otherwise
|
||||
*/
|
||||
inline const MelodyInfo* findMelodyByUID(const String& uid) {
|
||||
for (uint16_t i = 0; i < MELODY_COUNT; i++) {
|
||||
if (uid == MELODY_LIBRARY[i].uid) {
|
||||
return &MELODY_LIBRARY[i];
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Load a built-in melody into a vector
|
||||
* @param uid The melody UID to load
|
||||
* @param melodySteps Vector to fill with melody data
|
||||
* @return true if melody was found and loaded, false otherwise
|
||||
*/
|
||||
inline bool loadBuiltInMelody(const String& uid, std::vector<uint16_t>& melodySteps) {
|
||||
const MelodyInfo* melody = findMelodyByUID(uid);
|
||||
if (!melody) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Resize vector and copy data from PROGMEM
|
||||
melodySteps.resize(melody->stepCount);
|
||||
for (uint16_t i = 0; i < melody->stepCount; i++) {
|
||||
melodySteps[i] = pgm_read_word(&(melody->data[i]));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Get list of all built-in melodies as JSON string
|
||||
* @return JSON array string of melody names and UIDs
|
||||
*/
|
||||
inline String getBuiltInMelodiesJSON() {
|
||||
String json = "[";
|
||||
for (uint16_t i = 0; i < MELODY_COUNT; i++) {
|
||||
if (i > 0) json += ",";
|
||||
json += "{";
|
||||
json += "\"name\":\"" + String(MELODY_LIBRARY[i].name) + "\",";
|
||||
json += "\"uid\":\"" + String(MELODY_LIBRARY[i].uid) + "\",";
|
||||
json += "}";
|
||||
}
|
||||
json += "]";
|
||||
return json;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
# Built-In Melodies System
|
||||
|
||||
## Overview
|
||||
|
||||
The built-in melodies system allows you to bake melodies directly into the firmware, eliminating the need for SD card downloads. Melodies are stored in **PROGMEM** (Flash memory), so they don't consume precious RAM.
|
||||
|
||||
## How It Works
|
||||
|
||||
1. **Check**: When a melody is requested, the Player first checks if the UID starts with `builtin_`
|
||||
2. **Load**: If it's built-in, the melody is loaded from Flash memory (PROGMEM)
|
||||
3. **Fallback**: If not built-in, it loads from SD card as usual
|
||||
|
||||
## Adding New Melodies
|
||||
|
||||
### Step 1: Create Your Melody Data
|
||||
|
||||
Each melody step is a **2-byte (uint16_t) bitmask** representing which bells to activate:
|
||||
|
||||
```cpp
|
||||
// Example: Simple pattern
|
||||
const uint16_t PROGMEM melody_my_tune[] = {
|
||||
0x0001, // Bell 0
|
||||
0x0002, // Bell 1
|
||||
0x0004, // Bell 2
|
||||
0x0008, // Bell 3
|
||||
0x0003, // Bells 0+1 together
|
||||
0x000F // Bells 0+1+2+3 together
|
||||
};
|
||||
```
|
||||
|
||||
**Bitmask Reference:**
|
||||
- `0x0001` = Bell 0 (bit 0)
|
||||
- `0x0002` = Bell 1 (bit 1)
|
||||
- `0x0004` = Bell 2 (bit 2)
|
||||
- `0x0008` = Bell 3 (bit 3)
|
||||
- `0x0010` = Bell 4 (bit 4)
|
||||
- `0x0020` = Bell 5 (bit 5)
|
||||
- `0x0040` = Bell 6 (bit 6)
|
||||
- `0x0080` = Bell 7 (bit 7)
|
||||
- `0x0100` = Bell 8 (bit 8)
|
||||
- ... up to `0x8000` = Bell 15 (bit 15)
|
||||
- `0x0000` = Silence/rest
|
||||
|
||||
**Combining Bells:**
|
||||
- `0x0003` = Bells 0+1 (0x0001 | 0x0002)
|
||||
- `0x0005` = Bells 0+2 (0x0001 | 0x0004)
|
||||
- `0x000F` = Bells 0+1+2+3
|
||||
- `0xFFFF` = All 16 bells
|
||||
|
||||
### Step 2: Add to BuiltInMelodies.hpp
|
||||
|
||||
Open `src/BuiltInMelodies/BuiltInMelodies.hpp` and:
|
||||
|
||||
1. **Add your melody array:**
|
||||
```cpp
|
||||
// Your new melody
|
||||
const uint16_t PROGMEM melody_my_awesome_tune[] = {
|
||||
0x0001, 0x0002, 0x0004, 0x0008,
|
||||
0x0010, 0x0020, 0x0040, 0x0080,
|
||||
// ... up to 200 steps
|
||||
};
|
||||
```
|
||||
|
||||
2. **Add to MELODY_LIBRARY array:**
|
||||
```cpp
|
||||
const MelodyInfo MELODY_LIBRARY[] = {
|
||||
// ... existing melodies ...
|
||||
|
||||
// Your new melody
|
||||
{
|
||||
"My Awesome Tune", // Display name
|
||||
"builtin_my_awesome_tune", // UID (must start with "builtin_")
|
||||
melody_my_awesome_tune, // Data array
|
||||
sizeof(melody_my_awesome_tune) / sizeof(uint16_t), // Step count
|
||||
200 // Default speed in milliseconds per beat
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### Step 3: Use Your Melody
|
||||
|
||||
Send a play command with the built-in melody UID:
|
||||
|
||||
**MQTT:**
|
||||
```json
|
||||
{
|
||||
"group": "playback",
|
||||
"action": "play",
|
||||
"uid": "builtin_my_awesome_tune",
|
||||
"name": "My Awesome Tune",
|
||||
"speed": 200
|
||||
}
|
||||
```
|
||||
|
||||
**WebSocket/HTTP:**
|
||||
```json
|
||||
{
|
||||
"group": "playback",
|
||||
"action": "play",
|
||||
"uid": "builtin_my_awesome_tune",
|
||||
"name": "My Awesome Tune",
|
||||
"speed": 200
|
||||
}
|
||||
```
|
||||
|
||||
## Pre-Loaded Melodies
|
||||
|
||||
The following melodies are already built-in:
|
||||
|
||||
| UID | Name | Steps | Default Speed |
|
||||
|-----|------|-------|---------------|
|
||||
| `builtin_scale` | Simple Scale | 8 | 200ms |
|
||||
| `builtin_happy_birthday` | Happy Birthday | 23 | 250ms |
|
||||
| `builtin_jingle_bells` | Jingle Bells | 32 | 180ms |
|
||||
| `builtin_westminster` | Westminster Chimes | 16 | 400ms |
|
||||
| `builtin_alarm` | Alarm | 16 | 150ms |
|
||||
| `builtin_doorbell` | Doorbell | 4 | 300ms |
|
||||
| `builtin_single_bell` | Single Bell Test | 1 | 100ms |
|
||||
|
||||
## Memory Usage
|
||||
|
||||
### Flash Memory (PROGMEM)
|
||||
- Small melody (~30 steps): **60 bytes**
|
||||
- Large melody (~200 steps): **400 bytes**
|
||||
- 40 melodies average: **~6-10KB** (stored in Flash, not RAM!)
|
||||
|
||||
### RAM Usage
|
||||
Only the **currently playing melody** is loaded into RAM. Built-in melodies are copied from Flash when needed.
|
||||
|
||||
## Tips
|
||||
|
||||
1. **Always use `builtin_` prefix** for UIDs to identify them as built-in
|
||||
2. **Test with small melodies first** before adding large ones
|
||||
3. **Use hex calculator** for complex bell combinations: `0x0001 | 0x0004 = 0x0005`
|
||||
4. **Add rests** with `0x0000` for silence between notes
|
||||
5. **Keep it simple** - most melodies work great with 30-50 steps
|
||||
|
||||
## Converting Binary Files to Code
|
||||
|
||||
If you have existing binary melody files and want to convert them to built-in format:
|
||||
|
||||
```python
|
||||
# Python script to convert binary file to C++ array
|
||||
with open('melody.bin', 'rb') as f:
|
||||
data = f.read()
|
||||
|
||||
print("const uint16_t PROGMEM melody_name[] = {")
|
||||
for i in range(0, len(data), 2):
|
||||
if i % 16 == 0:
|
||||
print(" ", end="")
|
||||
high = data[i]
|
||||
low = data[i+1]
|
||||
value = (high << 8) | low
|
||||
print(f"0x{value:04X}", end="")
|
||||
if i < len(data) - 2:
|
||||
print(", ", end="")
|
||||
if (i + 2) % 16 == 0:
|
||||
print()
|
||||
print("\n};")
|
||||
```
|
||||
|
||||
## Example: Creating a Custom Melody
|
||||
|
||||
Let's create "Mary Had a Little Lamb":
|
||||
|
||||
```cpp
|
||||
// Mary Had a Little Lamb
|
||||
// Notes: E D C D E E E, D D D, E G G
|
||||
// Mapping: E=0, D=1, C=2, G=3
|
||||
const uint16_t PROGMEM melody_mary_lamb[] = {
|
||||
0x0001, 0x0002, 0x0004, 0x0002, // E D C D
|
||||
0x0001, 0x0001, 0x0001, 0x0000, // E E E (rest)
|
||||
0x0002, 0x0002, 0x0002, 0x0000, // D D D (rest)
|
||||
0x0001, 0x0008, 0x0008 // E G G
|
||||
};
|
||||
|
||||
// Add to MELODY_LIBRARY:
|
||||
{
|
||||
"Mary Had a Little Lamb",
|
||||
"builtin_mary_lamb",
|
||||
melody_mary_lamb,
|
||||
sizeof(melody_mary_lamb) / sizeof(uint16_t),
|
||||
300 // 300ms per beat
|
||||
}
|
||||
```
|
||||
|
||||
Now you can play it with UID `builtin_mary_lamb`!
|
||||
@@ -0,0 +1,169 @@
|
||||
#include "ClientManager.hpp"
|
||||
|
||||
#define TAG "ClientManager"
|
||||
#include "../Logging/Logging.hpp"
|
||||
|
||||
ClientManager::ClientManager() {
|
||||
LOG_INFO(TAG, "Client Manager initialized !");
|
||||
}
|
||||
|
||||
ClientManager::~ClientManager() {
|
||||
_clients.clear();
|
||||
LOG_INFO(TAG, "Client Manager destroyed");
|
||||
}
|
||||
|
||||
void ClientManager::addClient(AsyncWebSocketClient* client, DeviceType deviceType) {
|
||||
if (!isValidClient(client)) {
|
||||
LOG_WARNING(TAG, "Client Manager - Cannot add invalid client");
|
||||
return;
|
||||
}
|
||||
|
||||
uint32_t clientId = client->id();
|
||||
_clients[clientId] = ClientInfo(client, deviceType);
|
||||
|
||||
LOG_INFO(TAG, "Client Manager - Client #%u added as %s device", clientId, deviceTypeToString(deviceType));
|
||||
}
|
||||
|
||||
void ClientManager::removeClient(uint32_t clientId) {
|
||||
auto it = _clients.find(clientId);
|
||||
if (it != _clients.end()) {
|
||||
LOG_INFO(TAG, "Client Manager - Client #%u removed (%s device)", clientId,
|
||||
deviceTypeToString(it->second.deviceType));
|
||||
_clients.erase(it);
|
||||
}
|
||||
}
|
||||
|
||||
void ClientManager::updateClientType(uint32_t clientId, DeviceType deviceType) {
|
||||
auto it = _clients.find(clientId);
|
||||
if (it != _clients.end()) {
|
||||
DeviceType oldType = it->second.deviceType;
|
||||
it->second.deviceType = deviceType;
|
||||
LOG_INFO(TAG, "Client Manager - Client #%u type updated from %s to %s", clientId,
|
||||
deviceTypeToString(oldType), deviceTypeToString(deviceType));
|
||||
}
|
||||
}
|
||||
|
||||
void ClientManager::updateClientLastSeen(uint32_t clientId) {
|
||||
auto it = _clients.find(clientId);
|
||||
if (it != _clients.end()) {
|
||||
it->second.lastSeen = millis();
|
||||
}
|
||||
}
|
||||
|
||||
bool ClientManager::isClientConnected(uint32_t clientId) const {
|
||||
auto it = _clients.find(clientId);
|
||||
if (it != _clients.end()) {
|
||||
return it->second.isConnected &&
|
||||
isValidClient(it->second.client);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
ClientManager::DeviceType ClientManager::getClientType(uint32_t clientId) const {
|
||||
auto it = _clients.find(clientId);
|
||||
return (it != _clients.end()) ? it->second.deviceType : DeviceType::UNKNOWN;
|
||||
}
|
||||
|
||||
ClientManager::ClientInfo* ClientManager::getClientInfo(uint32_t clientId) {
|
||||
auto it = _clients.find(clientId);
|
||||
return (it != _clients.end()) ? &it->second : nullptr;
|
||||
}
|
||||
|
||||
bool ClientManager::sendToClient(uint32_t clientId, const String& message) {
|
||||
auto it = _clients.find(clientId);
|
||||
if (it != _clients.end() && isValidClient(it->second.client)) {
|
||||
it->second.client->text(message);
|
||||
updateClientLastSeen(clientId);
|
||||
LOG_DEBUG(TAG, "Client Manager - Message sent to client #%u: %s", clientId, message.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
LOG_WARNING(TAG, "Client Manager - Failed to send message to client #%u - client not found or invalid", clientId);
|
||||
return false;
|
||||
}
|
||||
|
||||
void ClientManager::sendToMasterClients(const String& message) {
|
||||
int count = 0;
|
||||
for (auto& pair : _clients) {
|
||||
if (pair.second.deviceType == DeviceType::MASTER &&
|
||||
isValidClient(pair.second.client)) {
|
||||
pair.second.client->text(message);
|
||||
updateClientLastSeen(pair.first);
|
||||
count++;
|
||||
}
|
||||
}
|
||||
LOG_DEBUG(TAG, "Client Manager - Message sent to %d master client(s): %s", count, message.c_str());
|
||||
}
|
||||
|
||||
void ClientManager::sendToSecondaryClients(const String& message) {
|
||||
int count = 0;
|
||||
for (auto& pair : _clients) {
|
||||
if (pair.second.deviceType == DeviceType::SECONDARY &&
|
||||
isValidClient(pair.second.client)) {
|
||||
pair.second.client->text(message);
|
||||
updateClientLastSeen(pair.first);
|
||||
count++;
|
||||
}
|
||||
}
|
||||
LOG_DEBUG(TAG, "Client Manager - Message sent to %d secondary client(s): %s", count, message.c_str());
|
||||
}
|
||||
|
||||
void ClientManager::broadcastToAll(const String& message) {
|
||||
int count = 0;
|
||||
for (auto& pair : _clients) {
|
||||
if (isValidClient(pair.second.client)) {
|
||||
pair.second.client->text(message);
|
||||
updateClientLastSeen(pair.first);
|
||||
count++;
|
||||
}
|
||||
}
|
||||
LOG_DEBUG(TAG, "Client Manager - Message broadcasted to %d client(s): %s", count, message.c_str());
|
||||
}
|
||||
|
||||
void ClientManager::cleanupDisconnectedClients() {
|
||||
auto it = _clients.begin();
|
||||
while (it != _clients.end()) {
|
||||
if (!isValidClient(it->second.client)) {
|
||||
LOG_DEBUG(TAG, "Client Manager - Cleaning up disconnected client #%u", it->first);
|
||||
it->second.isConnected = false;
|
||||
it = _clients.erase(it);
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String ClientManager::getClientListJson() const {
|
||||
StaticJsonDocument<512> doc;
|
||||
JsonArray clients = doc.createNestedArray("clients");
|
||||
|
||||
for (const auto& pair : _clients) {
|
||||
JsonObject client = clients.createNestedObject();
|
||||
client["id"] = pair.first;
|
||||
client["type"] = deviceTypeToString(pair.second.deviceType);
|
||||
client["connected"] = isValidClient(pair.second.client);
|
||||
client["last_seen"] = pair.second.lastSeen;
|
||||
}
|
||||
|
||||
String result;
|
||||
serializeJson(doc, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
const char* ClientManager::deviceTypeToString(DeviceType type) const {
|
||||
switch (type) {
|
||||
case DeviceType::MASTER: return "master";
|
||||
case DeviceType::SECONDARY: return "secondary";
|
||||
default: return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
ClientManager::DeviceType ClientManager::stringToDeviceType(const String& typeStr) const {
|
||||
if (typeStr == "master") return DeviceType::MASTER;
|
||||
if (typeStr == "secondary") return DeviceType::SECONDARY;
|
||||
return DeviceType::UNKNOWN;
|
||||
}
|
||||
|
||||
bool ClientManager::isValidClient(AsyncWebSocketClient* client) const {
|
||||
return client != nullptr && client->status() == WS_CONNECTED;
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* CLIENTMANAGER.HPP - WebSocket Client Management System
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 📱 MULTI-CLIENT WEBSOCKET MANAGEMENT 📱
|
||||
*
|
||||
* This class manages multiple WebSocket clients with device type identification
|
||||
* and provides targeted messaging capabilities for master/secondary device roles.
|
||||
*
|
||||
* 🏗️ ARCHITECTURE:
|
||||
* • Track multiple connected WebSocket clients
|
||||
* • Identify clients as "master" or "secondary" devices
|
||||
* • Provide targeted and broadcast messaging capabilities
|
||||
* • Automatic cleanup of disconnected clients
|
||||
*
|
||||
* 📱 CLIENT TYPES:
|
||||
* • Master: Primary control device (usually main Android app)
|
||||
* • Secondary: Additional control devices (up to 5 total devices)
|
||||
*
|
||||
* 🔄 CLIENT LIFECYCLE:
|
||||
* • Auto-registration on WebSocket connect
|
||||
* • Device type identification via initial handshake
|
||||
* • Automatic cleanup on disconnect
|
||||
* • Connection state monitoring
|
||||
*
|
||||
* 📡 MESSAGING FEATURES:
|
||||
* • Send to specific client by WebSocket ID
|
||||
* • Send to master/secondary device groups
|
||||
* • Broadcast to all connected clients
|
||||
* • Message delivery confirmation
|
||||
*
|
||||
* 📋 VERSION: 1.0 (Initial multi-client support)
|
||||
* 📅 DATE: 2025
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <ESPAsyncWebServer.h>
|
||||
#include <ArduinoJson.h>
|
||||
#include <map>
|
||||
|
||||
class ClientManager {
|
||||
public:
|
||||
enum class DeviceType {
|
||||
UNKNOWN,
|
||||
MASTER,
|
||||
SECONDARY
|
||||
};
|
||||
|
||||
struct ClientInfo {
|
||||
AsyncWebSocketClient* client;
|
||||
DeviceType deviceType;
|
||||
uint32_t lastSeen;
|
||||
bool isConnected;
|
||||
|
||||
ClientInfo() : client(nullptr), deviceType(DeviceType::UNKNOWN),
|
||||
lastSeen(0), isConnected(false) {}
|
||||
|
||||
ClientInfo(AsyncWebSocketClient* c, DeviceType type)
|
||||
: client(c), deviceType(type), lastSeen(millis()), isConnected(true) {}
|
||||
};
|
||||
|
||||
ClientManager();
|
||||
~ClientManager();
|
||||
|
||||
// Client lifecycle management
|
||||
void addClient(AsyncWebSocketClient* client, DeviceType deviceType = DeviceType::UNKNOWN);
|
||||
void removeClient(uint32_t clientId);
|
||||
void updateClientType(uint32_t clientId, DeviceType deviceType);
|
||||
void updateClientLastSeen(uint32_t clientId);
|
||||
|
||||
// Client information
|
||||
bool hasClients() const { return !_clients.empty(); }
|
||||
size_t getClientCount() const { return _clients.size(); }
|
||||
bool isClientConnected(uint32_t clientId) const;
|
||||
DeviceType getClientType(uint32_t clientId) const;
|
||||
ClientInfo* getClientInfo(uint32_t clientId);
|
||||
|
||||
// Messaging methods
|
||||
bool sendToClient(uint32_t clientId, const String& message);
|
||||
void sendToMasterClients(const String& message);
|
||||
void sendToSecondaryClients(const String& message);
|
||||
void broadcastToAll(const String& message);
|
||||
|
||||
// Utility methods
|
||||
void cleanupDisconnectedClients();
|
||||
String getClientListJson() const;
|
||||
|
||||
private:
|
||||
std::map<uint32_t, ClientInfo> _clients;
|
||||
|
||||
// Helper methods
|
||||
const char* deviceTypeToString(DeviceType type) const;
|
||||
DeviceType stringToDeviceType(const String& typeStr) const;
|
||||
bool isValidClient(AsyncWebSocketClient* client) const;
|
||||
};
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,163 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* COMMANDHANDLER.HPP - Unified Command Processing
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* ⚙️ COMMAND ROUTER AND PROCESSOR ⚙️
|
||||
*
|
||||
* Processes all incoming commands from both MQTT and WebSocket:
|
||||
* • System commands (ping, status, identify)
|
||||
* • Playback commands
|
||||
* • File manager commands
|
||||
* • Relay setup commands
|
||||
* • Clock setup commands
|
||||
* • Firmware management
|
||||
* • Network configuration
|
||||
*
|
||||
* 📋 VERSION: 1.0
|
||||
* 📅 DATE: 2025-10-01
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <ArduinoJson.h>
|
||||
|
||||
// Forward declarations
|
||||
class ConfigManager;
|
||||
class OTAManager;
|
||||
class Player;
|
||||
class FileManager;
|
||||
class Timekeeper;
|
||||
class FirmwareValidator;
|
||||
class ClientManager;
|
||||
class Telemetry;
|
||||
class CommunicationRouter;
|
||||
|
||||
class CommandHandler {
|
||||
public:
|
||||
// Message source identification
|
||||
enum class MessageSource {
|
||||
MQTT,
|
||||
WEBSOCKET,
|
||||
UART
|
||||
};
|
||||
|
||||
struct MessageContext {
|
||||
MessageSource source;
|
||||
uint32_t clientId; // Only for WebSocket
|
||||
|
||||
MessageContext(MessageSource src, uint32_t id = 0)
|
||||
: source(src), clientId(id) {}
|
||||
};
|
||||
|
||||
// Response callback type
|
||||
using ResponseCallback = std::function<void(const String& response, const MessageContext& context)>;
|
||||
|
||||
explicit CommandHandler(ConfigManager& configManager,
|
||||
OTAManager& otaManager);
|
||||
~CommandHandler();
|
||||
|
||||
/**
|
||||
* @brief Set component references
|
||||
*/
|
||||
void setPlayerReference(Player* player);
|
||||
void setFileManagerReference(FileManager* fm);
|
||||
void setTimeKeeperReference(Timekeeper* tk);
|
||||
void setFirmwareValidatorReference(FirmwareValidator* fv);
|
||||
void setClientManagerReference(ClientManager* cm);
|
||||
void setTelemetryReference(Telemetry* telemetry);
|
||||
void setCommunicationRouterReference(CommunicationRouter* comm);
|
||||
|
||||
/**
|
||||
* @brief Set response callback for sending responses back
|
||||
*/
|
||||
void setResponseCallback(ResponseCallback callback);
|
||||
|
||||
/**
|
||||
* @brief Process incoming command
|
||||
* @param command JSON command document
|
||||
* @param context Message context (source and client ID)
|
||||
*/
|
||||
void processCommand(JsonDocument& command, const MessageContext& context);
|
||||
|
||||
private:
|
||||
// Dependencies
|
||||
ConfigManager& _configManager;
|
||||
OTAManager& _otaManager;
|
||||
Player* _player;
|
||||
FileManager* _fileManager;
|
||||
Timekeeper* _timeKeeper;
|
||||
FirmwareValidator* _firmwareValidator;
|
||||
ClientManager* _clientManager;
|
||||
Telemetry* _telemetry;
|
||||
CommunicationRouter* _communicationRouter;
|
||||
ResponseCallback _responseCallback;
|
||||
|
||||
// Response helpers
|
||||
void sendResponse(const String& response, const MessageContext& context);
|
||||
void sendSuccessResponse(const String& type, const String& payload, const MessageContext& context);
|
||||
void sendErrorResponse(const String& type, const String& message, const MessageContext& context);
|
||||
|
||||
// Command handlers
|
||||
void handlePingCommand(const MessageContext& context);
|
||||
void handleStatusCommand(const MessageContext& context);
|
||||
void handleIdentifyCommand(JsonVariant contents, const MessageContext& context);
|
||||
void handlePlaybackCommand(JsonVariant contents, const MessageContext& context);
|
||||
void handleFileManagerCommand(JsonVariant contents, const MessageContext& context);
|
||||
void handleRelaySetupCommand(JsonVariant contents, const MessageContext& context);
|
||||
void handleClockSetupCommand(JsonVariant contents, const MessageContext& context);
|
||||
void handleSystemInfoCommand(JsonVariant contents, const MessageContext& context);
|
||||
void handleSystemCommand(JsonVariant contents, const MessageContext& context);
|
||||
|
||||
// File Manager sub-commands
|
||||
void handleListMelodiesCommand(const MessageContext& context);
|
||||
void handleDownloadMelodyCommand(JsonVariant contents, const MessageContext& context);
|
||||
void handleDeleteMelodyCommand(JsonVariant contents, const MessageContext& context);
|
||||
|
||||
// Relay Setup sub-commands
|
||||
void handleSetRelayTimersCommand(JsonVariant contents, const MessageContext& context);
|
||||
void handleSetRelayOutputsCommand(JsonVariant contents, const MessageContext& context);
|
||||
|
||||
// Clock Setup sub-commands
|
||||
void handleSetClockOutputsCommand(JsonVariant contents, const MessageContext& context);
|
||||
void handleSetClockTimingsCommand(JsonVariant contents, const MessageContext& context);
|
||||
void handleSetClockAlertsCommand(JsonVariant contents, const MessageContext& context);
|
||||
void handleSetClockBacklightCommand(JsonVariant contents, const MessageContext& context);
|
||||
void handleSetClockSilenceCommand(JsonVariant contents, const MessageContext& context);
|
||||
void handleSetRtcTimeCommand(JsonVariant contents, const MessageContext& context);
|
||||
void handleSetPhysicalClockTimeCommand(JsonVariant contents, const MessageContext& context);
|
||||
void handlePauseClockUpdatesCommand(JsonVariant contents, const MessageContext& context);
|
||||
void handleSetClockEnabledCommand(JsonVariant contents, const MessageContext& context);
|
||||
|
||||
// System Info sub-commands
|
||||
void handleGetDeviceTimeCommand(const MessageContext& context);
|
||||
void handleGetClockTimeCommand(const MessageContext& context);
|
||||
void handleCommitFirmwareCommand(const MessageContext& context);
|
||||
void handleRollbackFirmwareCommand(const MessageContext& context);
|
||||
void handleGetFirmwareStatusCommand(const MessageContext& context);
|
||||
void handleNetworkInfoCommand(const MessageContext& context);
|
||||
void handleGetFullSettingsCommand(const MessageContext& context);
|
||||
void handleSyncTimeToLcdCommand(const MessageContext& context);
|
||||
|
||||
// Network configuration
|
||||
void handleSetNetworkConfigCommand(JsonVariant contents, const MessageContext& context);
|
||||
|
||||
// System Config
|
||||
void handleResetDefaultsCommand(const MessageContext& context);
|
||||
|
||||
// Log Level Commands
|
||||
void handleSetSerialLogLevelCommand(JsonVariant contents, const MessageContext& context);
|
||||
void handleSetSdLogLevelCommand(JsonVariant contents, const MessageContext& context);
|
||||
void handleSetMqttLogLevelCommand(JsonVariant contents, const MessageContext& context);
|
||||
|
||||
// MQTT Control Commands
|
||||
void handleSetMqttEnabledCommand(JsonVariant contents, const MessageContext& context);
|
||||
|
||||
// Device Control Commands
|
||||
void handleRestartCommand(const MessageContext& context);
|
||||
void handleForceUpdateCommand(JsonVariant contents, const MessageContext& context);
|
||||
void handleCustomUpdateCommand(JsonVariant contents, const MessageContext& context);
|
||||
};
|
||||
@@ -0,0 +1,417 @@
|
||||
/*
|
||||
* COMMUNICATIONROUTER.CPP - Communication Router Implementation
|
||||
*/
|
||||
|
||||
#include "CommunicationRouter.hpp"
|
||||
|
||||
#define TAG "CommRouter"
|
||||
#include "../../ConfigManager/ConfigManager.hpp"
|
||||
#include "../../OTAManager/OTAManager.hpp"
|
||||
#include "../../Networking/Networking.hpp"
|
||||
#include "../../Logging/Logging.hpp"
|
||||
#include "../../Player/Player.hpp"
|
||||
#include "../../FileManager/FileManager.hpp"
|
||||
#include "../../TimeKeeper/TimeKeeper.hpp"
|
||||
#include "../../FirmwareValidator/FirmwareValidator.hpp"
|
||||
|
||||
CommunicationRouter::CommunicationRouter(ConfigManager& configManager,
|
||||
OTAManager& otaManager,
|
||||
Networking& networking,
|
||||
AsyncWebServer& server,
|
||||
AsyncWebSocket& webSocket,
|
||||
AsyncUDP& udp)
|
||||
: _configManager(configManager)
|
||||
, _otaManager(otaManager)
|
||||
, _networking(networking)
|
||||
, _server(server)
|
||||
, _webSocket(webSocket)
|
||||
, _udp(udp)
|
||||
, _player(nullptr)
|
||||
, _fileManager(nullptr)
|
||||
, _timeKeeper(nullptr)
|
||||
, _firmwareValidator(nullptr)
|
||||
, _mqttClient(configManager, networking)
|
||||
, _clientManager()
|
||||
, _wsServer(webSocket, _clientManager)
|
||||
, _commandHandler(configManager, otaManager)
|
||||
, _httpHandler(server, configManager)
|
||||
, _uartHandler()
|
||||
, _settingsServer(server, configManager, networking) {}
|
||||
|
||||
CommunicationRouter::~CommunicationRouter() {}
|
||||
|
||||
void CommunicationRouter::begin() {
|
||||
LOG_INFO(TAG, "Initializing Communication Router v4.0 (Modular)");
|
||||
|
||||
// 🔥 CRITICAL: Initialize WebSocket FIRST to ensure it's always set up
|
||||
// Even if MQTT fails, we want WebSocket to work!
|
||||
LOG_INFO(TAG, "Setting up WebSocket server...");
|
||||
|
||||
// Initialize WebSocket server
|
||||
_wsServer.begin();
|
||||
_wsServer.setCallback([this](uint32_t clientId, const JsonDocument& message) {
|
||||
onWebSocketMessage(clientId, message);
|
||||
});
|
||||
|
||||
// 🔥 CRITICAL FIX: Attach WebSocket handler to AsyncWebServer
|
||||
// This MUST happen before any potential failures!
|
||||
_server.addHandler(&_webSocket);
|
||||
LOG_INFO(TAG, "✅ WebSocket handler attached to AsyncWebServer on /ws");
|
||||
|
||||
//Now initialize MQTT client (can fail without breaking WebSocket)
|
||||
try {
|
||||
LOG_INFO(TAG, "Setting up MQTT client...");
|
||||
_mqttClient.begin();
|
||||
_mqttClient.setCallback([this](const String& topic, const String& payload) {
|
||||
onMqttMessage(topic, payload);
|
||||
});
|
||||
|
||||
// Setup MQTT logging callback
|
||||
String logTopic = "vesper/" + _configManager.getDeviceUID() + "/logs";
|
||||
Logging::setMqttPublishCallback(
|
||||
[this](const String& topic, const String& payload, int qos) {
|
||||
_mqttClient.publish(topic, payload, qos, false);
|
||||
},
|
||||
logTopic
|
||||
);
|
||||
|
||||
// Apply log levels from config for all three channels
|
||||
Logging::setSerialLevel((Logging::LogLevel)_configManager.getSerialLogLevel());
|
||||
Logging::setMqttLevel((Logging::LogLevel)_configManager.getMqttLogLevel());
|
||||
Logging::setSdLevel((Logging::LogLevel)_configManager.getSdLogLevel());
|
||||
LOG_INFO(TAG, "Log levels applied — Serial:%d MQTT:%d SD:%d",
|
||||
_configManager.getSerialLogLevel(),
|
||||
_configManager.getMqttLogLevel(),
|
||||
_configManager.getSdLogLevel());
|
||||
|
||||
// Silence MQTT-internal subsystems on the MQTT channel to prevent log storms.
|
||||
// These systems generate logs while sending logs — suppress them over MQTT only.
|
||||
Logging::setSubsystemMqttLevel("MQTTClient", Logging::NONE);
|
||||
Logging::setSubsystemMqttLevel("CommRouter", Logging::WARNING);
|
||||
Logging::setSubsystemMqttLevel("Logger", Logging::NONE);
|
||||
|
||||
LOG_INFO(TAG, "✅ MQTT client initialized");
|
||||
} catch (...) {
|
||||
LOG_ERROR(TAG, "❌ MQTT initialization failed, but WebSocket is still available");
|
||||
}
|
||||
|
||||
// Wire up SD logging channel (requires FileManager to be set first via setFileManagerReference)
|
||||
// SD callback is registered lazily in setFileManagerReference once the pointer is available
|
||||
|
||||
// 🔥 CRITICAL FIX: Connect ClientManager to CommandHandler
|
||||
_commandHandler.setClientManagerReference(&_clientManager);
|
||||
LOG_INFO(TAG, "ClientManager reference set for CommandHandler");
|
||||
|
||||
// 🔥 Set CommunicationRouter reference for MQTT control commands
|
||||
_commandHandler.setCommunicationRouterReference(this);
|
||||
LOG_INFO(TAG, "CommunicationRouter reference set for CommandHandler");
|
||||
|
||||
// Setup command handler response callback
|
||||
_commandHandler.setResponseCallback([this](const String& response, const CommandHandler::MessageContext& context) {
|
||||
sendResponse(response, context);
|
||||
});
|
||||
|
||||
// Initialize HTTP Request Handler
|
||||
LOG_INFO(TAG, "Setting up HTTP REST API...");
|
||||
_httpHandler.begin();
|
||||
_httpHandler.setCommandHandlerReference(&_commandHandler);
|
||||
LOG_INFO(TAG, "✅ HTTP REST API initialized");
|
||||
|
||||
// Initialize Settings Web Server
|
||||
LOG_INFO(TAG, "Setting up Settings Web Server...");
|
||||
_settingsServer.begin();
|
||||
LOG_INFO(TAG, "✅ Settings Web Server initialized at /settings");
|
||||
|
||||
// Initialize UART Command Handler
|
||||
LOG_INFO(TAG, "Setting up UART Command Handler...");
|
||||
_uartHandler.begin();
|
||||
_uartHandler.setCallback([this](JsonDocument& message) {
|
||||
onUartMessage(message);
|
||||
});
|
||||
LOG_INFO(TAG, "✅ UART Command Handler initialized (TX: GPIO12, RX: GPIO13)");
|
||||
|
||||
LOG_INFO(TAG, "Communication Router initialized with modular architecture");
|
||||
LOG_INFO(TAG, " • MQTT: AsyncMqttClient");
|
||||
LOG_INFO(TAG, " • WebSocket: Multi-client support");
|
||||
LOG_INFO(TAG, " • HTTP REST API: /api endpoints");
|
||||
LOG_INFO(TAG, " • UART: External device control");
|
||||
LOG_INFO(TAG, " • Settings Page: /settings");
|
||||
}
|
||||
|
||||
void CommunicationRouter::loop() {
|
||||
// Process UART incoming data
|
||||
_uartHandler.loop();
|
||||
}
|
||||
|
||||
void CommunicationRouter::setPlayerReference(Player* player) {
|
||||
_player = player;
|
||||
_commandHandler.setPlayerReference(player);
|
||||
}
|
||||
|
||||
void CommunicationRouter::setFileManagerReference(FileManager* fm) {
|
||||
_fileManager = fm;
|
||||
_commandHandler.setFileManagerReference(fm);
|
||||
|
||||
// Register SD log channel now that FileManager is available
|
||||
if (fm != nullptr) {
|
||||
Logging::setSdWriteCallback([fm](const String& line) {
|
||||
fm->appendLine("/logs/vesper.log", line);
|
||||
});
|
||||
LOG_INFO(TAG, "SD log channel registered -> /logs/vesper.log");
|
||||
}
|
||||
}
|
||||
|
||||
void CommunicationRouter::setTimeKeeperReference(Timekeeper* tk) {
|
||||
_timeKeeper = tk;
|
||||
_commandHandler.setTimeKeeperReference(tk);
|
||||
}
|
||||
|
||||
void CommunicationRouter::setFirmwareValidatorReference(FirmwareValidator* fv) {
|
||||
_firmwareValidator = fv;
|
||||
_commandHandler.setFirmwareValidatorReference(fv);
|
||||
}
|
||||
|
||||
void CommunicationRouter::setTelemetryReference(Telemetry* telemetry) {
|
||||
_commandHandler.setTelemetryReference(telemetry);
|
||||
}
|
||||
|
||||
void CommunicationRouter::setupUdpDiscovery() {
|
||||
uint16_t discoveryPort = _configManager.getNetworkConfig().discoveryPort;
|
||||
if (_udp.listen(discoveryPort)) {
|
||||
LOG_INFO(TAG, "UDP discovery listening on port %u", discoveryPort);
|
||||
|
||||
_udp.onPacket([this](AsyncUDPPacket packet) {
|
||||
String msg = String((const char*)packet.data(), packet.length());
|
||||
LOG_DEBUG(TAG, "UDP from %s:%u -> %s",
|
||||
packet.remoteIP().toString().c_str(),
|
||||
packet.remotePort(),
|
||||
msg.c_str());
|
||||
|
||||
bool shouldReply = false;
|
||||
|
||||
if (msg.indexOf("discover") >= 0) {
|
||||
shouldReply = true;
|
||||
} else {
|
||||
StaticJsonDocument<128> req;
|
||||
DeserializationError err = deserializeJson(req, msg);
|
||||
if (!err) {
|
||||
shouldReply = (req["op"] == "discover");
|
||||
}
|
||||
}
|
||||
|
||||
if (!shouldReply) return;
|
||||
|
||||
StaticJsonDocument<256> doc;
|
||||
doc["op"] = "discover_reply";
|
||||
doc["svc"] = "vesper";
|
||||
doc["ver"] = 1;
|
||||
|
||||
doc["name"] = "Proj. Vesper v2.0";
|
||||
doc["id"] = _configManager.getDeviceUID();
|
||||
doc["ip"] = _networking.getLocalIP();
|
||||
char wsUrl[64];
|
||||
snprintf(wsUrl, sizeof(wsUrl), "ws://%s:80/ws", _networking.getLocalIP().c_str());
|
||||
doc["ws"] = wsUrl;
|
||||
doc["port"] = 80;
|
||||
doc["fw"] = "2.0";
|
||||
doc["clients"] = _clientManager.getClientCount();
|
||||
|
||||
String out;
|
||||
serializeJson(doc, out);
|
||||
|
||||
_udp.writeTo((const uint8_t*)out.c_str(), out.length(),
|
||||
packet.remoteIP(), packet.remotePort());
|
||||
});
|
||||
} else {
|
||||
LOG_ERROR(TAG, "Failed to start UDP discovery.");
|
||||
}
|
||||
}
|
||||
|
||||
bool CommunicationRouter::isMqttConnected() const {
|
||||
return _mqttClient.isConnected();
|
||||
}
|
||||
|
||||
bool CommunicationRouter::hasActiveWebSocketClients() const {
|
||||
return _wsServer.hasClients();
|
||||
}
|
||||
|
||||
size_t CommunicationRouter::getWebSocketClientCount() const {
|
||||
return _wsServer.getClientCount();
|
||||
}
|
||||
|
||||
bool CommunicationRouter::isHealthy() const {
|
||||
// Check if required references are set
|
||||
if (!_player || !_fileManager || !_timeKeeper) {
|
||||
LOG_WARNING(TAG, "Unhealthy - missing subsystem references (player=%d fileManager=%d timeKeeper=%d)",
|
||||
_player != nullptr, _fileManager != nullptr, _timeKeeper != nullptr);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check network connectivity first — no point checking connections without a network
|
||||
if (!_networking.isConnected()) {
|
||||
LOG_WARNING(TAG, "Unhealthy - no network connection");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if at least one protocol is connected
|
||||
if (!isMqttConnected() && !hasActiveWebSocketClients()) {
|
||||
LOG_WARNING(TAG, "Unhealthy - no active connections (MQTT=%d, WebSocket=%d)",
|
||||
isMqttConnected(), hasActiveWebSocketClients());
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void CommunicationRouter::broadcastStatus(const String& statusMessage) {
|
||||
publishToMqtt(statusMessage);
|
||||
_wsServer.broadcastToAll(statusMessage);
|
||||
}
|
||||
|
||||
void CommunicationRouter::broadcastStatus(const JsonDocument& statusJson) {
|
||||
String statusMessage;
|
||||
serializeJson(statusJson, statusMessage);
|
||||
broadcastStatus(statusMessage);
|
||||
}
|
||||
|
||||
void CommunicationRouter::broadcastToMasterClients(const String& message) {
|
||||
_wsServer.broadcastToMaster(message);
|
||||
}
|
||||
|
||||
void CommunicationRouter::broadcastToSecondaryClients(const String& message) {
|
||||
_wsServer.broadcastToSecondary(message);
|
||||
}
|
||||
|
||||
void CommunicationRouter::broadcastToAllWebSocketClients(const String& message) {
|
||||
_wsServer.broadcastToAll(message);
|
||||
}
|
||||
|
||||
void CommunicationRouter::broadcastToAllWebSocketClients(const JsonDocument& message) {
|
||||
String messageStr;
|
||||
serializeJson(message, messageStr);
|
||||
_wsServer.broadcastToAll(messageStr);
|
||||
}
|
||||
|
||||
void CommunicationRouter::publishToMqtt(const String& data) {
|
||||
if (_mqttClient.isConnected()) {
|
||||
_mqttClient.publish("data", data, 0, false);
|
||||
LOG_DEBUG(TAG, "Published to MQTT: %s", data.c_str());
|
||||
} else {
|
||||
LOG_ERROR(TAG, "MQTT Not Connected! Message Failed: %s", data.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
void CommunicationRouter::sendBellOverloadNotification(const std::vector<uint8_t>& bellNumbers,
|
||||
const std::vector<uint16_t>& bellLoads,
|
||||
const String& severity) {
|
||||
StaticJsonDocument<512> overloadMsg;
|
||||
overloadMsg["status"] = "INFO";
|
||||
overloadMsg["type"] = "bell_overload";
|
||||
|
||||
JsonArray bellsArray = overloadMsg["payload"]["bells"].to<JsonArray>();
|
||||
JsonArray loadsArray = overloadMsg["payload"]["loads"].to<JsonArray>();
|
||||
|
||||
for (size_t i = 0; i < bellNumbers.size() && i < bellLoads.size(); i++) {
|
||||
bellsArray.add(bellNumbers[i] + 1);
|
||||
loadsArray.add(bellLoads[i]);
|
||||
}
|
||||
|
||||
overloadMsg["payload"]["severity"] = severity;
|
||||
broadcastStatus(overloadMsg);
|
||||
|
||||
LOG_WARNING(TAG, "Bell overload notification sent: %d bells, severity: %s",
|
||||
bellNumbers.size(), severity.c_str());
|
||||
}
|
||||
|
||||
void CommunicationRouter::onNetworkConnected() {
|
||||
LOG_DEBUG(TAG, "Network connected - notifying MQTT client");
|
||||
_mqttClient.onNetworkConnected();
|
||||
}
|
||||
|
||||
void CommunicationRouter::onNetworkDisconnected() {
|
||||
LOG_DEBUG(TAG, "Network disconnected - notifying MQTT client");
|
||||
_mqttClient.onNetworkDisconnected();
|
||||
}
|
||||
|
||||
void CommunicationRouter::onMqttMessage(const String& topic, const String& payload) {
|
||||
LOG_DEBUG(TAG, "MQTT message received: %s", payload.c_str());
|
||||
|
||||
// Parse JSON
|
||||
StaticJsonDocument<2048> doc;
|
||||
DeserializationError error = deserializeJson(doc, payload);
|
||||
|
||||
if (error) {
|
||||
LOG_ERROR(TAG, "Failed to parse MQTT JSON: %s", error.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
// Create message context for MQTT
|
||||
CommandHandler::MessageContext context(CommandHandler::MessageSource::MQTT);
|
||||
|
||||
// Forward to command handler
|
||||
_commandHandler.processCommand(doc, context);
|
||||
}
|
||||
|
||||
void CommunicationRouter::onWebSocketMessage(uint32_t clientId, const JsonDocument& message) {
|
||||
// Extract command for logging
|
||||
String cmd = message["cmd"] | "unknown";
|
||||
LOG_INFO(TAG, "📨 WebSocket message from client #%u: cmd=%s", clientId, cmd.c_str());
|
||||
|
||||
// Create message context for WebSocket with client ID
|
||||
CommandHandler::MessageContext context(CommandHandler::MessageSource::WEBSOCKET, clientId);
|
||||
|
||||
// Forward to command handler (need to cast away const for now)
|
||||
JsonDocument& mutableDoc = const_cast<JsonDocument&>(message);
|
||||
_commandHandler.processCommand(mutableDoc, context);
|
||||
|
||||
LOG_DEBUG(TAG, "WebSocket message from client #%u processed", clientId);
|
||||
}
|
||||
|
||||
void CommunicationRouter::onUartMessage(JsonDocument& message) {
|
||||
// Extract command and action for filtering
|
||||
String cmd = message["cmd"] | "";
|
||||
String action = message["contents"]["action"] | "";
|
||||
|
||||
// UART COMMAND WHITELIST: Only allow specific commands
|
||||
// This prevents feedback loops between devices when bad messages occur.
|
||||
// To re-enable full UART command support, remove this filter.
|
||||
bool allowed = false;
|
||||
|
||||
if (cmd == "system_info" && action == "sync_time_to_lcd") {
|
||||
allowed = true;
|
||||
} else if (cmd == "playback" && (action == "play" || action == "stop")) {
|
||||
allowed = true;
|
||||
}
|
||||
|
||||
if (!allowed) {
|
||||
// Silently ignore - do NOT send error response to avoid feedback loop
|
||||
LOG_DEBUG(TAG, "UART: Ignoring non-whitelisted command (cmd=%s, action=%s)",
|
||||
cmd.c_str(), action.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
LOG_INFO(TAG, "🔌 UART command received: cmd=%s, action=%s", cmd.c_str(), action.c_str());
|
||||
|
||||
// Create message context for UART
|
||||
CommandHandler::MessageContext context(CommandHandler::MessageSource::UART);
|
||||
|
||||
// Forward to command handler
|
||||
_commandHandler.processCommand(message, context);
|
||||
|
||||
LOG_DEBUG(TAG, "UART message processed");
|
||||
}
|
||||
|
||||
void CommunicationRouter::sendResponse(const String& response, const CommandHandler::MessageContext& context) {
|
||||
if (context.source == CommandHandler::MessageSource::MQTT) {
|
||||
LOG_DEBUG(TAG, "↗️ Sending response via MQTT: %s", response.c_str());
|
||||
publishToMqtt(response);
|
||||
} else if (context.source == CommandHandler::MessageSource::WEBSOCKET) {
|
||||
LOG_DEBUG(TAG, "↗️ Sending response to WebSocket client #%u: %s", context.clientId, response.c_str());
|
||||
_wsServer.sendToClient(context.clientId, response);
|
||||
} else if (context.source == CommandHandler::MessageSource::UART) {
|
||||
LOG_DEBUG(TAG, "↗️ Sending response via UART: %s", response.c_str());
|
||||
_uartHandler.send(response);
|
||||
} else {
|
||||
LOG_ERROR(TAG, "❌ Unknown message source for response routing!");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* COMMUNICATIONROUTER.HPP - Multi-Protocol Communication Router v4.0
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 📡 THE COMMUNICATION ROUTER OF VESPER 📡
|
||||
*
|
||||
* Routes messages between protocols and command handlers:
|
||||
* • MQTTAsyncClient: AsyncMqttClient for non-blocking MQTT
|
||||
* • WebSocketServer: Multi-client WebSocket management
|
||||
* • CommandHandler: Unified command processing
|
||||
* • ResponseBuilder: Structured response generation
|
||||
*
|
||||
* 🏗️ ARCHITECTURE:
|
||||
* • Message routing between protocols and handlers
|
||||
* • MQTT on dedicated RTOS task (Core 0)
|
||||
* • Unified command processing
|
||||
* • Thread-safe message routing
|
||||
*
|
||||
* 📡 SUPPORTED PROTOCOLS:
|
||||
* • MQTT: AsyncMqttClient for reliable async connectivity
|
||||
* • WebSocket: Real-time multi-client web interface
|
||||
* • UDP Discovery: Auto-discovery service
|
||||
*
|
||||
* 📋 VERSION: 5.0 (AsyncMqttClient)
|
||||
* 📅 DATE: 2025-10-01
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <ESPAsyncWebServer.h>
|
||||
#include <AsyncUDP.h>
|
||||
#include <ArduinoJson.h>
|
||||
#include "../MQTTAsyncClient/MQTTAsyncClient.hpp"
|
||||
#include "../WebSocketServer/WebSocketServer.hpp"
|
||||
#include "../CommandHandler/CommandHandler.hpp"
|
||||
#include "../ResponseBuilder/ResponseBuilder.hpp"
|
||||
#include "../HTTPRequestHandler/HTTPRequestHandler.hpp"
|
||||
#include "../UARTCommandHandler/UARTCommandHandler.hpp"
|
||||
#include "../../ClientManager/ClientManager.hpp"
|
||||
#include "../../SettingsWebServer/SettingsWebServer.hpp"
|
||||
|
||||
class ConfigManager;
|
||||
class OTAManager;
|
||||
class Player;
|
||||
class FileManager;
|
||||
class Timekeeper;
|
||||
class Networking;
|
||||
class FirmwareValidator;
|
||||
class Telemetry;
|
||||
|
||||
class CommunicationRouter {
|
||||
public:
|
||||
explicit CommunicationRouter(ConfigManager& configManager,
|
||||
OTAManager& otaManager,
|
||||
Networking& networking,
|
||||
AsyncWebServer& server,
|
||||
AsyncWebSocket& webSocket,
|
||||
AsyncUDP& udp);
|
||||
|
||||
~CommunicationRouter();
|
||||
|
||||
void begin();
|
||||
void loop(); // Must be called from main loop for UART processing
|
||||
void setPlayerReference(Player* player);
|
||||
void setFileManagerReference(FileManager* fm);
|
||||
void setTimeKeeperReference(Timekeeper* tk);
|
||||
void setFirmwareValidatorReference(FirmwareValidator* fv);
|
||||
void setTelemetryReference(Telemetry* telemetry);
|
||||
void setupUdpDiscovery();
|
||||
|
||||
// Status methods
|
||||
bool isMqttConnected() const;
|
||||
bool hasActiveWebSocketClients() const;
|
||||
size_t getWebSocketClientCount() const;
|
||||
bool isHealthy() const;
|
||||
|
||||
// Component accessors
|
||||
MQTTAsyncClient& getMQTTClient() { return _mqttClient; }
|
||||
UARTCommandHandler& getUARTHandler() { return _uartHandler; }
|
||||
|
||||
// Broadcast methods
|
||||
void broadcastStatus(const String& statusMessage);
|
||||
void broadcastStatus(const JsonDocument& statusJson);
|
||||
void broadcastToMasterClients(const String& message);
|
||||
void broadcastToSecondaryClients(const String& message);
|
||||
void broadcastToAllWebSocketClients(const String& message);
|
||||
void broadcastToAllWebSocketClients(const JsonDocument& message);
|
||||
void publishToMqtt(const String& data);
|
||||
|
||||
// Bell overload notification
|
||||
void sendBellOverloadNotification(const std::vector<uint8_t>& bellNumbers,
|
||||
const std::vector<uint16_t>& bellLoads,
|
||||
const String& severity);
|
||||
|
||||
// Network connection callbacks
|
||||
void onNetworkConnected();
|
||||
void onNetworkDisconnected();
|
||||
|
||||
private:
|
||||
// Dependencies
|
||||
ConfigManager& _configManager;
|
||||
OTAManager& _otaManager;
|
||||
Networking& _networking;
|
||||
AsyncWebServer& _server;
|
||||
AsyncWebSocket& _webSocket;
|
||||
AsyncUDP& _udp;
|
||||
Player* _player;
|
||||
FileManager* _fileManager;
|
||||
Timekeeper* _timeKeeper;
|
||||
FirmwareValidator* _firmwareValidator;
|
||||
|
||||
// Communication subsystems
|
||||
MQTTAsyncClient _mqttClient;
|
||||
ClientManager _clientManager;
|
||||
WebSocketServer _wsServer;
|
||||
CommandHandler _commandHandler;
|
||||
HTTPRequestHandler _httpHandler;
|
||||
UARTCommandHandler _uartHandler;
|
||||
SettingsWebServer _settingsServer;
|
||||
|
||||
// Message handlers
|
||||
void onMqttMessage(const String& topic, const String& payload);
|
||||
void onWebSocketMessage(uint32_t clientId, const JsonDocument& message);
|
||||
void onUartMessage(JsonDocument& message);
|
||||
|
||||
// Response routing
|
||||
void sendResponse(const String& response, const CommandHandler::MessageContext& context);
|
||||
};
|
||||
@@ -0,0 +1,189 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* HTTPREQUESTHANDLER.CPP - HTTP REST API Request Handler Implementation
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#include "HTTPRequestHandler.hpp"
|
||||
|
||||
#define TAG "HTTPHandler"
|
||||
#include "../CommandHandler/CommandHandler.hpp"
|
||||
#include "../../ConfigManager/ConfigManager.hpp"
|
||||
#include "../../Logging/Logging.hpp"
|
||||
|
||||
HTTPRequestHandler::HTTPRequestHandler(AsyncWebServer& server,
|
||||
ConfigManager& configManager)
|
||||
: _server(server)
|
||||
, _configManager(configManager)
|
||||
, _commandHandler(nullptr) {
|
||||
}
|
||||
|
||||
HTTPRequestHandler::~HTTPRequestHandler() {
|
||||
}
|
||||
|
||||
void HTTPRequestHandler::begin() {
|
||||
LOG_INFO(TAG, "HTTPRequestHandler - Initializing HTTP REST API endpoints");
|
||||
|
||||
// POST /api/command - Execute any command
|
||||
_server.on("/api/command", HTTP_POST,
|
||||
[](AsyncWebServerRequest* request) {
|
||||
// This is called when request is complete but body is empty
|
||||
request->send(400, "application/json", "{\"error\":\"No body provided\"}");
|
||||
},
|
||||
nullptr, // No file upload handler
|
||||
[this](AsyncWebServerRequest* request, uint8_t* data, size_t len, size_t index, size_t total) {
|
||||
// This is called for body data
|
||||
if (index == 0) {
|
||||
// First chunk - could allocate buffers if needed
|
||||
}
|
||||
|
||||
if (index + len == total) {
|
||||
// Last chunk - process the complete request
|
||||
handleCommandRequest(request, data, len);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// GET /api/status - Get system status
|
||||
_server.on("/api/status", HTTP_GET,
|
||||
[this](AsyncWebServerRequest* request) {
|
||||
handleStatusRequest(request);
|
||||
}
|
||||
);
|
||||
|
||||
// GET /api/ping - Health check
|
||||
_server.on("/api/ping", HTTP_GET,
|
||||
[this](AsyncWebServerRequest* request) {
|
||||
handlePingRequest(request);
|
||||
}
|
||||
);
|
||||
|
||||
// Enable CORS for API endpoints (allows web apps to call the API)
|
||||
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*");
|
||||
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
||||
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Headers", "Content-Type");
|
||||
|
||||
LOG_INFO(TAG, "HTTPRequestHandler - REST API endpoints registered");
|
||||
LOG_INFO(TAG, " POST /api/command - Execute commands");
|
||||
LOG_INFO(TAG, " GET /api/status - System status");
|
||||
LOG_INFO(TAG, " GET /api/ping - Health check");
|
||||
}
|
||||
|
||||
void HTTPRequestHandler::setCommandHandlerReference(CommandHandler* handler) {
|
||||
_commandHandler = handler;
|
||||
LOG_DEBUG(TAG, "HTTPRequestHandler - CommandHandler reference set");
|
||||
}
|
||||
|
||||
bool HTTPRequestHandler::isHealthy() const {
|
||||
// HTTP handler is healthy if it has been initialized with dependencies
|
||||
return _commandHandler != nullptr;
|
||||
}
|
||||
|
||||
void HTTPRequestHandler::handleCommandRequest(AsyncWebServerRequest* request, uint8_t* data, size_t len) {
|
||||
if (!_commandHandler) {
|
||||
sendErrorResponse(request, 503, "Command handler not initialized");
|
||||
return;
|
||||
}
|
||||
|
||||
// Parse JSON from body
|
||||
JsonDocument doc;
|
||||
DeserializationError error = deserializeJson(doc, data, len);
|
||||
|
||||
if (error) {
|
||||
LOG_WARNING(TAG, "HTTPRequestHandler - JSON parse error: %s", error.c_str());
|
||||
sendErrorResponse(request, 400, "Invalid JSON");
|
||||
return;
|
||||
}
|
||||
|
||||
LOG_DEBUG(TAG, "HTTPRequestHandler - Processing command via HTTP");
|
||||
|
||||
// Create message context for HTTP (treat as WebSocket with special ID)
|
||||
CommandHandler::MessageContext context(CommandHandler::MessageSource::WEBSOCKET, 0xFFFFFFFF);
|
||||
|
||||
// Capture request pointer for response
|
||||
AsyncWebServerRequest* capturedRequest = request;
|
||||
bool responseSent = false;
|
||||
|
||||
// Set temporary response callback to capture the response
|
||||
auto originalCallback = [capturedRequest, &responseSent](const String& response, const CommandHandler::MessageContext& ctx) {
|
||||
if (!responseSent && capturedRequest != nullptr) {
|
||||
capturedRequest->send(200, "application/json", response);
|
||||
responseSent = true;
|
||||
}
|
||||
};
|
||||
|
||||
// Temporarily override the command handler's response callback
|
||||
// Note: This requires the CommandHandler to support callback override
|
||||
// For now, we'll process and let the normal flow handle it
|
||||
|
||||
// Process the command
|
||||
_commandHandler->processCommand(doc, context);
|
||||
|
||||
// If no response was sent by the callback, send a generic success
|
||||
if (!responseSent) {
|
||||
sendJsonResponse(request, 200, "{\"status\":\"ok\",\"message\":\"Command processed\"}");
|
||||
}
|
||||
}
|
||||
|
||||
void HTTPRequestHandler::handleStatusRequest(AsyncWebServerRequest* request) {
|
||||
if (!_commandHandler) {
|
||||
sendErrorResponse(request, 503, "Command handler not initialized");
|
||||
return;
|
||||
}
|
||||
|
||||
LOG_DEBUG(TAG, "HTTPRequestHandler - Status request via HTTP");
|
||||
|
||||
// Create a status command
|
||||
JsonDocument doc;
|
||||
doc["group"] = "system";
|
||||
doc["action"] = "status";
|
||||
|
||||
// Create message context
|
||||
CommandHandler::MessageContext context(CommandHandler::MessageSource::WEBSOCKET, 0xFFFFFFFF);
|
||||
|
||||
// Capture request for response
|
||||
AsyncWebServerRequest* capturedRequest = request;
|
||||
bool responseSent = false;
|
||||
|
||||
// Process via command handler
|
||||
_commandHandler->processCommand(doc, context);
|
||||
|
||||
// Fallback response if needed
|
||||
if (!responseSent) {
|
||||
JsonDocument response;
|
||||
response["status"] = "ok";
|
||||
response["device_uid"] = _configManager.getDeviceUID();
|
||||
response["fw_version"] = _configManager.getFwVersion();
|
||||
|
||||
String output;
|
||||
serializeJson(response, output);
|
||||
sendJsonResponse(request, 200, output);
|
||||
}
|
||||
}
|
||||
|
||||
void HTTPRequestHandler::handlePingRequest(AsyncWebServerRequest* request) {
|
||||
LOG_DEBUG(TAG, "HTTPRequestHandler - Ping request via HTTP");
|
||||
|
||||
JsonDocument response;
|
||||
response["status"] = "ok";
|
||||
response["message"] = "pong";
|
||||
response["uptime"] = millis();
|
||||
|
||||
String output;
|
||||
serializeJson(response, output);
|
||||
sendJsonResponse(request, 200, output);
|
||||
}
|
||||
|
||||
void HTTPRequestHandler::sendJsonResponse(AsyncWebServerRequest* request, int code, const String& json) {
|
||||
request->send(code, "application/json", json);
|
||||
}
|
||||
|
||||
void HTTPRequestHandler::sendErrorResponse(AsyncWebServerRequest* request, int code, const String& error) {
|
||||
JsonDocument doc;
|
||||
doc["status"] = "error";
|
||||
doc["error"] = error;
|
||||
|
||||
String output;
|
||||
serializeJson(doc, output);
|
||||
sendJsonResponse(request, code, output);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* HTTPREQUESTHANDLER.HPP - HTTP REST API Request Handler
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 📡 HTTP REQUEST HANDLER FOR VESPER 📡
|
||||
*
|
||||
* Provides HTTP REST API endpoints alongside WebSocket/MQTT:
|
||||
* • Operates side-by-side with WebSocket (not as fallback)
|
||||
* • Same command structure as MQTT/WebSocket
|
||||
* • Reliable request-response pattern
|
||||
* • Works in both STA and AP modes
|
||||
*
|
||||
* 🏗️ ARCHITECTURE:
|
||||
* • Uses AsyncWebServer for non-blocking operation
|
||||
* • Routes HTTP POST requests to CommandHandler
|
||||
* • Returns JSON responses
|
||||
* • Thread-safe operation
|
||||
*
|
||||
* 📡 API ENDPOINTS:
|
||||
* POST /api/command - Execute any VESPER command
|
||||
* GET /api/status - Get system status
|
||||
* GET /api/ping - Health check
|
||||
*
|
||||
* 📋 VERSION: 1.0
|
||||
* 📅 DATE: 2025-12-28
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <ESPAsyncWebServer.h>
|
||||
#include <ArduinoJson.h>
|
||||
|
||||
// Forward declarations
|
||||
class CommandHandler;
|
||||
class ConfigManager;
|
||||
|
||||
class HTTPRequestHandler {
|
||||
public:
|
||||
explicit HTTPRequestHandler(AsyncWebServer& server,
|
||||
ConfigManager& configManager);
|
||||
~HTTPRequestHandler();
|
||||
|
||||
/**
|
||||
* @brief Initialize HTTP request handler and register endpoints
|
||||
*/
|
||||
void begin();
|
||||
|
||||
/**
|
||||
* @brief Set CommandHandler reference for processing commands
|
||||
*/
|
||||
void setCommandHandlerReference(CommandHandler* handler);
|
||||
|
||||
/**
|
||||
* @brief Check if HTTP handler is healthy
|
||||
*/
|
||||
bool isHealthy() const;
|
||||
|
||||
private:
|
||||
// Dependencies
|
||||
AsyncWebServer& _server;
|
||||
ConfigManager& _configManager;
|
||||
CommandHandler* _commandHandler;
|
||||
|
||||
// Endpoint handlers
|
||||
void handleCommandRequest(AsyncWebServerRequest* request, uint8_t* data, size_t len);
|
||||
void handleStatusRequest(AsyncWebServerRequest* request);
|
||||
void handlePingRequest(AsyncWebServerRequest* request);
|
||||
|
||||
// Helper methods
|
||||
void sendJsonResponse(AsyncWebServerRequest* request, int code, const String& json);
|
||||
void sendErrorResponse(AsyncWebServerRequest* request, int code, const String& error);
|
||||
};
|
||||
@@ -0,0 +1,476 @@
|
||||
/*
|
||||
* MQTTASYNCCLIENT.CPP - MQTT Client Implementation with AsyncMqttClient
|
||||
*/
|
||||
|
||||
#include "MQTTAsyncClient.hpp"
|
||||
|
||||
#define TAG "MQTTClient"
|
||||
#include "../../ConfigManager/ConfigManager.hpp"
|
||||
#include "../../Networking/Networking.hpp"
|
||||
#include "../../Logging/Logging.hpp"
|
||||
|
||||
MQTTAsyncClient* MQTTAsyncClient::_instance = nullptr;
|
||||
|
||||
MQTTAsyncClient::MQTTAsyncClient(ConfigManager& configManager, Networking& networking)
|
||||
: _configManager(configManager)
|
||||
, _networking(networking)
|
||||
, _messageCallback(nullptr)
|
||||
, _mqttReconnectTimer(nullptr)
|
||||
, _networkStabilizationTimer(nullptr)
|
||||
, _heartbeatTimer(nullptr)
|
||||
, _heartbeatTaskHandle(nullptr)
|
||||
, _reconnectAttempts(0)
|
||||
, _lastConnectionAttempt(0) {
|
||||
|
||||
_instance = this; // Set static instance pointer
|
||||
|
||||
// Create reconnection timer (initial delay will be calculated dynamically)
|
||||
_mqttReconnectTimer = xTimerCreate(
|
||||
"mqttReconnect", // Timer name (for debugging)
|
||||
pdMS_TO_TICKS(MQTT_RECONNECT_BASE_DELAY), // Initial period: 5000ms = 5 seconds
|
||||
pdFALSE, // One-shot (false) or Auto-reload (true)
|
||||
(void*)0, // Timer ID (can store data)
|
||||
mqttReconnectTimerCallback // Callback function when timer expires
|
||||
);
|
||||
|
||||
// Create network stabilization timer (one-shot, 2 seconds)
|
||||
_networkStabilizationTimer = xTimerCreate(
|
||||
"mqttNetStable", // Timer name
|
||||
pdMS_TO_TICKS(NETWORK_STABILIZATION_DELAY), // Period: 2000ms = 2 seconds
|
||||
pdFALSE, // One-shot timer
|
||||
(void*)0, // Timer ID
|
||||
networkStabilizationTimerCallback // Callback function
|
||||
);
|
||||
|
||||
// Create heartbeat timer (auto-reload every 30 seconds)
|
||||
_heartbeatTimer = xTimerCreate(
|
||||
"mqttHeartbeat", // Timer name
|
||||
pdMS_TO_TICKS(HEARTBEAT_INTERVAL), // Period: 30000ms = 30 seconds
|
||||
pdTRUE, // Auto-reload (true) - repeating timer
|
||||
(void*)0, // Timer ID
|
||||
heartbeatTimerCallback // Callback function
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
MQTTAsyncClient::~MQTTAsyncClient() {
|
||||
if (_mqttReconnectTimer) {
|
||||
xTimerDelete(_mqttReconnectTimer, portMAX_DELAY);
|
||||
}
|
||||
if (_networkStabilizationTimer) {
|
||||
xTimerStop(_networkStabilizationTimer, 0);
|
||||
xTimerDelete(_networkStabilizationTimer, portMAX_DELAY);
|
||||
}
|
||||
if (_heartbeatTimer) {
|
||||
xTimerStop(_heartbeatTimer, 0);
|
||||
xTimerDelete(_heartbeatTimer, portMAX_DELAY);
|
||||
}
|
||||
_mqttClient.disconnect();
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::begin() {
|
||||
LOG_INFO(TAG, "Initializing MQTT Async Client");
|
||||
|
||||
auto& mqttConfig = _configManager.getMqttConfig();
|
||||
|
||||
// Build topic strings (cache for performance)
|
||||
String deviceUID = _configManager.getDeviceUID();
|
||||
_controlTopic = "vesper/" + deviceUID + "/control";
|
||||
_dataTopic = "vesper/" + deviceUID + "/data";
|
||||
_clientId = "vesper-" + deviceUID;
|
||||
|
||||
LOG_INFO(TAG, "MQTT Topics: control=%s, data=%s", _controlTopic.c_str(), _dataTopic.c_str());
|
||||
|
||||
// Setup event handlers
|
||||
_mqttClient.onConnect([this](bool sessionPresent) {
|
||||
this->onMqttConnect(sessionPresent);
|
||||
});
|
||||
|
||||
_mqttClient.onDisconnect([this](AsyncMqttClientDisconnectReason reason) {
|
||||
this->onMqttDisconnect(reason);
|
||||
});
|
||||
|
||||
_mqttClient.onSubscribe([this](uint16_t packetId, uint8_t qos) {
|
||||
this->onMqttSubscribe(packetId, qos);
|
||||
});
|
||||
|
||||
_mqttClient.onUnsubscribe([this](uint16_t packetId) {
|
||||
this->onMqttUnsubscribe(packetId);
|
||||
});
|
||||
|
||||
_mqttClient.onMessage([this](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
|
||||
this->onMqttMessage(topic, payload, properties, len, index, total);
|
||||
});
|
||||
|
||||
_mqttClient.onPublish([this](uint16_t packetId) {
|
||||
this->onMqttPublish(packetId);
|
||||
});
|
||||
|
||||
// Configure connection
|
||||
_mqttClient.setServer(mqttConfig.host, mqttConfig.port);
|
||||
_mqttClient.setCredentials(mqttConfig.user.c_str(), mqttConfig.password.c_str());
|
||||
_mqttClient.setClientId(_clientId.c_str()); // Use member variable
|
||||
_mqttClient.setKeepAlive(15);
|
||||
_mqttClient.setCleanSession(true);
|
||||
|
||||
LOG_INFO(TAG, "✅ MQTT Async Client initialized");
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::connect() {
|
||||
auto& mqttConfig = _configManager.getMqttConfig();
|
||||
|
||||
// 🔥 Check if MQTT is enabled
|
||||
if (!mqttConfig.enabled) {
|
||||
LOG_DEBUG(TAG, "MQTT is disabled in configuration - skipping connection");
|
||||
return;
|
||||
}
|
||||
|
||||
if (_mqttClient.connected()) {
|
||||
LOG_DEBUG(TAG, "Already connected to MQTT");
|
||||
return;
|
||||
}
|
||||
|
||||
// Track connection attempt
|
||||
_lastConnectionAttempt = millis();
|
||||
|
||||
LOG_INFO(TAG, "Free heap BEFORE MQTT connect: %d bytes", ESP.getFreeHeap());
|
||||
|
||||
_mqttClient.connect();
|
||||
|
||||
LOG_INFO(TAG, "MQTT connect() called - waiting for async connection...");
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::disconnect() {
|
||||
_mqttClient.disconnect();
|
||||
LOG_INFO(TAG, "Disconnected from MQTT broker");
|
||||
}
|
||||
|
||||
uint16_t MQTTAsyncClient::publish(const String& topic, const String& payload, int qos, bool retain) {
|
||||
// Check if connected before attempting to publish
|
||||
if (!_mqttClient.connected()) {
|
||||
// Don't log error here - would cause infinite loop with MQTT logging
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Build full topic (if relative)
|
||||
String fullTopic = topic.startsWith("vesper/") ? topic : _dataTopic;
|
||||
|
||||
uint16_t packetId = _mqttClient.publish(fullTopic.c_str(), qos, retain, payload.c_str());
|
||||
|
||||
if (packetId > 0) {
|
||||
LOG_DEBUG(TAG, "Published to %s: %s (packetId=%d)", fullTopic.c_str(), payload.c_str(), packetId);
|
||||
}
|
||||
// REMOVED: Error logging here to prevent infinite recursion with MQTT logs
|
||||
|
||||
return packetId;
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::setCallback(MessageCallback callback) {
|
||||
_messageCallback = callback;
|
||||
}
|
||||
|
||||
bool MQTTAsyncClient::isConnected() const {
|
||||
return _mqttClient.connected();
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::onNetworkConnected() {
|
||||
auto& mqttConfig = _configManager.getMqttConfig();
|
||||
|
||||
// 🔥 Only attempt connection if MQTT is enabled
|
||||
if (!mqttConfig.enabled) {
|
||||
LOG_DEBUG(TAG, "Network connected but MQTT is disabled - skipping MQTT connection");
|
||||
return;
|
||||
}
|
||||
|
||||
LOG_DEBUG(TAG, "Network connected - scheduling MQTT connection after 2s stabilization (non-blocking)");
|
||||
|
||||
// Reset reconnect attempts on fresh network connection
|
||||
_reconnectAttempts = 0;
|
||||
|
||||
// 🔥 CRITICAL FIX: Use non-blocking timer instead of delay()
|
||||
// This prevents blocking UDP discovery, WebSocket connections, and async operations
|
||||
if (_networkStabilizationTimer) {
|
||||
xTimerStart(_networkStabilizationTimer, 0);
|
||||
} else {
|
||||
LOG_ERROR(TAG, "Network stabilization timer not initialized!");
|
||||
// Fallback to immediate connection (better than blocking)
|
||||
connect();
|
||||
}
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::onNetworkDisconnected() {
|
||||
LOG_DEBUG(TAG, "Network disconnected - MQTT will auto-reconnect when network returns");
|
||||
|
||||
if (_mqttClient.connected()) {
|
||||
_mqttClient.disconnect(true);
|
||||
}
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::subscribe() {
|
||||
uint16_t packetId = _mqttClient.subscribe(_controlTopic.c_str(), 0);
|
||||
LOG_INFO(TAG, "📬 Subscribing to control topic: %s (packetId=%d)", _controlTopic.c_str(), packetId);
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::onMqttConnect(bool sessionPresent) {
|
||||
LOG_INFO(TAG, "✅ Connected to MQTT broker (session present: %s)", sessionPresent ? "yes" : "no");
|
||||
LOG_INFO(TAG, "🔍 Free heap AFTER MQTT connect: %d bytes", ESP.getFreeHeap());
|
||||
|
||||
// Reset reconnection attempts on successful connection
|
||||
_reconnectAttempts = 0;
|
||||
|
||||
// Subscribe to control topic
|
||||
subscribe();
|
||||
|
||||
// 🔥 Start heartbeat timer
|
||||
startHeartbeat();
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
|
||||
auto& mqttConfig = _configManager.getMqttConfig();
|
||||
|
||||
const char* reasonStr;
|
||||
switch(reason) {
|
||||
case AsyncMqttClientDisconnectReason::TCP_DISCONNECTED:
|
||||
reasonStr = "TCP disconnected";
|
||||
break;
|
||||
case AsyncMqttClientDisconnectReason::MQTT_UNACCEPTABLE_PROTOCOL_VERSION:
|
||||
reasonStr = "Unacceptable protocol version";
|
||||
break;
|
||||
case AsyncMqttClientDisconnectReason::MQTT_IDENTIFIER_REJECTED:
|
||||
reasonStr = "Identifier rejected";
|
||||
break;
|
||||
case AsyncMqttClientDisconnectReason::MQTT_SERVER_UNAVAILABLE:
|
||||
reasonStr = "Server unavailable";
|
||||
break;
|
||||
case AsyncMqttClientDisconnectReason::MQTT_MALFORMED_CREDENTIALS:
|
||||
reasonStr = "Malformed credentials";
|
||||
break;
|
||||
case AsyncMqttClientDisconnectReason::MQTT_NOT_AUTHORIZED:
|
||||
reasonStr = "Not authorized";
|
||||
break;
|
||||
default:
|
||||
reasonStr = "Unknown";
|
||||
break;
|
||||
}
|
||||
|
||||
LOG_ERROR(TAG, "❌ Disconnected from MQTT broker - Reason: %s (%d)", reasonStr, static_cast<int>(reason));
|
||||
|
||||
// Stop heartbeat timer when disconnected
|
||||
stopHeartbeat();
|
||||
|
||||
// 🔥 Don't attempt reconnection if MQTT is disabled
|
||||
if (!mqttConfig.enabled) {
|
||||
LOG_INFO(TAG, "MQTT is disabled - not attempting reconnection");
|
||||
return;
|
||||
}
|
||||
|
||||
if (_networking.isConnected()) {
|
||||
// Increment reconnection attempts
|
||||
_reconnectAttempts++;
|
||||
|
||||
// Calculate backoff delay
|
||||
unsigned long reconnectDelay = getReconnectDelay();
|
||||
|
||||
LOG_INFO(TAG, "Network still connected - scheduling MQTT reconnection #%d in %lu seconds (backoff active)",
|
||||
_reconnectAttempts, reconnectDelay / 1000);
|
||||
|
||||
// Update timer period with new delay
|
||||
xTimerChangePeriod(_mqttReconnectTimer, pdMS_TO_TICKS(reconnectDelay), 0);
|
||||
xTimerStart(_mqttReconnectTimer, 0);
|
||||
} else {
|
||||
LOG_INFO(TAG, "Network is down - waiting for network to reconnect");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::onMqttSubscribe(uint16_t packetId, uint8_t qos) {
|
||||
LOG_INFO(TAG, "✅ Subscribed to topic (packetId=%d, QoS=%d)", packetId, qos);
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::onMqttUnsubscribe(uint16_t packetId) {
|
||||
LOG_DEBUG(TAG, "Unsubscribed from topic (packetId=%d)", packetId);
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
|
||||
// Convert to String
|
||||
String topicStr = String(topic);
|
||||
String payloadStr = String(payload).substring(0, len);
|
||||
|
||||
LOG_DEBUG(TAG, "MQTT message received - topic: %s, payload: %s", topicStr.c_str(), payloadStr.c_str());
|
||||
|
||||
// Call user callback
|
||||
if (_messageCallback) {
|
||||
_messageCallback(topicStr, payloadStr);
|
||||
}
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::onMqttPublish(uint16_t packetId) {
|
||||
LOG_DEBUG(TAG, "MQTT publish acknowledged (packetId=%d)", packetId);
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::attemptReconnection() {
|
||||
// Double-check network is still up
|
||||
if (_networking.isConnected()) {
|
||||
LOG_INFO(TAG, "Attempting MQTT reconnection...");
|
||||
connect();
|
||||
} else {
|
||||
LOG_WARNING(TAG, "Network down during reconnect attempt - aborting");
|
||||
}
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::mqttReconnectTaskFn(void* param) {
|
||||
MQTTAsyncClient* client = static_cast<MQTTAsyncClient*>(param);
|
||||
client->attemptReconnection();
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::mqttReconnectTimerCallback(TimerHandle_t xTimer) {
|
||||
if (MQTTAsyncClient::_instance) {
|
||||
xTaskCreate(mqttReconnectTaskFn, "mqttRecon", 3072, MQTTAsyncClient::_instance, 5, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// HEARTBEAT FUNCTIONALITY
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void MQTTAsyncClient::startHeartbeat() {
|
||||
if (_heartbeatTimer) {
|
||||
LOG_INFO(TAG, "💓 Starting MQTT heartbeat (every %d seconds)", HEARTBEAT_INTERVAL / 1000);
|
||||
|
||||
// Publish first heartbeat immediately
|
||||
publishHeartbeat();
|
||||
|
||||
// Start periodic timer
|
||||
xTimerStart(_heartbeatTimer, 0);
|
||||
}
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::stopHeartbeat() {
|
||||
if (_heartbeatTimer) {
|
||||
xTimerStop(_heartbeatTimer, 0);
|
||||
_heartbeatTaskHandle = nullptr;
|
||||
LOG_INFO(TAG, "❤️ Stopped MQTT heartbeat");
|
||||
}
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::publishHeartbeat() {
|
||||
if (!_mqttClient.connected()) {
|
||||
LOG_WARNING(TAG, "⚠️ Cannot publish heartbeat - MQTT not connected");
|
||||
return;
|
||||
}
|
||||
|
||||
// Build heartbeat JSON message
|
||||
StaticJsonDocument<512> doc;
|
||||
doc["status"] = "INFO";
|
||||
doc["type"] = "heartbeat";
|
||||
|
||||
JsonObject payload = doc.createNestedObject("payload");
|
||||
|
||||
// Device ID from NVS
|
||||
payload["device_id"] = _configManager.getDeviceUID();
|
||||
|
||||
// Firmware version
|
||||
payload["firmware_version"] = _configManager.getFwVersion();
|
||||
|
||||
// Current date/time (from TimeKeeper if available, else uptime-based)
|
||||
// For now, we'll use a simple timestamp format
|
||||
unsigned long uptimeMs = millis();
|
||||
unsigned long uptimeSec = uptimeMs / 1000;
|
||||
unsigned long hours = uptimeSec / 3600;
|
||||
unsigned long minutes = (uptimeSec % 3600) / 60;
|
||||
unsigned long seconds = uptimeSec % 60;
|
||||
|
||||
char timestampStr[64];
|
||||
snprintf(timestampStr, sizeof(timestampStr), "Uptime: %luh %lum %lus", hours, minutes, seconds);
|
||||
payload["timestamp"] = timestampStr;
|
||||
|
||||
// IP address
|
||||
payload["ip_address"] = _networking.getLocalIP();
|
||||
|
||||
// Gateway address
|
||||
payload["gateway"] = _networking.getGateway();
|
||||
|
||||
// Uptime in milliseconds
|
||||
payload["uptime_ms"] = uptimeMs;
|
||||
|
||||
// Serialize to string
|
||||
String heartbeatMessage;
|
||||
serializeJson(doc, heartbeatMessage);
|
||||
|
||||
// Publish to heartbeat topic with RETAIN flag
|
||||
String heartbeatTopic = "vesper/" + _configManager.getDeviceUID() + "/status/heartbeat";
|
||||
uint16_t packetId = _mqttClient.publish(heartbeatTopic.c_str(), 1, true, heartbeatMessage.c_str());
|
||||
|
||||
if (packetId > 0) {
|
||||
LOG_DEBUG(TAG, "💓 Published heartbeat (retained) - IP: %s, Uptime: %lums",
|
||||
_networking.getLocalIP().c_str(), uptimeMs);
|
||||
} else {
|
||||
LOG_ERROR(TAG, "❌ Failed to publish heartbeat");
|
||||
}
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::mqttHeartbeatTaskFn(void* param) {
|
||||
MQTTAsyncClient* client = static_cast<MQTTAsyncClient*>(param);
|
||||
client->publishHeartbeat();
|
||||
client->_heartbeatTaskHandle = nullptr;
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::heartbeatTimerCallback(TimerHandle_t xTimer) {
|
||||
if (MQTTAsyncClient::_instance) {
|
||||
// Guard: skip if previous heartbeat task is still running
|
||||
if (MQTTAsyncClient::_instance->_heartbeatTaskHandle != nullptr) {
|
||||
return;
|
||||
}
|
||||
xTaskCreate(mqttHeartbeatTaskFn, "mqttHB", 3072, MQTTAsyncClient::_instance, 3,
|
||||
&MQTTAsyncClient::_instance->_heartbeatTaskHandle);
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// NETWORK STABILIZATION - NON-BLOCKING TIMER APPROACH
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void MQTTAsyncClient::connectAfterStabilization() {
|
||||
LOG_DEBUG(TAG, "Network stabilization complete - connecting to MQTT");
|
||||
connect();
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::mqttConnectTaskFn(void* param) {
|
||||
// Runs in its own task so LOG calls don't overflow the Tmr Svc stack
|
||||
MQTTAsyncClient* client = static_cast<MQTTAsyncClient*>(param);
|
||||
client->connectAfterStabilization();
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::networkStabilizationTimerCallback(TimerHandle_t xTimer) {
|
||||
if (MQTTAsyncClient::_instance) {
|
||||
// Defer to a task — timer callbacks run in Tmr Svc (2KB stack), not enough for connect()
|
||||
xTaskCreate(mqttConnectTaskFn, "mqttConnect", 3072, MQTTAsyncClient::_instance, 5, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// EXPONENTIAL BACKOFF CALCULATION
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
unsigned long MQTTAsyncClient::getReconnectDelay() {
|
||||
// First 3 attempts: Quick retries (5 seconds each)
|
||||
if (_reconnectAttempts <= MQTT_MAX_QUICK_RETRIES) {
|
||||
return MQTT_RECONNECT_BASE_DELAY;
|
||||
}
|
||||
|
||||
// After quick retries: Exponential backoff
|
||||
// Formula: base_delay * 2^(attempts - quick_retries)
|
||||
// Examples: 10s, 20s, 40s, 80s, 160s, 300s (capped at 5 minutes)
|
||||
uint8_t backoffPower = _reconnectAttempts - MQTT_MAX_QUICK_RETRIES;
|
||||
unsigned long delay = MQTT_RECONNECT_BASE_DELAY * (1 << backoffPower); // 2^backoffPower
|
||||
|
||||
// Cap at maximum delay (5 minutes)
|
||||
if (delay > MQTT_RECONNECT_MAX_DELAY) {
|
||||
delay = MQTT_RECONNECT_MAX_DELAY;
|
||||
}
|
||||
|
||||
return delay;
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* MQTTASYNCCLIENT.HPP - MQTT Client with AsyncMqttClient
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 🔒 MQTT CONNECTION WITH ASYNC ARCHITECTURE 🔒
|
||||
*
|
||||
* This class manages MQTT connections using AsyncMqttClient library:
|
||||
* • Fully async/non-blocking operation
|
||||
* • No conflicts with AsyncWebServer
|
||||
* • Auto-reconnection built-in
|
||||
* • SSL/TLS support (optional)
|
||||
* • Perfect for Mosquitto broker
|
||||
*
|
||||
* 📋 VERSION: 3.0 (AsyncMqttClient-based)
|
||||
* 📅 DATE: 2025-01-04
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <AsyncMqttClient.h>
|
||||
|
||||
class ConfigManager;
|
||||
class Networking;
|
||||
|
||||
class MQTTAsyncClient {
|
||||
public:
|
||||
static MQTTAsyncClient* _instance;
|
||||
|
||||
// Message callback type
|
||||
using MessageCallback = std::function<void(const String& topic, const String& payload)>;
|
||||
|
||||
explicit MQTTAsyncClient(ConfigManager& configManager, Networking& networking);
|
||||
~MQTTAsyncClient();
|
||||
|
||||
/**
|
||||
* @brief Initialize MQTT client
|
||||
*/
|
||||
void begin();
|
||||
|
||||
/**
|
||||
* @brief Connect to MQTT broker
|
||||
*/
|
||||
void connect();
|
||||
|
||||
/**
|
||||
* @brief Disconnect from MQTT broker
|
||||
*/
|
||||
void disconnect();
|
||||
|
||||
/**
|
||||
* @brief Publish message to MQTT
|
||||
* @param topic Topic to publish to (relative, will prepend "vesper/{deviceID}/")
|
||||
* @param payload Message payload
|
||||
* @param qos QoS level (0, 1, or 2)
|
||||
* @param retain Retain flag
|
||||
* @return Packet ID (0 if failed)
|
||||
*/
|
||||
uint16_t publish(const String& topic, const String& payload, int qos = 0, bool retain = false);
|
||||
|
||||
/**
|
||||
* @brief Set message received callback
|
||||
*/
|
||||
void setCallback(MessageCallback callback);
|
||||
|
||||
/**
|
||||
* @brief Check if connected to MQTT broker
|
||||
*/
|
||||
bool isConnected() const;
|
||||
|
||||
/**
|
||||
* @brief Handle network connection callback
|
||||
*/
|
||||
void onNetworkConnected();
|
||||
|
||||
/**
|
||||
* @brief Handle network disconnection callback
|
||||
*/
|
||||
void onNetworkDisconnected();
|
||||
|
||||
private:
|
||||
ConfigManager& _configManager;
|
||||
Networking& _networking;
|
||||
AsyncMqttClient _mqttClient;
|
||||
MessageCallback _messageCallback;
|
||||
|
||||
|
||||
// Device topic strings (cached for performance)
|
||||
String _controlTopic;
|
||||
String _dataTopic;
|
||||
String _clientId; // Store client ID to keep it alive
|
||||
|
||||
/**
|
||||
* @brief Subscribe to control topic
|
||||
*/
|
||||
void subscribe();
|
||||
|
||||
/**
|
||||
* @brief MQTT event handlers
|
||||
*/
|
||||
void onMqttConnect(bool sessionPresent);
|
||||
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason);
|
||||
void onMqttSubscribe(uint16_t packetId, uint8_t qos);
|
||||
void onMqttUnsubscribe(uint16_t packetId);
|
||||
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total);
|
||||
void onMqttPublish(uint16_t packetId);
|
||||
|
||||
// Reconnection Timer with Exponential Backoff
|
||||
TimerHandle_t _mqttReconnectTimer;
|
||||
static const unsigned long MQTT_RECONNECT_BASE_DELAY = 5000; // 5 seconds base
|
||||
static const unsigned long MQTT_RECONNECT_MAX_DELAY = 300000; // 5 minutes max
|
||||
static const uint8_t MQTT_MAX_QUICK_RETRIES = 3; // Try 3 times quickly
|
||||
uint8_t _reconnectAttempts; // Track failed attempts
|
||||
unsigned long _lastConnectionAttempt; // Track last attempt time
|
||||
void attemptReconnection();
|
||||
static void mqttReconnectTimerCallback(TimerHandle_t xTimer);
|
||||
static void mqttReconnectTaskFn(void* param);
|
||||
unsigned long getReconnectDelay(); // Calculate backoff delay
|
||||
|
||||
// Network Stabilization Timer (non-blocking replacement for delay)
|
||||
TimerHandle_t _networkStabilizationTimer;
|
||||
static const unsigned long NETWORK_STABILIZATION_DELAY = 2000; // 2 seconds
|
||||
void connectAfterStabilization();
|
||||
static void networkStabilizationTimerCallback(TimerHandle_t xTimer);
|
||||
static void mqttConnectTaskFn(void* param);
|
||||
|
||||
// Heartbeat Timer (30 seconds)
|
||||
TimerHandle_t _heartbeatTimer;
|
||||
static const unsigned long HEARTBEAT_INTERVAL = 30000; // 30 seconds
|
||||
TaskHandle_t _heartbeatTaskHandle; // Guard: only one heartbeat task at a time
|
||||
void publishHeartbeat();
|
||||
static void heartbeatTimerCallback(TimerHandle_t xTimer);
|
||||
static void mqttHeartbeatTaskFn(void* param);
|
||||
void startHeartbeat();
|
||||
void stopHeartbeat();
|
||||
};
|
||||
@@ -0,0 +1,165 @@
|
||||
#include "ResponseBuilder.hpp"
|
||||
|
||||
#define TAG "ResponseBuilder"
|
||||
#include "../../Logging/Logging.hpp"
|
||||
|
||||
// Static member initialization
|
||||
StaticJsonDocument<512> ResponseBuilder::_responseDoc;
|
||||
|
||||
String ResponseBuilder::success(const String& type, const String& payload) {
|
||||
return buildResponse(Status::SUCCESS, type, payload);
|
||||
}
|
||||
|
||||
String ResponseBuilder::success(const String& type, const JsonObject& payload) {
|
||||
return buildResponse(Status::SUCCESS, type, payload);
|
||||
}
|
||||
|
||||
String ResponseBuilder::error(const String& type, const String& message) {
|
||||
return buildResponse(Status::ERROR, type, message);
|
||||
}
|
||||
|
||||
String ResponseBuilder::status(const String& type, const JsonObject& data) {
|
||||
return buildResponse(Status::SUCCESS, type, data);
|
||||
}
|
||||
|
||||
String ResponseBuilder::status(const String& type, const String& data) {
|
||||
return buildResponse(Status::SUCCESS, type, data);
|
||||
}
|
||||
|
||||
String ResponseBuilder::acknowledgment(const String& commandType) {
|
||||
return success(commandType, "Command acknowledged");
|
||||
}
|
||||
|
||||
String ResponseBuilder::pong() {
|
||||
return success("pong", "");
|
||||
}
|
||||
|
||||
String ResponseBuilder::deviceStatus(PlayerStatus playerStatus, uint32_t timeElapsed, uint64_t projectedRunTime, const uint32_t strikeCounters[16]) {
|
||||
DynamicJsonDocument statusDoc(1024); // Increased size for strikeCounters array
|
||||
|
||||
statusDoc["status"] = "SUCCESS";
|
||||
statusDoc["type"] = "current_status";
|
||||
|
||||
// Create payload object with the exact format expected by Flutter
|
||||
JsonObject payload = statusDoc.createNestedObject("payload");
|
||||
|
||||
// Convert PlayerStatus to string
|
||||
const char* statusStr;
|
||||
switch (playerStatus) {
|
||||
case PlayerStatus::PLAYING:
|
||||
statusStr = "playing";
|
||||
break;
|
||||
case PlayerStatus::PAUSED:
|
||||
statusStr = "paused";
|
||||
break;
|
||||
case PlayerStatus::STOPPING:
|
||||
statusStr = "stopping";
|
||||
break;
|
||||
case PlayerStatus::STOPPED:
|
||||
default:
|
||||
statusStr = "idle"; // STOPPED maps to "idle" in Flutter
|
||||
break;
|
||||
}
|
||||
|
||||
payload["player_status"] = statusStr;
|
||||
payload["time_elapsed"] = timeElapsed; // in milliseconds
|
||||
payload["projected_run_time"] = projectedRunTime; // NEW: total projected duration
|
||||
|
||||
// Add strike counters array
|
||||
JsonArray strikeCountersArray = payload.createNestedArray("strike_counters");
|
||||
for (uint8_t i = 0; i < 16; i++) {
|
||||
strikeCountersArray.add(strikeCounters[i]);
|
||||
}
|
||||
|
||||
String result;
|
||||
serializeJson(statusDoc, result);
|
||||
|
||||
LOG_DEBUG(TAG, "Device status response: %s", result.c_str());
|
||||
return result;
|
||||
}
|
||||
|
||||
String ResponseBuilder::melodyList(const String& fileListJson) {
|
||||
// The fileListJson is already a JSON string, so we pass it as payload
|
||||
return success("melody_list", fileListJson);
|
||||
}
|
||||
|
||||
String ResponseBuilder::downloadResult(bool success, const String& filename) {
|
||||
if (success) {
|
||||
String message = "Download successful";
|
||||
if (filename.length() > 0) {
|
||||
message += ": " + filename;
|
||||
}
|
||||
return ResponseBuilder::success("download", message);
|
||||
} else {
|
||||
String message = "Download failed";
|
||||
if (filename.length() > 0) {
|
||||
message += ": " + filename;
|
||||
}
|
||||
return error("download", message);
|
||||
}
|
||||
}
|
||||
|
||||
String ResponseBuilder::configUpdate(const String& configType) {
|
||||
return success(configType, configType + " configuration updated");
|
||||
}
|
||||
|
||||
String ResponseBuilder::invalidCommand(const String& command) {
|
||||
return error("invalid_command", "Unknown command: " + command);
|
||||
}
|
||||
|
||||
String ResponseBuilder::missingParameter(const String& parameter) {
|
||||
return error("missing_parameter", "Required parameter missing: " + parameter);
|
||||
}
|
||||
|
||||
String ResponseBuilder::operationFailed(const String& operation, const String& reason) {
|
||||
String message = operation + " failed";
|
||||
if (reason.length() > 0) {
|
||||
message += ": " + reason;
|
||||
}
|
||||
return error(operation, message);
|
||||
}
|
||||
|
||||
String ResponseBuilder::deviceBusy() {
|
||||
return error("device_busy", "Device is currently busy, try again later");
|
||||
}
|
||||
|
||||
String ResponseBuilder::unauthorized() {
|
||||
return error("unauthorized", "Operation not authorized for this client");
|
||||
}
|
||||
|
||||
// Response Builder with String Payload
|
||||
String ResponseBuilder::buildResponse(Status status, const String& type, const String& payload) {
|
||||
_responseDoc.clear();
|
||||
_responseDoc["status"] = statusToString(status);
|
||||
_responseDoc["type"] = type;
|
||||
_responseDoc["payload"] = payload;
|
||||
|
||||
String result;
|
||||
serializeJson(_responseDoc, result);
|
||||
|
||||
LOG_DEBUG(TAG, "Response built: %s", result.c_str());
|
||||
return result;
|
||||
}
|
||||
|
||||
// Response Builder with JSON Payload
|
||||
String ResponseBuilder::buildResponse(Status status, const String& type, const JsonObject& payload) {
|
||||
_responseDoc.clear();
|
||||
_responseDoc["status"] = statusToString(status);
|
||||
_responseDoc["type"] = type;
|
||||
_responseDoc["payload"] = payload;
|
||||
|
||||
String result;
|
||||
serializeJson(_responseDoc, result);
|
||||
|
||||
LOG_DEBUG(TAG, "Response built: %s", result.c_str());
|
||||
return result;
|
||||
}
|
||||
|
||||
const char* ResponseBuilder::statusToString(Status status) {
|
||||
switch (status) {
|
||||
case Status::SUCCESS: return "SUCCESS";
|
||||
case Status::ERROR: return "ERROR";
|
||||
case Status::INFO: return "INFO";
|
||||
default: return "UNKNOWN";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* RESPONSEBUILDER.HPP - Unified Response Generation System
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 📡 STANDARDIZED COMMUNICATION RESPONSES 📡
|
||||
*
|
||||
* This class provides a unified interface for generating consistent JSON responses
|
||||
* across all communication protocols (MQTT, WebSocket). It ensures all responses
|
||||
* follow the same format and structure.
|
||||
*
|
||||
* 🏗️ ARCHITECTURE:
|
||||
* • Static methods for response generation
|
||||
* • Consistent JSON structure across all protocols
|
||||
* • Memory-efficient response building
|
||||
* • Type-safe response categories
|
||||
*
|
||||
* 📡 RESPONSE TYPES:
|
||||
* • Success: Successful command execution
|
||||
* • Error: Command execution failures
|
||||
* • Status: System status reports and updates
|
||||
* • Data: Information requests and telemetry
|
||||
*
|
||||
* 🔄 RESPONSE STRUCTURE:
|
||||
* {
|
||||
* "status": "OK|ERROR",
|
||||
* "type": "command_type",
|
||||
* "payload": "data_or_message"
|
||||
* }
|
||||
*
|
||||
* 📋 USAGE EXAMPLES:
|
||||
* • ResponseBuilder::success("playback", "Started playing melody")
|
||||
* • ResponseBuilder::error("download", "File not found")
|
||||
* • ResponseBuilder::status("telemetry", telemetryData)
|
||||
*
|
||||
* 📋 VERSION: 1.0 (Initial unified response system)
|
||||
* 📅 DATE: 2025
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <ArduinoJson.h>
|
||||
#include "../../Player/Player.hpp" // For PlayerStatus enum
|
||||
|
||||
class ResponseBuilder {
|
||||
public:
|
||||
// Response status types
|
||||
enum class Status {
|
||||
SUCCESS,
|
||||
ERROR,
|
||||
INFO
|
||||
};
|
||||
|
||||
// Main response builders
|
||||
static String success(const String& type, const String& payload = "");
|
||||
static String success(const String& type, const JsonObject& payload);
|
||||
static String error(const String& type, const String& message);
|
||||
static String status(const String& type, const JsonObject& data);
|
||||
static String status(const String& type, const String& data);
|
||||
|
||||
// Specialized response builders for common scenarios
|
||||
static String acknowledgment(const String& commandType);
|
||||
static String pong();
|
||||
static String deviceStatus(PlayerStatus playerStatus, uint32_t timeElapsedMs, uint64_t projectedRunTime, const uint32_t strikeCounters[16]);
|
||||
static String melodyList(const String& fileListJson);
|
||||
static String downloadResult(bool success, const String& filename = "");
|
||||
static String configUpdate(const String& configType);
|
||||
|
||||
// Error response builders
|
||||
static String invalidCommand(const String& command);
|
||||
static String missingParameter(const String& parameter);
|
||||
static String operationFailed(const String& operation, const String& reason = "");
|
||||
static String deviceBusy();
|
||||
static String unauthorized();
|
||||
|
||||
// Utility methods
|
||||
static String buildResponse(Status status, const String& type, const String& payload);
|
||||
static String buildResponse(Status status, const String& type, const JsonObject& payload);
|
||||
|
||||
private:
|
||||
// Internal helper methods
|
||||
static const char* statusToString(Status status);
|
||||
static StaticJsonDocument<512> _responseDoc; // Reusable document for efficiency
|
||||
};
|
||||
@@ -0,0 +1,133 @@
|
||||
/*
|
||||
* UARTCOMMANDHANDLER.CPP - UART Command Handler Implementation
|
||||
*/
|
||||
|
||||
#include "UARTCommandHandler.hpp"
|
||||
|
||||
#define TAG "UARTHandler"
|
||||
#include "../../Logging/Logging.hpp"
|
||||
|
||||
UARTCommandHandler::UARTCommandHandler(uint8_t txPin, uint8_t rxPin, uint32_t baudRate)
|
||||
: _serial(Serial2)
|
||||
, _txPin(txPin)
|
||||
, _rxPin(rxPin)
|
||||
, _baudRate(baudRate)
|
||||
, _ready(false)
|
||||
, _bufferIndex(0)
|
||||
, _messageCount(0)
|
||||
, _errorCount(0)
|
||||
, _callback(nullptr)
|
||||
{
|
||||
resetBuffer();
|
||||
}
|
||||
|
||||
UARTCommandHandler::~UARTCommandHandler() {
|
||||
_serial.end();
|
||||
}
|
||||
|
||||
void UARTCommandHandler::begin() {
|
||||
LOG_INFO(TAG, "Initializing UART Command Handler");
|
||||
LOG_INFO(TAG, " TX Pin: GPIO%d", _txPin);
|
||||
LOG_INFO(TAG, " RX Pin: GPIO%d", _rxPin);
|
||||
LOG_INFO(TAG, " Baud Rate: %u", _baudRate);
|
||||
|
||||
// Initialize Serial2 with custom pins
|
||||
_serial.begin(_baudRate, SERIAL_8N1, _rxPin, _txPin);
|
||||
|
||||
// Clear any garbage in the buffer
|
||||
while (_serial.available()) {
|
||||
_serial.read();
|
||||
}
|
||||
|
||||
_ready = true;
|
||||
LOG_INFO(TAG, "UART Command Handler ready");
|
||||
}
|
||||
|
||||
void UARTCommandHandler::loop() {
|
||||
if (!_ready) return;
|
||||
|
||||
// Process all available bytes
|
||||
while (_serial.available()) {
|
||||
char c = _serial.read();
|
||||
|
||||
// Check for message delimiter (newline)
|
||||
if (c == '\n' || c == '\r') {
|
||||
if (_bufferIndex > 0) {
|
||||
// Null-terminate and process
|
||||
_buffer[_bufferIndex] = '\0';
|
||||
processLine(_buffer);
|
||||
resetBuffer();
|
||||
}
|
||||
// Skip empty lines
|
||||
continue;
|
||||
}
|
||||
|
||||
// Add character to buffer
|
||||
if (_bufferIndex < BUFFER_SIZE - 1) {
|
||||
_buffer[_bufferIndex++] = c;
|
||||
} else {
|
||||
// Buffer overflow - discard and reset
|
||||
LOG_ERROR(TAG, "UART buffer overflow, discarding message");
|
||||
_errorCount++;
|
||||
resetBuffer();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void UARTCommandHandler::setCallback(MessageCallback callback) {
|
||||
_callback = callback;
|
||||
}
|
||||
|
||||
void UARTCommandHandler::send(const String& response) {
|
||||
if (!_ready) {
|
||||
LOG_ERROR(TAG, "UART not ready, cannot send response");
|
||||
return;
|
||||
}
|
||||
|
||||
_serial.print(response);
|
||||
_serial.print('\n'); // Newline delimiter
|
||||
_serial.flush(); // Ensure data is sent
|
||||
|
||||
LOG_DEBUG(TAG, "UART TX: %s", response.c_str());
|
||||
}
|
||||
|
||||
void UARTCommandHandler::processLine(const char* line) {
|
||||
LOG_DEBUG(TAG, "UART RX: %s", line);
|
||||
|
||||
// Skip empty lines or whitespace-only
|
||||
if (strlen(line) == 0) return;
|
||||
|
||||
// Parse JSON
|
||||
StaticJsonDocument<1024> doc;
|
||||
DeserializationError error = deserializeJson(doc, line);
|
||||
|
||||
if (error) {
|
||||
LOG_ERROR(TAG, "UART JSON parse error: %s", error.c_str());
|
||||
_errorCount++;
|
||||
|
||||
// Send error response back
|
||||
StaticJsonDocument<256> errorDoc;
|
||||
errorDoc["status"] = "ERROR";
|
||||
errorDoc["type"] = "parse_error";
|
||||
errorDoc["payload"] = error.c_str();
|
||||
|
||||
String errorResponse;
|
||||
serializeJson(errorDoc, errorResponse);
|
||||
send(errorResponse);
|
||||
return;
|
||||
}
|
||||
|
||||
_messageCount++;
|
||||
|
||||
// Invoke callback if set
|
||||
if (_callback) {
|
||||
_callback(doc);
|
||||
} else {
|
||||
LOG_WARNING(TAG, "UART message received but no callback set");
|
||||
}
|
||||
}
|
||||
|
||||
void UARTCommandHandler::resetBuffer() {
|
||||
_bufferIndex = 0;
|
||||
memset(_buffer, 0, BUFFER_SIZE);
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* UARTCOMMANDHANDLER.HPP - UART Command Interface for External Control Devices
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 🔌 UART COMMAND HANDLER 🔌
|
||||
*
|
||||
* Enables command input from external devices (LCD panels, button controllers)
|
||||
* via UART serial communication. Uses newline-delimited JSON protocol.
|
||||
*
|
||||
* Pin Configuration:
|
||||
* • TX: GPIO12
|
||||
* • RX: GPIO13
|
||||
* • Baud: 115200 (configurable)
|
||||
*
|
||||
* Protocol:
|
||||
* • Newline-delimited JSON messages
|
||||
* • Same command format as MQTT/WebSocket
|
||||
* • Responses sent back on same UART
|
||||
*
|
||||
* 📋 VERSION: 1.0
|
||||
* 📅 DATE: 2025-01-19
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <ArduinoJson.h>
|
||||
#include <functional>
|
||||
|
||||
class UARTCommandHandler {
|
||||
public:
|
||||
// Default pin configuration
|
||||
static constexpr uint8_t DEFAULT_TX_PIN = 12;
|
||||
static constexpr uint8_t DEFAULT_RX_PIN = 13;
|
||||
static constexpr uint32_t DEFAULT_BAUD_RATE = 115200;
|
||||
static constexpr size_t BUFFER_SIZE = 1024;
|
||||
|
||||
// Message callback type - called when a complete JSON message is received
|
||||
using MessageCallback = std::function<void(JsonDocument& message)>;
|
||||
|
||||
/**
|
||||
* @brief Construct UART handler with custom pins
|
||||
* @param txPin GPIO pin for TX (default: 12)
|
||||
* @param rxPin GPIO pin for RX (default: 13)
|
||||
* @param baudRate Baud rate (default: 115200)
|
||||
*/
|
||||
explicit UARTCommandHandler(uint8_t txPin = DEFAULT_TX_PIN,
|
||||
uint8_t rxPin = DEFAULT_RX_PIN,
|
||||
uint32_t baudRate = DEFAULT_BAUD_RATE);
|
||||
|
||||
~UARTCommandHandler();
|
||||
|
||||
/**
|
||||
* @brief Initialize the UART interface
|
||||
*/
|
||||
void begin();
|
||||
|
||||
/**
|
||||
* @brief Process incoming UART data (call from loop or task)
|
||||
* Non-blocking - processes available bytes and returns
|
||||
*/
|
||||
void loop();
|
||||
|
||||
/**
|
||||
* @brief Set callback for received messages
|
||||
* @param callback Function to call with parsed JSON
|
||||
*/
|
||||
void setCallback(MessageCallback callback);
|
||||
|
||||
/**
|
||||
* @brief Send a response back over UART
|
||||
* @param response JSON string to send (newline appended automatically)
|
||||
*/
|
||||
void send(const String& response);
|
||||
|
||||
/**
|
||||
* @brief Check if UART is initialized and ready
|
||||
*/
|
||||
bool isReady() const { return _ready; }
|
||||
|
||||
/**
|
||||
* @brief Get number of messages received since boot
|
||||
*/
|
||||
uint32_t getMessageCount() const { return _messageCount; }
|
||||
|
||||
/**
|
||||
* @brief Get number of parse errors since boot
|
||||
*/
|
||||
uint32_t getErrorCount() const { return _errorCount; }
|
||||
|
||||
private:
|
||||
HardwareSerial& _serial;
|
||||
uint8_t _txPin;
|
||||
uint8_t _rxPin;
|
||||
uint32_t _baudRate;
|
||||
bool _ready;
|
||||
|
||||
// Receive buffer
|
||||
char _buffer[BUFFER_SIZE];
|
||||
size_t _bufferIndex;
|
||||
|
||||
// Statistics
|
||||
uint32_t _messageCount;
|
||||
uint32_t _errorCount;
|
||||
|
||||
// Callback
|
||||
MessageCallback _callback;
|
||||
|
||||
/**
|
||||
* @brief Process a complete line from the buffer
|
||||
* @param line Null-terminated string containing the message
|
||||
*/
|
||||
void processLine(const char* line);
|
||||
|
||||
/**
|
||||
* @brief Reset the receive buffer
|
||||
*/
|
||||
void resetBuffer();
|
||||
};
|
||||
@@ -0,0 +1,159 @@
|
||||
/*
|
||||
* WEBSOCKETSERVER.CPP - WebSocket Server Implementation
|
||||
*/
|
||||
|
||||
#include "WebSocketServer.hpp"
|
||||
|
||||
#define TAG "WebSocket"
|
||||
#include "../../Logging/Logging.hpp"
|
||||
#include "../ResponseBuilder/ResponseBuilder.hpp"
|
||||
|
||||
// Static instance for callback
|
||||
WebSocketServer* WebSocketServer::_instance = nullptr;
|
||||
|
||||
WebSocketServer::WebSocketServer(AsyncWebSocket& webSocket, ClientManager& clientManager)
|
||||
: _webSocket(webSocket)
|
||||
, _clientManager(clientManager)
|
||||
, _messageCallback(nullptr) {
|
||||
|
||||
_instance = this;
|
||||
}
|
||||
|
||||
WebSocketServer::~WebSocketServer() {
|
||||
_instance = nullptr;
|
||||
}
|
||||
|
||||
void WebSocketServer::begin() {
|
||||
_webSocket.onEvent(onEvent);
|
||||
LOG_INFO(TAG, "WebSocket server initialized on /ws");
|
||||
|
||||
// 🔥 CRITICAL: This line was missing - attach WebSocket to the AsyncWebServer
|
||||
// Without this, the server doesn't know about the WebSocket handler!
|
||||
// Note: We can't access _server here directly, so this must be done in CommunicationRouter
|
||||
}
|
||||
|
||||
void WebSocketServer::setCallback(MessageCallback callback) {
|
||||
_messageCallback = callback;
|
||||
}
|
||||
|
||||
void WebSocketServer::sendToClient(uint32_t clientId, const String& message) {
|
||||
_clientManager.sendToClient(clientId, message);
|
||||
}
|
||||
|
||||
void WebSocketServer::broadcastToAll(const String& message) {
|
||||
_clientManager.broadcastToAll(message);
|
||||
LOG_DEBUG(TAG, "Broadcast to all WebSocket clients: %s", message.c_str());
|
||||
}
|
||||
|
||||
void WebSocketServer::broadcastToMaster(const String& message) {
|
||||
_clientManager.sendToMasterClients(message);
|
||||
LOG_DEBUG(TAG, "Broadcast to master clients: %s", message.c_str());
|
||||
}
|
||||
|
||||
void WebSocketServer::broadcastToSecondary(const String& message) {
|
||||
_clientManager.sendToSecondaryClients(message);
|
||||
LOG_DEBUG(TAG, "Broadcast to secondary clients: %s", message.c_str());
|
||||
}
|
||||
|
||||
bool WebSocketServer::hasClients() const {
|
||||
return _clientManager.hasClients();
|
||||
}
|
||||
|
||||
size_t WebSocketServer::getClientCount() const {
|
||||
return _clientManager.getClientCount();
|
||||
}
|
||||
|
||||
void WebSocketServer::onEvent(AsyncWebSocket* server, AsyncWebSocketClient* client,
|
||||
AwsEventType type, void* arg, uint8_t* data, size_t len) {
|
||||
if (!_instance) {
|
||||
LOG_ERROR(TAG, "WebSocketServer static instance is NULL - callback ignored!");
|
||||
return;
|
||||
}
|
||||
|
||||
switch (type) {
|
||||
case WS_EVT_CONNECT:
|
||||
_instance->onConnect(client);
|
||||
break;
|
||||
|
||||
case WS_EVT_DISCONNECT:
|
||||
_instance->onDisconnect(client);
|
||||
break;
|
||||
|
||||
case WS_EVT_DATA:
|
||||
_instance->onData(client, arg, data, len);
|
||||
break;
|
||||
|
||||
case WS_EVT_ERROR:
|
||||
LOG_ERROR(TAG, "WebSocket client #%u error(%u): %s",
|
||||
client->id(), *((uint16_t*)arg), (char*)data);
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void WebSocketServer::onConnect(AsyncWebSocketClient* client) {
|
||||
LOG_INFO(TAG, "WebSocket client #%u connected from %s",
|
||||
client->id(), client->remoteIP().toString().c_str());
|
||||
|
||||
// Add client to manager (type UNKNOWN until they identify)
|
||||
_clientManager.addClient(client, ClientManager::DeviceType::UNKNOWN);
|
||||
|
||||
// Send welcome message
|
||||
String welcomeMsg = ResponseBuilder::success("connection", "Connected to Vesper");
|
||||
_clientManager.sendToClient(client->id(), welcomeMsg);
|
||||
}
|
||||
|
||||
void WebSocketServer::onDisconnect(AsyncWebSocketClient* client) {
|
||||
LOG_INFO(TAG, "WebSocket client #%u disconnected", client->id());
|
||||
|
||||
_clientManager.removeClient(client->id());
|
||||
_clientManager.cleanupDisconnectedClients();
|
||||
}
|
||||
|
||||
void WebSocketServer::onData(AsyncWebSocketClient* client, void* arg, uint8_t* data, size_t len) {
|
||||
AwsFrameInfo* info = (AwsFrameInfo*)arg;
|
||||
|
||||
// Only handle complete, single-frame text messages
|
||||
if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
|
||||
// Allocate buffer for payload
|
||||
char* payload = (char*)malloc(len + 1);
|
||||
if (!payload) {
|
||||
LOG_ERROR(TAG, "Failed to allocate memory for WebSocket payload");
|
||||
String errorResponse = ResponseBuilder::error("memory_error", "Out of memory");
|
||||
_clientManager.sendToClient(client->id(), errorResponse);
|
||||
return;
|
||||
}
|
||||
|
||||
memcpy(payload, data, len);
|
||||
payload[len] = '\0';
|
||||
|
||||
LOG_DEBUG(TAG, "WebSocket client #%u sent: %s", client->id(), payload);
|
||||
|
||||
// Parse JSON
|
||||
StaticJsonDocument<2048> doc;
|
||||
DeserializationError error = deserializeJson(doc, payload);
|
||||
|
||||
if (error) {
|
||||
LOG_ERROR(TAG, "Failed to parse WebSocket JSON from client #%u: %s", client->id(), error.c_str());
|
||||
String errorResponse = ResponseBuilder::error("parse_error", "Invalid JSON");
|
||||
_clientManager.sendToClient(client->id(), errorResponse);
|
||||
} else {
|
||||
// Update client last seen time
|
||||
_clientManager.updateClientLastSeen(client->id());
|
||||
|
||||
// Call user callback if set
|
||||
if (_messageCallback) {
|
||||
LOG_DEBUG(TAG, "Routing message from client #%u to callback handler", client->id());
|
||||
_messageCallback(client->id(), doc);
|
||||
} else {
|
||||
LOG_WARNING(TAG, "WebSocket message received but no callback handler is set!");
|
||||
}
|
||||
}
|
||||
|
||||
free(payload);
|
||||
} else {
|
||||
LOG_WARNING(TAG, "Received fragmented or non-text WebSocket message from client #%u - ignoring", client->id());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* WEBSOCKETSERVER.HPP - WebSocket Server Manager
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 📡 WEBSOCKET MULTI-CLIENT MANAGER 📡
|
||||
*
|
||||
* Handles WebSocket connections with:
|
||||
* • Multi-client support with device type identification
|
||||
* • Automatic client cleanup
|
||||
* • Broadcast and targeted messaging
|
||||
* • Integration with ClientManager
|
||||
*
|
||||
* 📋 VERSION: 1.0
|
||||
* 📅 DATE: 2025-10-01
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <ESPAsyncWebServer.h>
|
||||
#include <ArduinoJson.h>
|
||||
#include "../../ClientManager/ClientManager.hpp"
|
||||
|
||||
class WebSocketServer {
|
||||
public:
|
||||
// Message callback type
|
||||
using MessageCallback = std::function<void(uint32_t clientId, const JsonDocument& message)>;
|
||||
|
||||
explicit WebSocketServer(AsyncWebSocket& webSocket, ClientManager& clientManager);
|
||||
~WebSocketServer();
|
||||
|
||||
/**
|
||||
* @brief Initialize WebSocket server
|
||||
*/
|
||||
void begin();
|
||||
|
||||
/**
|
||||
* @brief Set message received callback
|
||||
*/
|
||||
void setCallback(MessageCallback callback);
|
||||
|
||||
/**
|
||||
* @brief Send message to specific client
|
||||
*/
|
||||
void sendToClient(uint32_t clientId, const String& message);
|
||||
|
||||
/**
|
||||
* @brief Broadcast to all connected clients
|
||||
*/
|
||||
void broadcastToAll(const String& message);
|
||||
|
||||
/**
|
||||
* @brief Broadcast to master devices only
|
||||
*/
|
||||
void broadcastToMaster(const String& message);
|
||||
|
||||
/**
|
||||
* @brief Broadcast to secondary devices only
|
||||
*/
|
||||
void broadcastToSecondary(const String& message);
|
||||
|
||||
/**
|
||||
* @brief Check if any clients are connected
|
||||
*/
|
||||
bool hasClients() const;
|
||||
|
||||
/**
|
||||
* @brief Get number of connected clients
|
||||
*/
|
||||
size_t getClientCount() const;
|
||||
|
||||
private:
|
||||
AsyncWebSocket& _webSocket;
|
||||
ClientManager& _clientManager;
|
||||
MessageCallback _messageCallback;
|
||||
|
||||
/**
|
||||
* @brief Static WebSocket event handler
|
||||
*/
|
||||
static void onEvent(AsyncWebSocket* server, AsyncWebSocketClient* client,
|
||||
AwsEventType type, void* arg, uint8_t* data, size_t len);
|
||||
|
||||
/**
|
||||
* @brief Handle client connection
|
||||
*/
|
||||
void onConnect(AsyncWebSocketClient* client);
|
||||
|
||||
/**
|
||||
* @brief Handle client disconnection
|
||||
*/
|
||||
void onDisconnect(AsyncWebSocketClient* client);
|
||||
|
||||
/**
|
||||
* @brief Handle received data
|
||||
*/
|
||||
void onData(AsyncWebSocketClient* client, void* arg, uint8_t* data, size_t len);
|
||||
|
||||
// Static instance for callback routing
|
||||
static WebSocketServer* _instance;
|
||||
};
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,471 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* CONFIGMANAGER.HPP - Deployment-Ready Configuration Management System
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 🗂️ CLEAN DEPLOYMENT-READY CONFIG SYSTEM 🗂️
|
||||
*
|
||||
* This restructured configuration system is designed for production deployment
|
||||
* with minimal hardcoded defaults, proper separation of factory vs user settings,
|
||||
* and clean configuration hierarchy.
|
||||
*
|
||||
* 🏗️ DEPLOYMENT PHILOSOPHY:
|
||||
* • Factory settings stored in NVS (permanent, set once)
|
||||
* • User settings stored on SD card (configurable via app)
|
||||
* • Hardware settings compiled per HWID variant
|
||||
* • Network credentials handled by WiFiManager only
|
||||
* • Auto-generated identifiers where appropriate
|
||||
*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <ArduinoJson.h>
|
||||
#include <SD.h>
|
||||
#include <IPAddress.h>
|
||||
#include <vector>
|
||||
#include <nvs_flash.h>
|
||||
#include <nvs.h>
|
||||
|
||||
class ConfigManager {
|
||||
public:
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// CONFIGURATION STRUCTURES - Clean deployment-ready design
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @struct DeviceConfig
|
||||
* @brief Factory-set device identity (NVS storage)
|
||||
*
|
||||
* These values are set once during manufacturing and stored in NVS.
|
||||
* fwVersion is updated automatically after OTA updates (SD storage).
|
||||
*/
|
||||
struct DeviceConfig {
|
||||
String deviceUID = ""; // 🏷️ Factory-set UID (NVS) - NO DEFAULT
|
||||
String hwType = ""; // 🔧 Factory-set hardware type (NVS) - NO DEFAULT
|
||||
String hwVersion = ""; // 📐 Factory-set hardware revision (NVS) - NO DEFAULT
|
||||
String fwVersion = "0"; // 📋 Current firmware version (SD) - auto-updated (integer string)
|
||||
};
|
||||
|
||||
/**
|
||||
* @struct NetworkConfig
|
||||
* @brief Network connectivity settings
|
||||
*
|
||||
* WiFi credentials are handled entirely by WiFiManager.
|
||||
* Static IP settings are configured via app commands and stored on SD.
|
||||
* hostname is auto-generated from deviceUID.
|
||||
*/
|
||||
struct NetworkConfig {
|
||||
String hostname; // 🏭 Auto-generated: "BellSystems-<DEVID>"
|
||||
bool useStaticIP = false; // 🔧 Default DHCP, app-configurable via SD
|
||||
IPAddress ip; // 🏠 Empty default, read from SD
|
||||
IPAddress gateway; // 🌐 Empty default, read from SD
|
||||
IPAddress subnet; // 📊 Empty default, read from SD
|
||||
IPAddress dns1; // 📝 Empty default, read from SD
|
||||
IPAddress dns2; // 📝 Empty default, read from SD
|
||||
String apSsid; // 📡 Auto-generated AP name
|
||||
String apPass; // 🔐 AP is Open. No Password
|
||||
uint16_t discoveryPort = 32101; // 📡 Fixed discovery port
|
||||
bool permanentAPMode = false; // 🔘 Permanent AP mode toggle (stored on SD)
|
||||
String defaultWifiSsid = "BellSystemsInfra"; // 📡 Default WiFi SSID to try on boot
|
||||
String defaultWifiPsk = "v3sp3r_8998!"; // 🔐 Default WiFi password to try on boot
|
||||
};
|
||||
|
||||
/**
|
||||
* @struct MqttConfig
|
||||
* @brief MQTT broker connection settings
|
||||
*
|
||||
* Default configured for local Mosquitto broker.
|
||||
* Username defaults to deviceUID for unique identification.
|
||||
*/
|
||||
struct MqttConfig {
|
||||
IPAddress host = IPAddress(72,61,191,197); // 📡 MQTT broker (default cloud broker)
|
||||
int port = 1883; // 🔌 Standard MQTT port (non-SSL)
|
||||
String user; // 👤 Auto-set to deviceUID
|
||||
String password; // 🔑 Derived at runtime via computeMqttPassword()
|
||||
bool useSSL = false; // 🔒 SSL disabled for local broker
|
||||
bool enabled = true; // 🔘 MQTT enabled by default (can be toggled via command)
|
||||
};
|
||||
|
||||
/**
|
||||
* @struct HardwareConfig
|
||||
* @brief Hardware-specific settings (compiled per HWID)
|
||||
*
|
||||
* These values are hardware-variant specific and compiled into firmware.
|
||||
* Different values for different hardware revisions.
|
||||
*/
|
||||
struct HardwareConfig {
|
||||
uint8_t pcf8574Address = 0x24; // 🔌 Hardware-specific - OK as is
|
||||
uint8_t sdChipSelect = 5; // 💾 Hardware-specific - OK as is
|
||||
|
||||
// Ethernet SPI configuration - hardware-specific
|
||||
uint8_t ethSpiSck = 18; // ⏱️ Hardware-specific - OK as is
|
||||
uint8_t ethSpiMiso = 19; // 🔄 Hardware-specific - OK as is
|
||||
uint8_t ethSpiMosi = 23; // 🔄 Hardware-specific - OK as is
|
||||
|
||||
// ETH PHY Configuration - ETHERNET DISABLED (kept for legacy/future use)
|
||||
uint8_t ethPhyType = 9; // was ETH_PHY_W5500 (9) — Ethernet removed in v138
|
||||
uint8_t ethPhyAddr = 1; // 📍 Hardware-specific - OK as is
|
||||
uint8_t ethPhyCs = 5; // 💾 Hardware-specific - OK as is
|
||||
int8_t ethPhyIrq = -1; // ⚡ Hardware-specific - OK as is
|
||||
int8_t ethPhyRst = -1; // 🔄 Hardware-specific - OK as is
|
||||
};
|
||||
|
||||
/**
|
||||
* @struct TimeConfig
|
||||
* @brief Timezone and NTP settings
|
||||
*
|
||||
* NTP server is universal default.
|
||||
* Timezone offsets default to 0 (UTC) and are configured via app.
|
||||
*/
|
||||
struct TimeConfig {
|
||||
String ntpServer = "pool.ntp.org"; // ⏰ Universal NTP - OK as is
|
||||
long gmtOffsetSec = 7200; // 🌍 Default GMT+2 (Greek Time), app-configurable via SD
|
||||
int daylightOffsetSec = 0; // ☀️ Default no DST, app-configurable via SD
|
||||
};
|
||||
|
||||
/**
|
||||
* @struct UpdateConfig
|
||||
* @brief OTA update server configuration
|
||||
*
|
||||
* Universal defaults for all devices.
|
||||
*/
|
||||
struct UpdateConfig {
|
||||
String fallbackServerUrl = "http://firmware.bonamin.space"; // 🛡️ Universal fallback - OK as is
|
||||
int timeout = 10000; // ⏱️ Universal timeout - OK as is
|
||||
int retries = 3; // 🔄 Universal retries - OK as is
|
||||
};
|
||||
|
||||
/**
|
||||
* @struct BellConfig
|
||||
* @brief Bell system configuration (loaded from SD)
|
||||
*
|
||||
* All bell settings are loaded from SD card at startup.
|
||||
*/
|
||||
struct BellConfig {
|
||||
uint16_t durations[16]; // ⏱️ Loaded from SD at startup Factory Def: Min Size Hammer
|
||||
uint16_t outputs[16]; // 🔌 Loaded from SD at startup. Factory Def: Disabled
|
||||
};
|
||||
|
||||
/**
|
||||
* @struct ClockConfig
|
||||
* @brief Clock mechanism configuration (loaded from SD)
|
||||
*
|
||||
* All clock settings are loaded from SD card at startup.
|
||||
* This struct is correctly designed and needs no changes.
|
||||
*/
|
||||
struct ClockConfig {
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// CLOCK ENABLE/DISABLE - Master control for all clock functionality
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
bool enabled = false; // 🔘 Enable/disable ALL clock functionality
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// CLOCK OUTPUTS - Physical output configuration
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
uint8_t c1output = 255; // 🕐 Clock output #1 pin (255 = disabled)
|
||||
uint8_t c2output = 255; // 🕑 Clock output #2 pin (255 = disabled)
|
||||
uint16_t pulseDuration = 5000; // ⏱️ Pulse duration in milliseconds
|
||||
uint16_t pauseDuration = 2000; // 🛑 Pause between consecutive pulses
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// PHYSICAL CLOCK STATE - Position tracking for sync
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
uint8_t physicalHour = 0; // 🕐 Physical clock hour (0-11)
|
||||
uint8_t physicalMinute = 0; // 🕐 Physical clock minute (0-59)
|
||||
bool nextOutputIsC1 = true; // 🔄 Which output fires next
|
||||
uint32_t lastSyncTime = 0; // ⏰ Last successful sync timestamp
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// ALERT CONFIGURATION - Bell alert behavior
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
String alertType = "OFF"; // 🔔 Alert mode: "SINGLE", "HOURS", or "OFF"
|
||||
uint16_t alertRingInterval = 1200; // ⏰ Interval between bell rings (ms) 1-2s 0.2s steps
|
||||
uint8_t hourBell = 255; // 🕐 Bell for hourly alerts (255 = disabled)
|
||||
uint8_t halfBell = 255; // 🕕 Bell for half-hour alerts (255 = disabled)
|
||||
uint8_t quarterBell = 255; // 🕒 Bell for quarter-hour alerts (255 = disabled)
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// BACKLIGHT AUTOMATION - Clock illumination control
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
bool backlight = false; // 💡 Enable/disable backlight automation
|
||||
uint8_t backlightOutput = 255; // 🔌 Backlight output pin (255 = disabled)
|
||||
String backlightOnTime = "18:00"; // 🌅 Time to turn backlight ON
|
||||
String backlightOffTime = "06:00"; // 🌄 Time to turn backlight OFF
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// SILENCE PERIODS - Quiet hours configuration
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
bool daytimeSilenceEnabled = false; // 🌞 Enable/disable daytime silence
|
||||
String daytimeSilenceOnTime = "14:00"; // 🌞 Start of daytime silence
|
||||
String daytimeSilenceOffTime = "17:00"; // 🌞 End of daytime silence
|
||||
bool nighttimeSilenceEnabled = false; // 🌙 Enable/disable nighttime silence
|
||||
String nighttimeSilenceOnTime = "22:00"; // 🌙 Start of nighttime silence
|
||||
String nighttimeSilenceOffTime = "07:00"; // 🌙 End of nighttime silence
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @struct General Config
|
||||
* @brief General configuration (loaded from SD)
|
||||
*
|
||||
* All clock settings are loaded from SD card at startup.
|
||||
*/
|
||||
struct GeneralConfig {
|
||||
uint8_t serialLogLevel = 5;
|
||||
uint8_t sdLogLevel = 0;
|
||||
uint8_t mqttLogLevel = 0;
|
||||
bool mqttEnabled = true; // MQTT enabled by default
|
||||
};
|
||||
|
||||
private:
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// MEMBER VARIABLES - Clean deployment-ready storage
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
DeviceConfig deviceConfig;
|
||||
NetworkConfig networkConfig;
|
||||
MqttConfig mqttConfig;
|
||||
HardwareConfig hardwareConfig;
|
||||
TimeConfig timeConfig;
|
||||
UpdateConfig updateConfig;
|
||||
BellConfig bellConfig;
|
||||
ClockConfig clockConfig;
|
||||
GeneralConfig generalConfig;
|
||||
|
||||
bool sdInitialized = false;
|
||||
std::vector<String> updateServers;
|
||||
nvs_handle_t nvsHandle = 0;
|
||||
static const char* NVS_NAMESPACE;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// PRIVATE METHODS - Clean initialization and auto-generation
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Initialize configuration with clean defaults and auto-generation
|
||||
*
|
||||
* This method:
|
||||
* 1. Loads device identity from NVS (factory-set)
|
||||
* 2. Auto-generates hostname from deviceUID
|
||||
* 3. Auto-generates AP SSID from deviceUID
|
||||
* 4. Sets MQTT username to deviceUID
|
||||
* 5. Loads user-configurable settings from SD
|
||||
*/
|
||||
void initializeCleanDefaults();
|
||||
|
||||
/**
|
||||
* @brief Auto-generate network identifiers from deviceUID
|
||||
*
|
||||
* Generates:
|
||||
* - hostname: "BellSystems-<last6ofUID>"
|
||||
* - apSsid: "BellSystems-Setup-<last6ofUID>"
|
||||
* - mqttUser: deviceUID
|
||||
*/
|
||||
void generateNetworkIdentifiers();
|
||||
|
||||
bool ensureSDCard();
|
||||
void createDefaultBellConfig();
|
||||
|
||||
// NVS management (READ-ONLY for factory-set device identity)
|
||||
bool initializeNVS();
|
||||
bool loadDeviceIdentityFromNVS();
|
||||
String readNVSString(const char* key, const String& defaultValue);
|
||||
// REMOVED: saveDeviceIdentityToNVS() and writeNVSString() - Production firmware is READ-ONLY
|
||||
|
||||
String computeMqttPassword(const String& uid);
|
||||
|
||||
public:
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// PUBLIC INTERFACE - Clean deployment-ready API
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
ConfigManager();
|
||||
|
||||
/**
|
||||
* @brief Initialize clean deployment-ready configuration system
|
||||
*
|
||||
* Load order:
|
||||
* 1. Device identity from NVS (factory-set, permanent)
|
||||
* 2. Auto-generate network identifiers
|
||||
* 3. Load user settings from SD card
|
||||
* 4. Apply clean defaults for missing settings
|
||||
*/
|
||||
bool begin();
|
||||
|
||||
bool saveToSD();
|
||||
|
||||
// Configuration access (read-only getters)
|
||||
const DeviceConfig& getDeviceConfig() const { return deviceConfig; }
|
||||
const NetworkConfig& getNetworkConfig() const { return networkConfig; }
|
||||
const MqttConfig& getMqttConfig() const { return mqttConfig; }
|
||||
const HardwareConfig& getHardwareConfig() const { return hardwareConfig; }
|
||||
const TimeConfig& getTimeConfig() const { return timeConfig; }
|
||||
const UpdateConfig& getUpdateConfig() const { return updateConfig; }
|
||||
const BellConfig& getBellConfig() const { return bellConfig; }
|
||||
const ClockConfig& getClockConfig() const { return clockConfig; }
|
||||
const GeneralConfig& getGeneralConfig() const { return generalConfig; }
|
||||
|
||||
// Device identity methods (READ-ONLY - factory set via separate factory firmware)
|
||||
// These values are loaded ONCE at boot from NVS and kept in RAM
|
||||
// Production firmware CANNOT modify device identity
|
||||
String getDeviceUID() const { return deviceConfig.deviceUID; }
|
||||
String getHwType() const { return deviceConfig.hwType; }
|
||||
String getHwVersion() const { return deviceConfig.hwVersion; }
|
||||
String getFwVersion() const { return deviceConfig.fwVersion; }
|
||||
|
||||
/** @brief Set firmware version (auto-updated after OTA) */
|
||||
void setFwVersion(const String& version) { deviceConfig.fwVersion = version; }
|
||||
|
||||
// Configuration update methods for app commands
|
||||
void updateTimeConfig(long gmtOffsetSec, int daylightOffsetSec);
|
||||
void updateNetworkConfig(const String& hostname, bool useStaticIP, IPAddress ip, IPAddress gateway,
|
||||
IPAddress subnet, IPAddress dns1, IPAddress dns2);
|
||||
|
||||
// AP Mode configuration
|
||||
bool getPermanentAPMode() const { return networkConfig.permanentAPMode; }
|
||||
void setPermanentAPMode(bool enabled) { networkConfig.permanentAPMode = enabled; }
|
||||
|
||||
// Network configuration persistence
|
||||
bool loadNetworkConfig();
|
||||
bool saveNetworkConfig();
|
||||
|
||||
// Time configuration persistence
|
||||
bool loadTimeConfig();
|
||||
bool saveTimeConfig();
|
||||
|
||||
// Bell and clock configuration methods (unchanged)
|
||||
bool loadBellDurations();
|
||||
bool saveBellDurations();
|
||||
bool loadBellOutputs();
|
||||
bool saveBellOutputs();
|
||||
void updateBellDurations(JsonVariant doc);
|
||||
void updateBellOutputs(JsonVariant doc);
|
||||
uint16_t getBellDuration(uint8_t bellIndex) const;
|
||||
uint16_t getBellOutput(uint8_t bellIndex) const;
|
||||
void setBellDuration(uint8_t bellIndex, uint16_t duration);
|
||||
void setBellOutput(uint8_t bellIndex, uint16_t output);
|
||||
|
||||
// Clock configuration methods (unchanged - already correct)
|
||||
bool getClockEnabled() const { return clockConfig.enabled; }
|
||||
void setClockEnabled(bool enabled) { clockConfig.enabled = enabled; }
|
||||
void updateClockOutputs(JsonVariant doc);
|
||||
uint8_t getClockOutput1() const { return clockConfig.c1output; }
|
||||
uint8_t getClockOutput2() const { return clockConfig.c2output; }
|
||||
uint16_t getClockPulseDuration() const { return clockConfig.pulseDuration; }
|
||||
uint16_t getClockPauseDuration() const { return clockConfig.pauseDuration; }
|
||||
void setClockOutput1(uint8_t output) { clockConfig.c1output = output; }
|
||||
void setClockOutput2(uint8_t output) { clockConfig.c2output = output; }
|
||||
void setClockPulseDuration(uint16_t duration) { clockConfig.pulseDuration = duration; }
|
||||
void setClockPauseDuration(uint16_t duration) { clockConfig.pauseDuration = duration; }
|
||||
|
||||
// Physical clock state methods (unchanged)
|
||||
uint8_t getPhysicalClockHour() const { return clockConfig.physicalHour; }
|
||||
uint8_t getPhysicalClockMinute() const { return clockConfig.physicalMinute; }
|
||||
bool getNextOutputIsC1() const { return clockConfig.nextOutputIsC1; }
|
||||
uint32_t getLastSyncTime() const { return clockConfig.lastSyncTime; }
|
||||
void setPhysicalClockHour(uint8_t hour) { clockConfig.physicalHour = (hour % 12 == 0) ? 12 : hour % 12; }
|
||||
void setPhysicalClockMinute(uint8_t minute) { clockConfig.physicalMinute = minute % 60; }
|
||||
void setNextOutputIsC1(bool isC1) { clockConfig.nextOutputIsC1 = isC1; }
|
||||
void setLastSyncTime(uint32_t timestamp) { clockConfig.lastSyncTime = timestamp; }
|
||||
|
||||
// Alert configuration methods (unchanged)
|
||||
String getAlertType() const { return clockConfig.alertType; }
|
||||
uint16_t getAlertRingInterval() const { return clockConfig.alertRingInterval; }
|
||||
uint8_t getHourBell() const { return clockConfig.hourBell; }
|
||||
uint8_t getHalfBell() const { return clockConfig.halfBell; }
|
||||
uint8_t getQuarterBell() const { return clockConfig.quarterBell; }
|
||||
void setAlertType(const String& type) { clockConfig.alertType = type; }
|
||||
void setAlertRingInterval(uint16_t interval) { clockConfig.alertRingInterval = interval; }
|
||||
void setHourBell(uint8_t bell) { clockConfig.hourBell = bell; }
|
||||
void setHalfBell(uint8_t bell) { clockConfig.halfBell = bell; }
|
||||
void setQuarterBell(uint8_t bell) { clockConfig.quarterBell = bell; }
|
||||
|
||||
// Backlight configuration methods (unchanged)
|
||||
bool getBacklightEnabled() const { return clockConfig.backlight; }
|
||||
uint8_t getBacklightOutput() const { return clockConfig.backlightOutput; }
|
||||
String getBacklightOnTime() const { return clockConfig.backlightOnTime; }
|
||||
String getBacklightOffTime() const { return clockConfig.backlightOffTime; }
|
||||
void setBacklightEnabled(bool enabled) { clockConfig.backlight = enabled; }
|
||||
void setBacklightOutput(uint8_t output) { clockConfig.backlightOutput = output; }
|
||||
void setBacklightOnTime(const String& time) { clockConfig.backlightOnTime = time; }
|
||||
void setBacklightOffTime(const String& time) { clockConfig.backlightOffTime = time; }
|
||||
|
||||
// Silence periods methods (unchanged)
|
||||
bool getDaytimeSilenceEnabled() const { return clockConfig.daytimeSilenceEnabled; }
|
||||
String getDaytimeSilenceOnTime() const { return clockConfig.daytimeSilenceOnTime; }
|
||||
String getDaytimeSilenceOffTime() const { return clockConfig.daytimeSilenceOffTime; }
|
||||
bool getNighttimeSilenceEnabled() const { return clockConfig.nighttimeSilenceEnabled; }
|
||||
String getNighttimeSilenceOnTime() const { return clockConfig.nighttimeSilenceOnTime; }
|
||||
String getNighttimeSilenceOffTime() const { return clockConfig.nighttimeSilenceOffTime; }
|
||||
void setDaytimeSilenceEnabled(bool enabled) { clockConfig.daytimeSilenceEnabled = enabled; }
|
||||
void setDaytimeSilenceOnTime(const String& time) { clockConfig.daytimeSilenceOnTime = time; }
|
||||
void setDaytimeSilenceOffTime(const String& time) { clockConfig.daytimeSilenceOffTime = time; }
|
||||
void setNighttimeSilenceEnabled(bool enabled) { clockConfig.nighttimeSilenceEnabled = enabled; }
|
||||
void setNighttimeSilenceOnTime(const String& time) { clockConfig.nighttimeSilenceOnTime = time; }
|
||||
void setNighttimeSilenceOffTime(const String& time) { clockConfig.nighttimeSilenceOffTime = time; }
|
||||
|
||||
// General Config methods
|
||||
bool setSerialLogLevel(uint8_t level);
|
||||
bool setSdLogLevel(uint8_t level);
|
||||
bool setMqttLogLevel(uint8_t level);
|
||||
uint8_t getSerialLogLevel() const { return generalConfig.serialLogLevel; }
|
||||
uint8_t getSdLogLevel() const { return generalConfig.sdLogLevel; }
|
||||
uint8_t getMqttLogLevel() const { return generalConfig.mqttLogLevel; }
|
||||
void setMqttEnabled(bool enabled) { generalConfig.mqttEnabled = enabled; mqttConfig.enabled = enabled; }
|
||||
bool getMqttEnabled() const { return generalConfig.mqttEnabled; }
|
||||
bool loadGeneralConfig();
|
||||
bool saveGeneralConfig();
|
||||
|
||||
// Other methods (unchanged)
|
||||
void updateClockAlerts(JsonVariant doc);
|
||||
void updateClockBacklight(JsonVariant doc);
|
||||
void updateClockSilence(JsonVariant doc);
|
||||
bool loadClockConfig();
|
||||
bool saveClockConfig();
|
||||
bool loadClockState();
|
||||
bool saveClockState();
|
||||
void updateRealTimeFromCommand(JsonVariant doc);
|
||||
void updatePhysicalClockTimeFromCommand(JsonVariant doc);
|
||||
void saveFileToSD(const char* dirPath, const char* filename, const char* data);
|
||||
String getHardwareVariant() const { return deviceConfig.hwType; }
|
||||
bool loadDeviceConfig();
|
||||
bool saveDeviceConfig();
|
||||
bool loadUpdateServers();
|
||||
std::vector<String> getUpdateServers() const;
|
||||
String getAPSSID() const { return networkConfig.apSsid; }
|
||||
bool isHealthy() const;
|
||||
|
||||
|
||||
/**
|
||||
* @brief Get all configuration settings as a JSON string
|
||||
* @return JSON string containing all current settings
|
||||
*/
|
||||
String getAllSettingsAsJson() const;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// FACTORY RESET
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Perform a full Reset of the Settings to Factory Defaults
|
||||
*
|
||||
* This method:
|
||||
* 1. Clears all user Settings on the SD card
|
||||
* 2. Deletes all Melodies on the SD card
|
||||
*
|
||||
* @return true if reset successful, false otherwise
|
||||
*/
|
||||
bool resetAllToDefaults();
|
||||
|
||||
|
||||
};
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// DEPLOYMENT NOTES:
|
||||
// 2. USER SETTINGS: All loaded from SD card, configurable via app
|
||||
// 3. NETWORK: WiFiManager handles SSIDs/Passwords. IP Settigns loaded from SD, configurable via app
|
||||
// 4. IDENTIFIERS: Auto-generated from deviceUID for consistency
|
||||
// 5. DEFAULTS: Clean minimal defaults, everything configurable
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
@@ -0,0 +1,353 @@
|
||||
#include "FileManager.hpp"
|
||||
|
||||
#define TAG "FileManager"
|
||||
#include "../BuiltInMelodies/BuiltInMelodies.hpp"
|
||||
|
||||
FileManager::FileManager(ConfigManager* config) : configManager(config) {
|
||||
// Constructor - store reference to ConfigManager
|
||||
}
|
||||
|
||||
bool FileManager::initializeSD() {
|
||||
uint8_t sdPin = configManager->getHardwareConfig().sdChipSelect;
|
||||
if (!SD.begin(sdPin)) {
|
||||
LOG_ERROR(TAG, "SD Card initialization failed!");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FileManager::addMelody(JsonVariant doc) {
|
||||
LOG_INFO(TAG, "Adding melody from JSON data...");
|
||||
|
||||
// Extract URL and filename from JSON
|
||||
if (!doc.containsKey("download_url") || !doc.containsKey("melodys_uid")) {
|
||||
LOG_ERROR(TAG, "Missing required parameters: download_url or melodys_uid");
|
||||
return false;
|
||||
}
|
||||
|
||||
const char* url = doc["download_url"];
|
||||
const char* melodyUid = doc["melodys_uid"];
|
||||
|
||||
// Check if this is a built-in melody - skip download if it exists
|
||||
if (BuiltInMelodies::isBuiltInMelody(melodyUid)) {
|
||||
const BuiltInMelodies::MelodyInfo* builtinMelody = BuiltInMelodies::findMelodyByUID(melodyUid);
|
||||
if (builtinMelody != nullptr) {
|
||||
LOG_INFO(TAG, "Melody '%s' is a built-in melody, skipping download", melodyUid);
|
||||
return true; // Success - no download needed
|
||||
}
|
||||
// If starts with builtin_ but not found, log warning and try download anyway
|
||||
LOG_WARNING(TAG, "Melody '%s' has builtin_ prefix but not found in library, attempting download", melodyUid);
|
||||
}
|
||||
|
||||
// Download the melody file to /melodies directory
|
||||
if (downloadFile(url, "/melodies", melodyUid)) {
|
||||
LOG_INFO(TAG, "Melody download successful: %s", melodyUid);
|
||||
return true;
|
||||
}
|
||||
|
||||
LOG_ERROR(TAG, "Melody download failed: %s", melodyUid);
|
||||
return false;
|
||||
}
|
||||
|
||||
bool FileManager::ensureDirectoryExists(const String& dirPath) {
|
||||
if (!initializeSD()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Ensure the directory ends with '/'
|
||||
String normalizedPath = dirPath;
|
||||
if (!normalizedPath.endsWith("/")) {
|
||||
normalizedPath += "/";
|
||||
}
|
||||
|
||||
// Check if directory already exists
|
||||
if (SD.exists(normalizedPath.c_str())) {
|
||||
return true; // Directory already exists, success
|
||||
}
|
||||
|
||||
// Create directory if it doesn't exist
|
||||
return SD.mkdir(normalizedPath.c_str());
|
||||
}
|
||||
|
||||
bool FileManager::downloadFile(const String& url, const String& directory, const String& filename) {
|
||||
LOG_INFO(TAG, "Starting download from: %s", url.c_str());
|
||||
|
||||
// Check if URL is HTTPS
|
||||
bool isHttps = url.startsWith("https://");
|
||||
|
||||
HTTPClient http;
|
||||
WiFiClientSecure* secureClient = nullptr;
|
||||
|
||||
// Configure HTTP client based on protocol
|
||||
if (isHttps) {
|
||||
secureClient = new WiFiClientSecure();
|
||||
secureClient->setInsecure(); // Skip certificate validation for Firebase
|
||||
secureClient->setTimeout(15); // 15 second timeout for TLS operations
|
||||
http.begin(*secureClient, url);
|
||||
LOG_DEBUG(TAG, "Using HTTPS with secure client");
|
||||
} else {
|
||||
http.begin(url);
|
||||
LOG_DEBUG(TAG, "Using HTTP");
|
||||
}
|
||||
|
||||
http.setTimeout(30000); // 30 second timeout for large files
|
||||
http.setFollowRedirects(HTTPC_FORCE_FOLLOW_REDIRECTS); // Follow redirects automatically
|
||||
|
||||
// Disable task watchdog for current task during blocking HTTPS operation
|
||||
// The TLS handshake can take several seconds and would trigger watchdog
|
||||
LOG_DEBUG(TAG, "Disabling watchdog for download...");
|
||||
esp_task_wdt_delete(NULL);
|
||||
|
||||
LOG_DEBUG(TAG, "Sending HTTP GET request...");
|
||||
int httpCode = http.GET();
|
||||
|
||||
// Re-enable task watchdog after HTTP request completes
|
||||
esp_task_wdt_add(NULL);
|
||||
LOG_DEBUG(TAG, "Watchdog re-enabled after HTTP request");
|
||||
|
||||
if (httpCode != HTTP_CODE_OK && httpCode != HTTP_CODE_MOVED_PERMANENTLY && httpCode != HTTP_CODE_FOUND) {
|
||||
LOG_ERROR(TAG, "HTTP GET failed, code: %d, error: %s", httpCode, http.errorToString(httpCode).c_str());
|
||||
http.end();
|
||||
if (secureClient) delete secureClient;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!initializeSD()) {
|
||||
http.end();
|
||||
if (secureClient) delete secureClient;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Ensure directory exists
|
||||
if (!ensureDirectoryExists(directory)) {
|
||||
LOG_ERROR(TAG, "Failed to create directory: %s", directory.c_str());
|
||||
http.end();
|
||||
if (secureClient) delete secureClient;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Build full file path
|
||||
String dirPath = directory;
|
||||
if (!dirPath.endsWith("/")) dirPath += "/";
|
||||
String fullPath = dirPath + filename;
|
||||
|
||||
File file = SD.open(fullPath.c_str(), FILE_WRITE);
|
||||
if (!file) {
|
||||
LOG_ERROR(TAG, "Failed to open file for writing: %s", fullPath.c_str());
|
||||
http.end();
|
||||
if (secureClient) delete secureClient;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Get stream and file size
|
||||
WiFiClient* stream = http.getStreamPtr();
|
||||
int contentLength = http.getSize();
|
||||
LOG_DEBUG(TAG, "Content length: %d bytes", contentLength);
|
||||
|
||||
uint8_t buffer[512]; // Smaller buffer for better responsiveness
|
||||
size_t totalBytes = 0;
|
||||
unsigned long lastYield = millis();
|
||||
unsigned long lastLog = millis();
|
||||
|
||||
// Download with aggressive watchdog feeding
|
||||
while (http.connected() && (contentLength <= 0 || totalBytes < contentLength)) {
|
||||
// Check available data
|
||||
size_t availableSize = stream->available();
|
||||
|
||||
if (availableSize) {
|
||||
// Read available data (up to buffer size)
|
||||
size_t readSize = availableSize > sizeof(buffer) ? sizeof(buffer) : availableSize;
|
||||
int bytesRead = stream->readBytes(buffer, readSize);
|
||||
|
||||
if (bytesRead > 0) {
|
||||
file.write(buffer, bytesRead);
|
||||
totalBytes += bytesRead;
|
||||
|
||||
// Log progress every 5 seconds
|
||||
if (millis() - lastLog > 5000) {
|
||||
LOG_DEBUG(TAG, "Download progress: %u bytes", totalBytes);
|
||||
lastLog = millis();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Aggressive task yielding every 50ms to prevent watchdog timeout
|
||||
if (millis() - lastYield > 50) {
|
||||
yield();
|
||||
vTaskDelay(5 / portTICK_PERIOD_MS); // Let other tasks run (5ms)
|
||||
lastYield = millis();
|
||||
}
|
||||
|
||||
// Exit if no data and connection closed
|
||||
if (!availableSize && !http.connected()) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Yield and small delay if no data available yet
|
||||
if (!availableSize) {
|
||||
yield();
|
||||
vTaskDelay(10 / portTICK_PERIOD_MS);
|
||||
}
|
||||
}
|
||||
|
||||
file.close();
|
||||
http.end();
|
||||
if (secureClient) delete secureClient;
|
||||
LOG_INFO(TAG, "Download complete, file saved to: %s (%u bytes)", fullPath.c_str(), totalBytes);
|
||||
return true;
|
||||
}
|
||||
|
||||
String FileManager::listFilesAsJson(const char* dirPath) {
|
||||
if (!initializeSD()) {
|
||||
LOG_ERROR(TAG, "SD initialization failed");
|
||||
return "{}";
|
||||
}
|
||||
|
||||
File dir = SD.open(dirPath);
|
||||
if (!dir || !dir.isDirectory()) {
|
||||
LOG_ERROR(TAG, "Directory not found: %s", dirPath);
|
||||
return "{}";
|
||||
}
|
||||
|
||||
DynamicJsonDocument doc(1024);
|
||||
JsonArray fileList = doc.createNestedArray("files");
|
||||
|
||||
File file = dir.openNextFile();
|
||||
while (file) {
|
||||
if (!file.isDirectory()) {
|
||||
fileList.add(file.name());
|
||||
}
|
||||
file = dir.openNextFile();
|
||||
}
|
||||
|
||||
String json;
|
||||
serializeJson(doc, json);
|
||||
return json;
|
||||
}
|
||||
|
||||
bool FileManager::fileExists(const String& filePath) {
|
||||
if (!initializeSD()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
File file = SD.open(filePath.c_str());
|
||||
if (file) {
|
||||
file.close();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool FileManager::deleteFile(const String& filePath) {
|
||||
if (!initializeSD()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (SD.remove(filePath.c_str())) {
|
||||
LOG_INFO(TAG, "File deleted: %s", filePath.c_str());
|
||||
return true;
|
||||
} else {
|
||||
LOG_ERROR(TAG, "Failed to delete file: %s", filePath.c_str());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool FileManager::createDirectory(const String& dirPath) {
|
||||
return ensureDirectoryExists(dirPath);
|
||||
}
|
||||
|
||||
size_t FileManager::getFileSize(const String& filePath) {
|
||||
if (!initializeSD()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
File file = SD.open(filePath.c_str());
|
||||
if (!file) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
size_t size = file.size();
|
||||
file.close();
|
||||
return size;
|
||||
}
|
||||
|
||||
bool FileManager::writeJsonFile(const String& filePath, JsonDocument& doc) {
|
||||
if (!initializeSD()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
File file = SD.open(filePath.c_str(), FILE_WRITE);
|
||||
if (!file) {
|
||||
LOG_ERROR(TAG, "Failed to open file for writing: %s", filePath.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
if (serializeJson(doc, file) == 0) {
|
||||
LOG_ERROR(TAG, "Failed to write JSON to file: %s", filePath.c_str());
|
||||
file.close();
|
||||
return false;
|
||||
}
|
||||
|
||||
file.close();
|
||||
LOG_DEBUG(TAG, "JSON file written successfully: %s", filePath.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FileManager::readJsonFile(const String& filePath, JsonDocument& doc) {
|
||||
if (!initializeSD()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
File file = SD.open(filePath.c_str(), FILE_READ);
|
||||
if (!file) {
|
||||
LOG_ERROR(TAG, "Failed to open file for reading: %s", filePath.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
DeserializationError error = deserializeJson(doc, file);
|
||||
file.close();
|
||||
|
||||
if (error) {
|
||||
LOG_ERROR(TAG, "Failed to parse JSON from file: %s, error: %s",
|
||||
filePath.c_str(), error.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
LOG_DEBUG(TAG, "JSON file read successfully: %s", filePath.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// HEALTH CHECK IMPLEMENTATION
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
bool FileManager::isHealthy() const {
|
||||
if (!configManager) {
|
||||
LOG_DEBUG(TAG, "FileManager: Unhealthy - ConfigManager not available");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Use SD.cardType() as a lightweight presence check — avoids calling SD.begin()
|
||||
// on every health poll (which is expensive and crashes without a card inserted).
|
||||
if (SD.cardType() == CARD_NONE) {
|
||||
LOG_DEBUG(TAG, "FileManager: Unhealthy - SD Card initialization failed");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FileManager::appendLine(const String& filePath, const String& line) {
|
||||
if (!initializeSD()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
File file = SD.open(filePath.c_str(), FILE_APPEND);
|
||||
if (!file) {
|
||||
return false;
|
||||
}
|
||||
|
||||
file.println(line);
|
||||
file.close();
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* FILEMANAGER.HPP - SD Card and File Operations Manager
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 📁 THE FILE SYSTEM ORCHESTRATOR OF VESPER 📁
|
||||
*
|
||||
* This class provides a clean, robust interface for all file operations
|
||||
* including melody file management, configuration persistence, and
|
||||
* comprehensive error handling with automatic recovery.
|
||||
*
|
||||
* 📋 VERSION: 2.0 (Enhanced file management)
|
||||
* 📅 DATE: 2025
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#ifndef FILEMANAGER_HPP
|
||||
#define FILEMANAGER_HPP
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <SD.h>
|
||||
#include <HTTPClient.h>
|
||||
#include <WiFiClient.h>
|
||||
#include <WiFiClientSecure.h>
|
||||
#include <ArduinoJson.h>
|
||||
#include <esp_task_wdt.h>
|
||||
#include "../Logging/Logging.hpp"
|
||||
#include "../ConfigManager/ConfigManager.hpp"
|
||||
|
||||
class FileManager {
|
||||
private:
|
||||
ConfigManager* configManager;
|
||||
|
||||
public:
|
||||
// Constructor
|
||||
FileManager(ConfigManager* config);
|
||||
|
||||
// Core file operations
|
||||
bool downloadFile(const String& url, const String& directory, const String& filename);
|
||||
bool addMelody(JsonVariant doc); // Download melody file from JSON data
|
||||
String listFilesAsJson(const char* dirPath);
|
||||
|
||||
// File utilities
|
||||
bool fileExists(const String& filePath);
|
||||
bool deleteFile(const String& filePath);
|
||||
bool createDirectory(const String& dirPath);
|
||||
size_t getFileSize(const String& filePath);
|
||||
|
||||
// Generic read/write for JSON data
|
||||
bool writeJsonFile(const String& filePath, JsonDocument& doc);
|
||||
bool readJsonFile(const String& filePath, JsonDocument& doc);
|
||||
|
||||
// Append a single text line to a file (used by SD log channel)
|
||||
bool appendLine(const String& filePath, const String& line);
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// HEALTH CHECK METHOD
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/** @brief Check if FileManager is in healthy state */
|
||||
bool isHealthy() const;
|
||||
|
||||
private:
|
||||
// Helper functions
|
||||
bool initializeSD();
|
||||
bool ensureDirectoryExists(const String& dirPath);
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,701 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* FIRMWAREVALIDATOR.CPP - Bulletproof Firmware Update Validation Implementation
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#include "FirmwareValidator.hpp"
|
||||
|
||||
#define TAG "FirmwareValidator"
|
||||
#include "../HealthMonitor/HealthMonitor.hpp"
|
||||
#include "../ConfigManager/ConfigManager.hpp"
|
||||
#include <esp_task_wdt.h>
|
||||
#include <esp_image_format.h>
|
||||
#include <ArduinoJson.h>
|
||||
|
||||
// NVS keys for persistent validation state
|
||||
static const char* NVS_NAMESPACE = "fw_validator";
|
||||
static const char* NVS_STATE_KEY = "val_state";
|
||||
static const char* NVS_BOOT_COUNT_KEY = "boot_count";
|
||||
static const char* NVS_RETRY_COUNT_KEY = "retry_count";
|
||||
static const char* NVS_FAILURE_COUNT_KEY = "fail_count";
|
||||
static const char* NVS_LAST_BOOT_KEY = "last_boot";
|
||||
|
||||
FirmwareValidator::FirmwareValidator() {
|
||||
// Initialize default configuration
|
||||
_config = ValidationConfig();
|
||||
}
|
||||
|
||||
FirmwareValidator::~FirmwareValidator() {
|
||||
// Clean up resources
|
||||
if (_validationTimer) {
|
||||
xTimerDelete(_validationTimer, portMAX_DELAY);
|
||||
_validationTimer = nullptr;
|
||||
}
|
||||
|
||||
if (_monitoringTask) {
|
||||
vTaskDelete(_monitoringTask);
|
||||
_monitoringTask = nullptr;
|
||||
}
|
||||
|
||||
if (_nvsHandle) {
|
||||
nvs_close(_nvsHandle);
|
||||
_nvsHandle = 0;
|
||||
}
|
||||
}
|
||||
|
||||
bool FirmwareValidator::begin(HealthMonitor* healthMonitor, ConfigManager* configManager) {
|
||||
LOG_INFO(TAG, "🛡️ Initializing Firmware Validator System");
|
||||
|
||||
_healthMonitor = healthMonitor;
|
||||
_configManager = configManager;
|
||||
|
||||
// Initialize NVS for persistent state storage
|
||||
if (!initializeNVS()) {
|
||||
LOG_ERROR(TAG, "❌ Failed to initialize NVS for firmware validation");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Initialize ESP32 partition information
|
||||
if (!initializePartitions()) {
|
||||
LOG_ERROR(TAG, "❌ Failed to initialize ESP32 partitions");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Load previous validation state
|
||||
loadValidationState();
|
||||
|
||||
LOG_INFO(TAG, "✅ Firmware Validator initialized");
|
||||
LOG_INFO(TAG, "📍 Running partition: %s", getPartitionLabel(_runningPartition).c_str());
|
||||
LOG_INFO(TAG, "📍 Backup partition: %s", getPartitionLabel(_backupPartition).c_str());
|
||||
LOG_INFO(TAG, "🔄 Validation state: %s", validationStateToString(_validationState).c_str());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FirmwareValidator::performStartupValidation() {
|
||||
LOG_INFO(TAG, "🚀 Starting firmware startup validation...");
|
||||
|
||||
// Check if this is a new firmware that needs validation
|
||||
const esp_partition_t* bootPartition = esp_ota_get_boot_partition();
|
||||
const esp_partition_t* runningPartition = esp_ota_get_running_partition();
|
||||
|
||||
if (bootPartition != runningPartition) {
|
||||
LOG_WARNING(TAG, "⚠️ Boot partition differs from running partition!");
|
||||
LOG_WARNING(TAG, " Boot: %s", getPartitionLabel(bootPartition).c_str());
|
||||
LOG_WARNING(TAG, " Running: %s", getPartitionLabel(runningPartition).c_str());
|
||||
}
|
||||
|
||||
// Increment boot count for this session
|
||||
incrementBootCount();
|
||||
|
||||
// Check if we need to validate new firmware
|
||||
if (_validationState == FirmwareValidationState::UNKNOWN) {
|
||||
// First boot of potentially new firmware
|
||||
_validationState = FirmwareValidationState::STARTUP_PENDING;
|
||||
LOG_INFO(TAG, "🆕 New firmware detected - entering validation mode");
|
||||
}
|
||||
|
||||
if (_validationState == FirmwareValidationState::STARTUP_PENDING) {
|
||||
LOG_INFO(TAG, "🔍 Performing startup validation...");
|
||||
_validationState = FirmwareValidationState::STARTUP_RUNNING;
|
||||
_validationStartTime = millis();
|
||||
|
||||
// Perform basic health checks with timeout protection
|
||||
unsigned long startTime = millis();
|
||||
bool healthCheckPassed = false;
|
||||
|
||||
while ((millis() - startTime) < _config.startupTimeoutMs) {
|
||||
healthCheckPassed = performBasicHealthCheck();
|
||||
if (healthCheckPassed) {
|
||||
break;
|
||||
}
|
||||
|
||||
LOG_WARNING(TAG, "⚠️ Startup health check failed, retrying...");
|
||||
delay(1000); // Wait 1 second before retry
|
||||
}
|
||||
|
||||
if (healthCheckPassed) {
|
||||
_validationState = FirmwareValidationState::RUNTIME_TESTING;
|
||||
_startupRetryCount = 0; // Reset retry count on success
|
||||
saveValidationState();
|
||||
LOG_INFO(TAG, "✅ Firmware startup validation PASSED - proceeding with initialization");
|
||||
return true;
|
||||
} else {
|
||||
LOG_ERROR(TAG, "❌ Startup validation FAILED after %lu ms", _config.startupTimeoutMs);
|
||||
_startupRetryCount++;
|
||||
|
||||
if (_startupRetryCount >= _config.maxStartupRetries) {
|
||||
LOG_ERROR(TAG, "💥 Maximum startup retries exceeded - triggering rollback");
|
||||
handleValidationFailure("Startup validation failed repeatedly");
|
||||
return false; // This will trigger rollback and reboot
|
||||
} else {
|
||||
LOG_WARNING(TAG, "🔄 Startup retry %d/%d - rebooting...",
|
||||
_startupRetryCount, _config.maxStartupRetries);
|
||||
saveValidationState();
|
||||
delay(1000);
|
||||
ESP.restart();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} else if (_validationState == FirmwareValidationState::VALIDATED) {
|
||||
LOG_INFO(TAG, "✅ Firmware already validated - normal operation");
|
||||
return true;
|
||||
} else if (_validationState == FirmwareValidationState::STARTUP_RUNNING) {
|
||||
// Handle interrupted validation from previous boot
|
||||
LOG_INFO(TAG, "🔄 Resuming interrupted validation - transitioning to runtime testing");
|
||||
_validationState = FirmwareValidationState::RUNTIME_TESTING;
|
||||
saveValidationState();
|
||||
return true;
|
||||
} else if (_validationState == FirmwareValidationState::RUNTIME_TESTING) {
|
||||
// Already in runtime testing from previous boot
|
||||
LOG_INFO(TAG, "🔄 Continuing runtime validation from previous session");
|
||||
return true;
|
||||
} else {
|
||||
LOG_WARNING(TAG, "⚠️ Unexpected validation state: %s",
|
||||
validationStateToString(_validationState).c_str());
|
||||
return true; // Continue anyway
|
||||
}
|
||||
}
|
||||
|
||||
void FirmwareValidator::startRuntimeValidation() {
|
||||
if (_validationState != FirmwareValidationState::RUNTIME_TESTING) {
|
||||
LOG_WARNING(TAG, "⚠️ Runtime validation called in wrong state: %s",
|
||||
validationStateToString(_validationState).c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
LOG_INFO(TAG, "🏃 Starting extended runtime validation (%lu ms timeout)",
|
||||
_config.runtimeTimeoutMs);
|
||||
|
||||
_validationStartTime = millis();
|
||||
|
||||
// Create validation timer
|
||||
_validationTimer = xTimerCreate(
|
||||
"FW_Validation",
|
||||
pdMS_TO_TICKS(_config.runtimeTimeoutMs),
|
||||
pdFALSE, // One-shot timer
|
||||
this,
|
||||
validationTimerCallback
|
||||
);
|
||||
|
||||
if (_validationTimer) {
|
||||
xTimerStart(_validationTimer, 0);
|
||||
} else {
|
||||
LOG_ERROR(TAG, "❌ Failed to create validation timer");
|
||||
handleValidationFailure("Timer creation failed");
|
||||
return;
|
||||
}
|
||||
|
||||
// Create monitoring task for continuous health checks
|
||||
xTaskCreatePinnedToCore(
|
||||
monitoringTaskFunction,
|
||||
"FW_Monitor",
|
||||
4096,
|
||||
this,
|
||||
4, // Higher priority than health monitor
|
||||
&_monitoringTask,
|
||||
0 // Core 0
|
||||
);
|
||||
|
||||
if (!_monitoringTask) {
|
||||
LOG_ERROR(TAG, "❌ Failed to create monitoring task");
|
||||
handleValidationFailure("Monitoring task creation failed");
|
||||
return;
|
||||
}
|
||||
|
||||
// Setup watchdog if enabled
|
||||
if (_config.enableWatchdog) {
|
||||
setupWatchdog();
|
||||
}
|
||||
|
||||
LOG_INFO(TAG, "✅ Runtime validation started - monitoring system health...");
|
||||
}
|
||||
|
||||
void FirmwareValidator::commitFirmware() {
|
||||
if (_validationState == FirmwareValidationState::VALIDATED) {
|
||||
LOG_INFO(TAG, "✅ Firmware already committed");
|
||||
return;
|
||||
}
|
||||
|
||||
LOG_INFO(TAG, "💾 Committing firmware as valid and stable...");
|
||||
|
||||
// Mark current partition as valid boot partition
|
||||
esp_err_t err = esp_ota_set_boot_partition(_runningPartition);
|
||||
if (err != ESP_OK) {
|
||||
LOG_ERROR(TAG, "❌ Failed to set boot partition: %s", esp_err_to_name(err));
|
||||
return;
|
||||
}
|
||||
|
||||
_validationState = FirmwareValidationState::VALIDATED;
|
||||
resetValidationCounters();
|
||||
saveValidationState();
|
||||
|
||||
// Clean up validation resources
|
||||
if (_validationTimer) {
|
||||
xTimerDelete(_validationTimer, portMAX_DELAY);
|
||||
_validationTimer = nullptr;
|
||||
}
|
||||
|
||||
if (_monitoringTask) {
|
||||
vTaskDelete(_monitoringTask);
|
||||
_monitoringTask = nullptr;
|
||||
}
|
||||
|
||||
LOG_INFO(TAG, "🎉 Firmware successfully committed! System is now stable.");
|
||||
}
|
||||
|
||||
void FirmwareValidator::rollbackFirmware() {
|
||||
LOG_WARNING(TAG, "🔄 Manual firmware rollback requested");
|
||||
handleValidationFailure("Manual rollback requested");
|
||||
}
|
||||
|
||||
// ... [rest of implementation continues with all the private methods] ...
|
||||
|
||||
bool FirmwareValidator::initializeNVS() {
|
||||
esp_err_t err = nvs_flash_init();
|
||||
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
|
||||
ESP_ERROR_CHECK(nvs_flash_erase());
|
||||
err = nvs_flash_init();
|
||||
}
|
||||
|
||||
if (err != ESP_OK) {
|
||||
LOG_ERROR(TAG, "❌ Failed to initialize NVS flash: %s", esp_err_to_name(err));
|
||||
return false;
|
||||
}
|
||||
|
||||
err = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &_nvsHandle);
|
||||
if (err != ESP_OK) {
|
||||
LOG_ERROR(TAG, "❌ Failed to open NVS namespace: %s", esp_err_to_name(err));
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void FirmwareValidator::loadValidationState() {
|
||||
esp_err_t err;
|
||||
|
||||
// Load validation state
|
||||
uint8_t state = static_cast<uint8_t>(FirmwareValidationState::UNKNOWN);
|
||||
err = nvs_get_u8(_nvsHandle, NVS_STATE_KEY, &state);
|
||||
if (err == ESP_OK) {
|
||||
_validationState = static_cast<FirmwareValidationState>(state);
|
||||
LOG_DEBUG(TAG, "📖 NVS validation state found: %s", validationStateToString(_validationState).c_str());
|
||||
} else {
|
||||
LOG_DEBUG(TAG, "📖 No NVS validation state found, using UNKNOWN (error: %s)", esp_err_to_name(err));
|
||||
_validationState = FirmwareValidationState::UNKNOWN;
|
||||
}
|
||||
|
||||
// Load retry counts
|
||||
nvs_get_u8(_nvsHandle, NVS_RETRY_COUNT_KEY, &_startupRetryCount);
|
||||
nvs_get_u8(_nvsHandle, NVS_FAILURE_COUNT_KEY, &_runtimeFailureCount);
|
||||
|
||||
LOG_DEBUG(TAG, "📖 Loaded validation state: %s (retries: %d, failures: %d)",
|
||||
validationStateToString(_validationState).c_str(),
|
||||
_startupRetryCount, _runtimeFailureCount);
|
||||
}
|
||||
|
||||
void FirmwareValidator::saveValidationState() {
|
||||
esp_err_t err;
|
||||
|
||||
// Save validation state
|
||||
err = nvs_set_u8(_nvsHandle, NVS_STATE_KEY, static_cast<uint8_t>(_validationState));
|
||||
if (err != ESP_OK) {
|
||||
LOG_ERROR(TAG, "❌ Failed to save validation state: %s", esp_err_to_name(err));
|
||||
}
|
||||
|
||||
// Save retry counts
|
||||
nvs_set_u8(_nvsHandle, NVS_RETRY_COUNT_KEY, _startupRetryCount);
|
||||
nvs_set_u8(_nvsHandle, NVS_FAILURE_COUNT_KEY, _runtimeFailureCount);
|
||||
|
||||
// Save timestamp
|
||||
unsigned long currentTime = millis();
|
||||
nvs_set_u32(_nvsHandle, NVS_LAST_BOOT_KEY, currentTime);
|
||||
|
||||
// Commit changes
|
||||
err = nvs_commit(_nvsHandle);
|
||||
if (err != ESP_OK) {
|
||||
LOG_ERROR(TAG, "❌ Failed to commit NVS changes: %s", esp_err_to_name(err));
|
||||
}
|
||||
|
||||
LOG_DEBUG(TAG, "💾 Saved validation state: %s", validationStateToString(_validationState).c_str());
|
||||
}
|
||||
|
||||
bool FirmwareValidator::initializePartitions() {
|
||||
_runningPartition = esp_ota_get_running_partition();
|
||||
if (!_runningPartition) {
|
||||
LOG_ERROR(TAG, "❌ Failed to get running partition");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Find the other OTA partition (backup)
|
||||
esp_partition_iterator_t iterator = esp_partition_find(ESP_PARTITION_TYPE_APP,
|
||||
ESP_PARTITION_SUBTYPE_APP_OTA_0, NULL);
|
||||
if (iterator) {
|
||||
const esp_partition_t* ota0 = esp_partition_get(iterator);
|
||||
esp_partition_iterator_release(iterator);
|
||||
|
||||
iterator = esp_partition_find(ESP_PARTITION_TYPE_APP,
|
||||
ESP_PARTITION_SUBTYPE_APP_OTA_1, NULL);
|
||||
if (iterator) {
|
||||
const esp_partition_t* ota1 = esp_partition_get(iterator);
|
||||
esp_partition_iterator_release(iterator);
|
||||
|
||||
// Determine which is the backup partition
|
||||
if (_runningPartition == ota0) {
|
||||
_backupPartition = ota1;
|
||||
} else {
|
||||
_backupPartition = ota0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!_backupPartition) {
|
||||
LOG_ERROR(TAG, "❌ Failed to find backup partition");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FirmwareValidator::performBasicHealthCheck() {
|
||||
LOG_VERBOSE(TAG, "🔍 Performing basic startup health check...");
|
||||
|
||||
// Check if health monitor is available
|
||||
if (!_healthMonitor) {
|
||||
LOG_ERROR(TAG, "❌ Health monitor not available");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check hardware-critical subsystems only.
|
||||
// SD-dependent systems (ConfigManager, FileManager) are excluded: SD absence
|
||||
// means config defaults are used, but hardware is still functional.
|
||||
bool bellEngineOk = (_healthMonitor->checkSubsystemHealth("BellEngine") == HealthStatus::HEALTHY);
|
||||
bool outputManagerOk = (_healthMonitor->checkSubsystemHealth("OutputManager") == HealthStatus::HEALTHY);
|
||||
|
||||
bool basicHealthOk = bellEngineOk && outputManagerOk;
|
||||
|
||||
if (!basicHealthOk) {
|
||||
LOG_ERROR(TAG, "❌ Basic health check failed:");
|
||||
if (!bellEngineOk) LOG_ERROR(TAG, " - BellEngine: FAILED");
|
||||
if (!outputManagerOk) LOG_ERROR(TAG, " - OutputManager: FAILED");
|
||||
} else {
|
||||
LOG_VERBOSE(TAG, "✅ Basic health check passed");
|
||||
}
|
||||
|
||||
return basicHealthOk;
|
||||
}
|
||||
|
||||
bool FirmwareValidator::performRuntimeHealthCheck() {
|
||||
LOG_VERBOSE(TAG, "🔍 Performing comprehensive runtime health check...");
|
||||
|
||||
if (!_healthMonitor) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Perform full health check
|
||||
HealthStatus overallHealth = _healthMonitor->performFullHealthCheck();
|
||||
uint8_t criticalFailures = _healthMonitor->getCriticalFailureCount();
|
||||
|
||||
bool runtimeHealthOk = (overallHealth == HealthStatus::HEALTHY || overallHealth == HealthStatus::WARNING)
|
||||
&& (criticalFailures == 0);
|
||||
|
||||
if (!runtimeHealthOk) {
|
||||
LOG_WARNING(TAG, "⚠️ Runtime health check failed - Critical failures: %d, Overall: %s",
|
||||
criticalFailures,
|
||||
(overallHealth == HealthStatus::HEALTHY) ? "HEALTHY" :
|
||||
(overallHealth == HealthStatus::WARNING) ? "WARNING" :
|
||||
(overallHealth == HealthStatus::CRITICAL) ? "CRITICAL" : "FAILED");
|
||||
}
|
||||
|
||||
return runtimeHealthOk;
|
||||
}
|
||||
|
||||
void FirmwareValidator::validationTimerCallback(TimerHandle_t timer) {
|
||||
// This runs in the FreeRTOS timer service task (Tmr Svc) which has a small stack.
|
||||
// Do NOT call commitFirmware() here — just set a flag and let the monitoring task commit.
|
||||
FirmwareValidator* validator = static_cast<FirmwareValidator*>(pvTimerGetTimerID(timer));
|
||||
validator->_commitPending = true;
|
||||
}
|
||||
|
||||
void FirmwareValidator::monitoringTaskFunction(void* parameter) {
|
||||
FirmwareValidator* validator = static_cast<FirmwareValidator*>(parameter);
|
||||
LOG_INFO(TAG, "🔍 Firmware validation monitoring task started on Core %d", xPortGetCoreID());
|
||||
|
||||
validator->monitoringLoop();
|
||||
|
||||
// Task should not reach here normally
|
||||
LOG_WARNING(TAG, "⚠️ Firmware validation monitoring task ended unexpectedly");
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
void FirmwareValidator::monitoringLoop() {
|
||||
while (_validationState == FirmwareValidationState::RUNTIME_TESTING) {
|
||||
// Check if the validation timer fired — commit from here (not from Tmr Svc callback)
|
||||
if (_commitPending) {
|
||||
_commitPending = false;
|
||||
LOG_INFO(TAG, "⏰ Runtime validation timeout reached - committing firmware");
|
||||
handleValidationSuccess();
|
||||
return;
|
||||
}
|
||||
|
||||
// Feed watchdog if enabled
|
||||
if (_config.enableWatchdog) {
|
||||
feedWatchdog();
|
||||
}
|
||||
|
||||
// Perform runtime health check
|
||||
bool healthOk = performRuntimeHealthCheck();
|
||||
|
||||
if (!healthOk) {
|
||||
_runtimeFailureCount++;
|
||||
LOG_WARNING(TAG, "⚠️ Runtime health check failed (%d/%d failures)",
|
||||
_runtimeFailureCount, _config.maxRuntimeFailures);
|
||||
|
||||
if (_runtimeFailureCount >= _config.maxRuntimeFailures) {
|
||||
LOG_ERROR(TAG, "💥 Maximum runtime failures exceeded - triggering rollback");
|
||||
handleValidationFailure("Too many runtime health check failures");
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
// Reset failure count on successful health check
|
||||
if (_runtimeFailureCount > 0) {
|
||||
_runtimeFailureCount = 0;
|
||||
LOG_INFO(TAG, "✅ Runtime health recovered - reset failure count");
|
||||
}
|
||||
}
|
||||
|
||||
// Wait before next health check
|
||||
vTaskDelay(pdMS_TO_TICKS(_config.healthCheckIntervalMs));
|
||||
}
|
||||
}
|
||||
|
||||
void FirmwareValidator::handleValidationSuccess() {
|
||||
LOG_INFO(TAG, "🎉 Firmware validation completed successfully!");
|
||||
commitFirmware();
|
||||
}
|
||||
|
||||
void FirmwareValidator::handleValidationFailure(const String& reason) {
|
||||
LOG_ERROR(TAG, "💥 Firmware validation FAILED: %s", reason.c_str());
|
||||
LOG_ERROR(TAG, "🔄 Initiating firmware rollback...");
|
||||
|
||||
_validationState = FirmwareValidationState::FAILED_RUNTIME;
|
||||
saveValidationState();
|
||||
|
||||
executeRollback();
|
||||
}
|
||||
|
||||
void FirmwareValidator::executeRollback() {
|
||||
LOG_WARNING(TAG, "🔄 Executing firmware rollback to previous version...");
|
||||
|
||||
// Clean up validation resources first
|
||||
if (_validationTimer) {
|
||||
xTimerDelete(_validationTimer, portMAX_DELAY);
|
||||
_validationTimer = nullptr;
|
||||
}
|
||||
|
||||
if (_monitoringTask) {
|
||||
vTaskDelete(_monitoringTask);
|
||||
_monitoringTask = nullptr;
|
||||
}
|
||||
|
||||
// Mark current firmware as invalid and rollback
|
||||
esp_err_t err = esp_ota_mark_app_invalid_rollback_and_reboot();
|
||||
|
||||
if (err != ESP_OK) {
|
||||
LOG_ERROR(TAG, "❌ Failed to rollback firmware: %s", esp_err_to_name(err));
|
||||
LOG_ERROR(TAG, "💀 System may be in unstable state - manual intervention required");
|
||||
|
||||
// If rollback fails, try manual reboot to backup partition
|
||||
LOG_WARNING(TAG, "🆘 Attempting manual reboot to backup partition...");
|
||||
|
||||
if (_backupPartition) {
|
||||
esp_ota_set_boot_partition(_backupPartition);
|
||||
delay(1000);
|
||||
ESP.restart();
|
||||
} else {
|
||||
LOG_ERROR(TAG, "💀 No backup partition available - system halt");
|
||||
while(1) {
|
||||
delay(1000); // Hang here to prevent further damage
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// This point should not be reached as the device should reboot
|
||||
LOG_ERROR(TAG, "💀 Rollback function returned unexpectedly");
|
||||
}
|
||||
|
||||
FirmwareInfo FirmwareValidator::getCurrentFirmwareInfo() const {
|
||||
FirmwareInfo info;
|
||||
|
||||
if (_configManager) {
|
||||
info.version = _configManager->getFwVersion();
|
||||
info.buildDate = __DATE__ " " __TIME__;
|
||||
// Add more info as needed
|
||||
}
|
||||
|
||||
info.isValid = (_validationState == FirmwareValidationState::VALIDATED);
|
||||
info.isTesting = isInTestingMode();
|
||||
info.bootCount = getBootCount();
|
||||
info.lastBootTime = millis();
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
FirmwareInfo FirmwareValidator::getBackupFirmwareInfo() const {
|
||||
FirmwareInfo info;
|
||||
|
||||
// This would require reading partition metadata
|
||||
// For now, return basic info
|
||||
info.version = "Unknown";
|
||||
info.isValid = isPartitionValid(_backupPartition);
|
||||
info.isTesting = false;
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
bool FirmwareValidator::isHealthy() const {
|
||||
// Check if validator itself is in a good state
|
||||
bool nvsOk = (_nvsHandle != 0);
|
||||
bool partitionsOk = (_runningPartition != nullptr && _backupPartition != nullptr);
|
||||
bool dependenciesOk = (_healthMonitor != nullptr && _configManager != nullptr);
|
||||
bool stateOk = (_validationState != FirmwareValidationState::FAILED_STARTUP &&
|
||||
_validationState != FirmwareValidationState::FAILED_RUNTIME);
|
||||
|
||||
return nvsOk && partitionsOk && dependenciesOk && stateOk;
|
||||
}
|
||||
|
||||
const esp_partition_t* FirmwareValidator::getRunningPartition() const {
|
||||
return _runningPartition;
|
||||
}
|
||||
|
||||
const esp_partition_t* FirmwareValidator::getBackupPartition() const {
|
||||
return _backupPartition;
|
||||
}
|
||||
|
||||
bool FirmwareValidator::isNewFirmwarePending() const {
|
||||
// Check if there's a new firmware in the backup partition that hasn't been tested
|
||||
return (_validationState == FirmwareValidationState::STARTUP_PENDING ||
|
||||
_validationState == FirmwareValidationState::STARTUP_RUNNING ||
|
||||
_validationState == FirmwareValidationState::RUNTIME_TESTING);
|
||||
}
|
||||
|
||||
String FirmwareValidator::validationStateToString(FirmwareValidationState state) const {
|
||||
switch (state) {
|
||||
case FirmwareValidationState::UNKNOWN:
|
||||
return "UNKNOWN";
|
||||
case FirmwareValidationState::STARTUP_PENDING:
|
||||
return "STARTUP_PENDING";
|
||||
case FirmwareValidationState::STARTUP_RUNNING:
|
||||
return "STARTUP_RUNNING";
|
||||
case FirmwareValidationState::RUNTIME_TESTING:
|
||||
return "RUNTIME_TESTING";
|
||||
case FirmwareValidationState::VALIDATED:
|
||||
return "VALIDATED";
|
||||
case FirmwareValidationState::FAILED_STARTUP:
|
||||
return "FAILED_STARTUP";
|
||||
case FirmwareValidationState::FAILED_RUNTIME:
|
||||
return "FAILED_RUNTIME";
|
||||
case FirmwareValidationState::ROLLED_BACK:
|
||||
return "ROLLED_BACK";
|
||||
default:
|
||||
return "INVALID";
|
||||
}
|
||||
}
|
||||
|
||||
String FirmwareValidator::getPartitionLabel(const esp_partition_t* partition) const {
|
||||
if (!partition) {
|
||||
return "NULL";
|
||||
}
|
||||
|
||||
String label = String(partition->label);
|
||||
if (label.isEmpty()) {
|
||||
// Generate label based on subtype
|
||||
switch (partition->subtype) {
|
||||
case ESP_PARTITION_SUBTYPE_APP_OTA_0:
|
||||
label = "ota_0";
|
||||
break;
|
||||
case ESP_PARTITION_SUBTYPE_APP_OTA_1:
|
||||
label = "ota_1";
|
||||
break;
|
||||
default:
|
||||
label = "app_" + String(partition->subtype);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return label;
|
||||
}
|
||||
|
||||
bool FirmwareValidator::isPartitionValid(const esp_partition_t* partition) const {
|
||||
if (!partition) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if partition has valid app header
|
||||
esp_image_header_t header;
|
||||
esp_err_t err = esp_partition_read(partition, 0, &header, sizeof(header));
|
||||
|
||||
if (err != ESP_OK) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check magic number
|
||||
return (header.magic == ESP_IMAGE_HEADER_MAGIC);
|
||||
}
|
||||
|
||||
unsigned long FirmwareValidator::getBootCount() const {
|
||||
uint32_t bootCount = 0;
|
||||
nvs_get_u32(_nvsHandle, NVS_BOOT_COUNT_KEY, &bootCount);
|
||||
return bootCount;
|
||||
}
|
||||
|
||||
void FirmwareValidator::incrementBootCount() {
|
||||
uint32_t bootCount = getBootCount();
|
||||
bootCount++;
|
||||
nvs_set_u32(_nvsHandle, NVS_BOOT_COUNT_KEY, bootCount);
|
||||
nvs_commit(_nvsHandle);
|
||||
|
||||
LOG_DEBUG(TAG, "📊 Boot count: %lu", bootCount);
|
||||
}
|
||||
|
||||
void FirmwareValidator::resetValidationCounters() {
|
||||
_startupRetryCount = 0;
|
||||
_runtimeFailureCount = 0;
|
||||
|
||||
// Also reset in NVS
|
||||
nvs_set_u8(_nvsHandle, NVS_RETRY_COUNT_KEY, 0);
|
||||
nvs_set_u8(_nvsHandle, NVS_FAILURE_COUNT_KEY, 0);
|
||||
nvs_commit(_nvsHandle);
|
||||
|
||||
LOG_DEBUG(TAG, "🔄 Reset validation counters");
|
||||
}
|
||||
|
||||
void FirmwareValidator::setupWatchdog() {
|
||||
// Check if watchdog is already initialized
|
||||
// Use IDF v4 API: esp_task_wdt_init(timeout_seconds, panic_on_timeout)
|
||||
uint32_t timeoutSec = (_config.watchdogTimeoutMs + 999) / 1000; // ms → seconds, round up
|
||||
esp_err_t err = esp_task_wdt_init(timeoutSec, true);
|
||||
if (err == ESP_ERR_INVALID_STATE) {
|
||||
LOG_DEBUG(TAG, "🐕 Watchdog already initialized - skipping init");
|
||||
} else if (err != ESP_OK) {
|
||||
LOG_WARNING(TAG, "⚠️ Failed to initialize task watchdog: %s", esp_err_to_name(err));
|
||||
return;
|
||||
}
|
||||
|
||||
// Try to add current task to watchdog
|
||||
err = esp_task_wdt_add(NULL);
|
||||
if (err == ESP_ERR_INVALID_ARG) {
|
||||
LOG_DEBUG(TAG, "🐕 Task already added to watchdog");
|
||||
} else if (err != ESP_OK) {
|
||||
LOG_WARNING(TAG, "⚠️ Failed to add task to watchdog: %s", esp_err_to_name(err));
|
||||
return;
|
||||
}
|
||||
|
||||
LOG_INFO(TAG, "🐕 Watchdog enabled with %lu second timeout", _config.watchdogTimeoutMs / 1000);
|
||||
}
|
||||
|
||||
void FirmwareValidator::feedWatchdog() {
|
||||
esp_task_wdt_reset();
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* FIRMWAREVALIDATOR.HPP - Bulletproof Firmware Update Validation System
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 🛡️ THE FIRMWARE SAFETY GUARDIAN OF VESPER 🛡️
|
||||
*
|
||||
* This class implements a bulletproof firmware update system using ESP32's dual
|
||||
* partition architecture. It ensures that firmware updates are safe, validated,
|
||||
* and can automatically rollback if critical systems fail during startup or runtime.
|
||||
*
|
||||
* 🏗️ ARCHITECTURE:
|
||||
* • Dual partition management (OTA_0 and OTA_1)
|
||||
* • Immediate startup health checks within first few seconds
|
||||
* • Progressive validation from basic → comprehensive health checks
|
||||
* • Automatic rollback to previous working firmware on critical failures
|
||||
* • Testing mode for new firmware validation
|
||||
* • Permanent commit only after full health validation
|
||||
*
|
||||
* 🔄 FIRMWARE UPDATE FLOW:
|
||||
* 1. Download new firmware to inactive partition
|
||||
* 2. Boot new firmware in "TESTING" mode
|
||||
* 3. Immediate basic health check (within 10 seconds)
|
||||
* - If FAIL → Automatic rollback via esp_ota_mark_app_invalid_rollback_and_reboot()
|
||||
* 4. Extended validation period (configurable, default 5 minutes)
|
||||
* - Continuous health monitoring of all critical subsystems
|
||||
* - If PASS → Mark partition as valid via esp_ota_set_boot_partition()
|
||||
* - If FAIL → Rollback to previous firmware
|
||||
* 5. Normal operation mode
|
||||
*
|
||||
* 🚨 SAFETY MECHANISMS:
|
||||
* • Watchdog integration to handle complete system hangs
|
||||
* • Multi-level health checks (startup → runtime → comprehensive)
|
||||
* • Configurable validation timeouts and retry counts
|
||||
* • Persistent validation state tracking
|
||||
* • Emergency rollback triggers
|
||||
*
|
||||
* 🔍 VALIDATION LEVELS:
|
||||
* • STARTUP: Basic system initialization (I2C, SD, GPIO)
|
||||
* • RUNTIME: Core functionality (BellEngine, OutputManager, Player)
|
||||
* • COMPREHENSIVE: Full system health (Network, MQTT, Telemetry)
|
||||
*
|
||||
* 📋 VERSION: 1.0 (Initial firmware validation system)
|
||||
* 📅 DATE: 2025
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <esp_ota_ops.h>
|
||||
#include <esp_partition.h>
|
||||
#include <nvs_flash.h>
|
||||
#include <nvs.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/task.h>
|
||||
#include <freertos/timers.h>
|
||||
#include "../Logging/Logging.hpp"
|
||||
|
||||
// Forward declarations
|
||||
class HealthMonitor;
|
||||
class ConfigManager;
|
||||
|
||||
/**
|
||||
* @enum FirmwareValidationState
|
||||
* @brief Current state of firmware validation process
|
||||
*/
|
||||
enum class FirmwareValidationState {
|
||||
UNKNOWN, // Initial state, validation status unknown
|
||||
STARTUP_PENDING, // New firmware booted, startup validation pending
|
||||
STARTUP_RUNNING, // Currently performing startup validation
|
||||
RUNTIME_TESTING, // Startup passed, now in extended runtime testing
|
||||
VALIDATED, // Firmware fully validated and committed
|
||||
FAILED_STARTUP, // Failed startup validation, rollback triggered
|
||||
FAILED_RUNTIME, // Failed runtime validation, rollback triggered
|
||||
ROLLED_BACK // Successfully rolled back to previous firmware
|
||||
};
|
||||
|
||||
/**
|
||||
* @enum ValidationLevel
|
||||
* @brief Different levels of health validation
|
||||
*/
|
||||
enum class ValidationLevel {
|
||||
STARTUP, // Basic system initialization checks
|
||||
RUNTIME, // Core functionality validation
|
||||
COMPREHENSIVE // Full system health validation
|
||||
};
|
||||
|
||||
/**
|
||||
* @struct FirmwareInfo
|
||||
* @brief Information about a firmware partition
|
||||
*/
|
||||
struct FirmwareInfo {
|
||||
String version;
|
||||
String buildDate;
|
||||
String commitHash;
|
||||
bool isValid;
|
||||
bool isTesting;
|
||||
unsigned long bootCount;
|
||||
unsigned long lastBootTime;
|
||||
|
||||
FirmwareInfo() : version(""), buildDate(""), commitHash(""),
|
||||
isValid(false), isTesting(false), bootCount(0), lastBootTime(0) {}
|
||||
};
|
||||
|
||||
/**
|
||||
* @struct ValidationConfig
|
||||
* @brief Configuration parameters for firmware validation
|
||||
*/
|
||||
struct ValidationConfig {
|
||||
unsigned long startupTimeoutMs = 10000; // 10 seconds for startup validation
|
||||
unsigned long runtimeTimeoutMs = 300000; // 5 minutes for runtime validation
|
||||
unsigned long healthCheckIntervalMs = 30000; // 30 seconds between health checks
|
||||
uint8_t maxStartupRetries = 3; // Max startup failures before rollback
|
||||
uint8_t maxRuntimeFailures = 5; // Max runtime failures before rollback
|
||||
bool enableWatchdog = true; // Enable watchdog protection
|
||||
unsigned long watchdogTimeoutMs = 30000; // 30 seconds watchdog timeout
|
||||
};
|
||||
|
||||
/**
|
||||
* @class FirmwareValidator
|
||||
* @brief Bulletproof firmware update validation and rollback system
|
||||
*
|
||||
* This class manages the complete firmware validation lifecycle, from initial
|
||||
* boot to full system validation, with automatic rollback capabilities for
|
||||
* failed firmware updates.
|
||||
*/
|
||||
class FirmwareValidator {
|
||||
public:
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// CONSTRUCTOR & INITIALIZATION
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Constructor - Initialize firmware validation system
|
||||
*/
|
||||
FirmwareValidator();
|
||||
|
||||
/**
|
||||
* @brief Destructor - Clean up resources
|
||||
*/
|
||||
~FirmwareValidator();
|
||||
|
||||
/**
|
||||
* @brief Initialize firmware validation system
|
||||
* @param healthMonitor Reference to system health monitor
|
||||
* @param configManager Reference to configuration manager
|
||||
* @return true if initialization successful
|
||||
*/
|
||||
bool begin(HealthMonitor* healthMonitor, ConfigManager* configManager);
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// STARTUP VALIDATION (CRITICAL - MUST BE CALLED EARLY IN setup())
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Perform immediate startup validation
|
||||
*
|
||||
* This MUST be called early in setup() before initializing other subsystems.
|
||||
* If validation fails, the system will automatically rollback and reboot.
|
||||
*
|
||||
* @return true if startup validation passes, false if rollback was triggered
|
||||
*/
|
||||
bool performStartupValidation();
|
||||
|
||||
/**
|
||||
* @brief Check if current firmware is in testing mode
|
||||
* @return true if firmware is being tested and not yet committed
|
||||
*/
|
||||
bool isInTestingMode() const { return _validationState == FirmwareValidationState::STARTUP_PENDING ||
|
||||
_validationState == FirmwareValidationState::STARTUP_RUNNING ||
|
||||
_validationState == FirmwareValidationState::RUNTIME_TESTING; }
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// RUNTIME VALIDATION & MONITORING
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Start extended runtime validation
|
||||
*
|
||||
* Call this after all subsystems are initialized to begin the extended
|
||||
* validation period before committing the firmware.
|
||||
*/
|
||||
void startRuntimeValidation();
|
||||
|
||||
/**
|
||||
* @brief Manually trigger firmware validation completion
|
||||
*
|
||||
* This commits the current firmware as valid and stable.
|
||||
* Normally called automatically after successful runtime validation.
|
||||
*/
|
||||
void commitFirmware();
|
||||
|
||||
/**
|
||||
* @brief Manually trigger firmware rollback
|
||||
*
|
||||
* Forces an immediate rollback to the previous firmware version.
|
||||
* Use this for emergency situations or failed validations.
|
||||
*/
|
||||
void rollbackFirmware();
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// STATUS & INFORMATION
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Get current validation state
|
||||
* @return Current firmware validation state
|
||||
*/
|
||||
FirmwareValidationState getValidationState() const { return _validationState; }
|
||||
|
||||
/**
|
||||
* @brief Get information about the current running firmware
|
||||
* @return Firmware information structure
|
||||
*/
|
||||
FirmwareInfo getCurrentFirmwareInfo() const;
|
||||
|
||||
/**
|
||||
* @brief Get information about the backup firmware partition
|
||||
* @return Firmware information structure for backup partition
|
||||
*/
|
||||
FirmwareInfo getBackupFirmwareInfo() const;
|
||||
|
||||
/**
|
||||
* @brief Get validation configuration
|
||||
* @return Current validation configuration
|
||||
*/
|
||||
const ValidationConfig& getValidationConfig() const { return _config; }
|
||||
|
||||
/**
|
||||
* @brief Set validation configuration
|
||||
* @param config New validation configuration
|
||||
*/
|
||||
void setValidationConfig(const ValidationConfig& config) { _config = config; }
|
||||
|
||||
/**
|
||||
* @brief Check if firmware validation system is healthy
|
||||
* @return true if validation system is functioning properly
|
||||
*/
|
||||
bool isHealthy() const;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// PARTITION MANAGEMENT
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Get the currently running OTA partition
|
||||
* @return Pointer to running partition, nullptr on error
|
||||
*/
|
||||
const esp_partition_t* getRunningPartition() const;
|
||||
|
||||
/**
|
||||
* @brief Get the backup (inactive) OTA partition
|
||||
* @return Pointer to backup partition, nullptr on error
|
||||
*/
|
||||
const esp_partition_t* getBackupPartition() const;
|
||||
|
||||
/**
|
||||
* @brief Check if a new firmware update is available for testing
|
||||
* @return true if there's a new firmware waiting to be validated
|
||||
*/
|
||||
bool isNewFirmwarePending() const;
|
||||
|
||||
private:
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// PRIVATE MEMBERS
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
HealthMonitor* _healthMonitor = nullptr;
|
||||
ConfigManager* _configManager = nullptr;
|
||||
|
||||
FirmwareValidationState _validationState = FirmwareValidationState::UNKNOWN;
|
||||
ValidationConfig _config;
|
||||
|
||||
// Partition information
|
||||
const esp_partition_t* _runningPartition = nullptr;
|
||||
const esp_partition_t* _backupPartition = nullptr;
|
||||
|
||||
// Validation tracking
|
||||
unsigned long _validationStartTime = 0;
|
||||
uint8_t _startupRetryCount = 0;
|
||||
uint8_t _runtimeFailureCount = 0;
|
||||
TimerHandle_t _validationTimer = nullptr;
|
||||
TaskHandle_t _monitoringTask = nullptr;
|
||||
// Flag set by timer callback (Tmr Svc context) — actual commit done in monitoring task
|
||||
volatile bool _commitPending = false;
|
||||
|
||||
// NVS handles for persistent storage
|
||||
nvs_handle_t _nvsHandle = 0;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// PRIVATE METHODS
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Initialize NVS storage for validation state persistence
|
||||
*/
|
||||
bool initializeNVS();
|
||||
|
||||
/**
|
||||
* @brief Load validation state from NVS
|
||||
*/
|
||||
void loadValidationState();
|
||||
|
||||
/**
|
||||
* @brief Save validation state to NVS
|
||||
*/
|
||||
void saveValidationState();
|
||||
|
||||
/**
|
||||
* @brief Initialize ESP32 partition information
|
||||
*/
|
||||
bool initializePartitions();
|
||||
|
||||
/**
|
||||
* @brief Perform basic startup health checks
|
||||
*/
|
||||
bool performBasicHealthCheck();
|
||||
|
||||
/**
|
||||
* @brief Perform comprehensive runtime health checks
|
||||
*/
|
||||
bool performRuntimeHealthCheck();
|
||||
|
||||
/**
|
||||
* @brief Timer callback for validation timeout
|
||||
*/
|
||||
static void validationTimerCallback(TimerHandle_t timer);
|
||||
|
||||
/**
|
||||
* @brief Monitoring task for continuous health checks during validation
|
||||
*/
|
||||
static void monitoringTaskFunction(void* parameter);
|
||||
|
||||
/**
|
||||
* @brief Main monitoring loop
|
||||
*/
|
||||
void monitoringLoop();
|
||||
|
||||
/**
|
||||
* @brief Handle validation success
|
||||
*/
|
||||
void handleValidationSuccess();
|
||||
|
||||
/**
|
||||
* @brief Handle validation failure
|
||||
*/
|
||||
void handleValidationFailure(const String& reason);
|
||||
|
||||
/**
|
||||
* @brief Execute firmware rollback
|
||||
*/
|
||||
void executeRollback();
|
||||
|
||||
/**
|
||||
* @brief Convert validation state to string
|
||||
*/
|
||||
String validationStateToString(FirmwareValidationState state) const;
|
||||
|
||||
/**
|
||||
* @brief Get partition label string
|
||||
*/
|
||||
String getPartitionLabel(const esp_partition_t* partition) const;
|
||||
|
||||
/**
|
||||
* @brief Check if partition has valid firmware
|
||||
*/
|
||||
bool isPartitionValid(const esp_partition_t* partition) const;
|
||||
|
||||
/**
|
||||
* @brief Get boot count for current session
|
||||
*/
|
||||
unsigned long getBootCount() const;
|
||||
|
||||
/**
|
||||
* @brief Increment boot count
|
||||
*/
|
||||
void incrementBootCount();
|
||||
|
||||
/**
|
||||
* @brief Reset validation counters
|
||||
*/
|
||||
void resetValidationCounters();
|
||||
|
||||
/**
|
||||
* @brief Setup watchdog protection
|
||||
*/
|
||||
void setupWatchdog();
|
||||
|
||||
/**
|
||||
* @brief Feed the watchdog timer
|
||||
*/
|
||||
void feedWatchdog();
|
||||
};
|
||||
@@ -0,0 +1,437 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* HEALTHMONITOR.CPP - System Health Monitoring Implementation
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#include "HealthMonitor.hpp"
|
||||
|
||||
#define TAG "HealthMonitor"
|
||||
#include "../BellEngine/BellEngine.hpp"
|
||||
#include "../OutputManager/OutputManager.hpp"
|
||||
#include "../Communication/CommunicationRouter/CommunicationRouter.hpp"
|
||||
#include "../Player/Player.hpp"
|
||||
#include "../TimeKeeper/TimeKeeper.hpp"
|
||||
#include "../Telemetry/Telemetry.hpp"
|
||||
#include "../OTAManager/OTAManager.hpp"
|
||||
#include "../Networking/Networking.hpp"
|
||||
#include "../ConfigManager/ConfigManager.hpp"
|
||||
#include "../FileManager/FileManager.hpp"
|
||||
#include <ArduinoJson.h>
|
||||
|
||||
HealthMonitor::HealthMonitor() {
|
||||
initializeSubsystemHealth();
|
||||
}
|
||||
|
||||
HealthMonitor::~HealthMonitor() {
|
||||
if (_monitoringTaskHandle != nullptr) {
|
||||
vTaskDelete(_monitoringTaskHandle);
|
||||
_monitoringTaskHandle = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
bool HealthMonitor::begin() {
|
||||
LOG_INFO(TAG, "🏥 Initializing Health Monitor System");
|
||||
|
||||
// Create monitoring task if auto-monitoring is enabled
|
||||
if (_autoMonitoring) {
|
||||
xTaskCreatePinnedToCore(
|
||||
monitoringTask,
|
||||
"HealthMonitor",
|
||||
4096,
|
||||
this,
|
||||
3, // Medium priority
|
||||
&_monitoringTaskHandle,
|
||||
0 // Core 0 (different from BellEngine which uses Core 1)
|
||||
);
|
||||
|
||||
if (_monitoringTaskHandle != nullptr) {
|
||||
LOG_INFO(TAG, "✅ Health Monitor initialized with automatic monitoring");
|
||||
return true;
|
||||
} else {
|
||||
LOG_ERROR(TAG, "❌ Failed to create Health Monitor task");
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
LOG_INFO(TAG, "✅ Health Monitor initialized (manual mode)");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
void HealthMonitor::initializeSubsystemHealth() {
|
||||
// Initialize all subsystem health entries
|
||||
// Mark critical subsystems that must be healthy for operation
|
||||
|
||||
_subsystemHealth["BellEngine"] = SubsystemHealth("BellEngine", true);
|
||||
_subsystemHealth["OutputManager"] = SubsystemHealth("OutputManager", true);
|
||||
_subsystemHealth["ConfigManager"] = SubsystemHealth("ConfigManager", true);
|
||||
_subsystemHealth["FileManager"] = SubsystemHealth("FileManager", true);
|
||||
_subsystemHealth["Communication"] = SubsystemHealth("Communication", false); // Non-critical
|
||||
_subsystemHealth["Player"] = SubsystemHealth("Player", true);
|
||||
_subsystemHealth["TimeKeeper"] = SubsystemHealth("TimeKeeper", false); // Non-critical
|
||||
_subsystemHealth["Telemetry"] = SubsystemHealth("Telemetry", false); // Non-critical
|
||||
_subsystemHealth["OTAManager"] = SubsystemHealth("OTAManager", false); // Non-critical
|
||||
_subsystemHealth["Networking"] = SubsystemHealth("Networking", false); // Non-critical
|
||||
|
||||
LOG_DEBUG(TAG, "🏗️ Initialized health monitoring for %d subsystems", _subsystemHealth.size());
|
||||
}
|
||||
|
||||
void HealthMonitor::monitoringTask(void* parameter) {
|
||||
HealthMonitor* monitor = static_cast<HealthMonitor*>(parameter);
|
||||
LOG_INFO(TAG, "🏥 Health Monitor task started on Core %d", xPortGetCoreID());
|
||||
|
||||
while (true) {
|
||||
monitor->monitoringLoop();
|
||||
vTaskDelay(pdMS_TO_TICKS(monitor->_healthCheckInterval));
|
||||
}
|
||||
}
|
||||
|
||||
void HealthMonitor::monitoringLoop() {
|
||||
|
||||
if (_player) {
|
||||
if (_player->_status != PlayerStatus::STOPPED) {
|
||||
LOG_VERBOSE(TAG, "⏸️ Skipping health check during active playback");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
LOG_VERBOSE(TAG, "🔍 Performing periodic health check...");
|
||||
|
||||
HealthStatus overallHealth = performFullHealthCheck();
|
||||
|
||||
// Log warnings for any unhealthy subsystems
|
||||
uint8_t criticalCount = getCriticalFailureCount();
|
||||
uint8_t warningCount = getWarningCount();
|
||||
|
||||
if (criticalCount > 0) {
|
||||
LOG_WARNING(TAG, "🚨 Health Monitor: %d critical failures detected!", criticalCount);
|
||||
|
||||
// List critical failures
|
||||
for (const auto& [name, health] : _subsystemHealth) {
|
||||
if (health.status == HealthStatus::CRITICAL || health.status == HealthStatus::FAILED) {
|
||||
LOG_ERROR(TAG, "❌ CRITICAL: %s - %s", name.c_str(), health.lastError.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
// Check if firmware rollback is recommended
|
||||
if (shouldRollbackFirmware()) {
|
||||
LOG_ERROR(TAG, "🔄 FIRMWARE ROLLBACK RECOMMENDED - Too many critical failures");
|
||||
// In a real system, this would trigger an OTA rollback
|
||||
// For now, we just log the recommendation
|
||||
}
|
||||
} else if (warningCount > 0) {
|
||||
LOG_WARNING(TAG, "⚠️ Health Monitor: %d warning(s) detected", warningCount);
|
||||
|
||||
// List every subsystem that is in WARNING state
|
||||
for (const auto& [name, health] : _subsystemHealth) {
|
||||
if (health.status == HealthStatus::WARNING) {
|
||||
LOG_WARNING(TAG, "⚠️ WARNING: %s - %s", name.c_str(), health.lastError.c_str());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
LOG_VERBOSE(TAG, "✅ All subsystems healthy");
|
||||
}
|
||||
}
|
||||
|
||||
HealthStatus HealthMonitor::performFullHealthCheck() {
|
||||
unsigned long startTime = millis();
|
||||
uint8_t checkedSystems = 0;
|
||||
|
||||
// Check BellEngine
|
||||
if (_bellEngine) {
|
||||
bool healthy = _bellEngine->isHealthy();
|
||||
updateSubsystemHealth("BellEngine",
|
||||
healthy ? HealthStatus::HEALTHY : HealthStatus::CRITICAL,
|
||||
healthy ? "" : "BellEngine health check failed");
|
||||
checkedSystems++;
|
||||
}
|
||||
|
||||
// Check OutputManager
|
||||
if (_outputManager) {
|
||||
bool healthy = _outputManager->isHealthy();
|
||||
updateSubsystemHealth("OutputManager",
|
||||
healthy ? HealthStatus::HEALTHY : HealthStatus::CRITICAL,
|
||||
healthy ? "" : "OutputManager health check failed");
|
||||
checkedSystems++;
|
||||
}
|
||||
|
||||
// Check Communication
|
||||
if (_communication) {
|
||||
bool healthy = _communication->isHealthy();
|
||||
updateSubsystemHealth("Communication",
|
||||
healthy ? HealthStatus::HEALTHY : HealthStatus::WARNING,
|
||||
healthy ? "" : "Communication health check failed");
|
||||
checkedSystems++;
|
||||
}
|
||||
|
||||
// Check Player
|
||||
if (_player) {
|
||||
bool healthy = _player->isHealthy();
|
||||
updateSubsystemHealth("Player",
|
||||
healthy ? HealthStatus::HEALTHY : HealthStatus::CRITICAL,
|
||||
healthy ? "" : "Player health check failed");
|
||||
checkedSystems++;
|
||||
}
|
||||
|
||||
// Check TimeKeeper
|
||||
if (_timeKeeper) {
|
||||
bool healthy = _timeKeeper->isHealthy();
|
||||
updateSubsystemHealth("TimeKeeper",
|
||||
healthy ? HealthStatus::HEALTHY : HealthStatus::WARNING,
|
||||
healthy ? "" : "TimeKeeper health check failed");
|
||||
checkedSystems++;
|
||||
}
|
||||
|
||||
// Check Telemetry
|
||||
if (_telemetry) {
|
||||
bool healthy = _telemetry->isHealthy();
|
||||
updateSubsystemHealth("Telemetry",
|
||||
healthy ? HealthStatus::HEALTHY : HealthStatus::WARNING,
|
||||
healthy ? "" : "Telemetry health check failed");
|
||||
checkedSystems++;
|
||||
}
|
||||
|
||||
// Check OTAManager
|
||||
if (_otaManager) {
|
||||
bool healthy = _otaManager->isHealthy();
|
||||
updateSubsystemHealth("OTAManager",
|
||||
healthy ? HealthStatus::HEALTHY : HealthStatus::WARNING,
|
||||
healthy ? "" : "OTAManager health check failed");
|
||||
checkedSystems++;
|
||||
}
|
||||
|
||||
// Check Networking
|
||||
if (_networking) {
|
||||
bool healthy = _networking->isHealthy();
|
||||
updateSubsystemHealth("Networking",
|
||||
healthy ? HealthStatus::HEALTHY : HealthStatus::WARNING,
|
||||
healthy ? "" : "Networking health check failed");
|
||||
checkedSystems++;
|
||||
}
|
||||
|
||||
// Check ConfigManager — SD absence is non-critical (device runs on defaults)
|
||||
if (_configManager) {
|
||||
bool healthy = _configManager->isHealthy();
|
||||
updateSubsystemHealth("ConfigManager",
|
||||
healthy ? HealthStatus::HEALTHY : HealthStatus::WARNING,
|
||||
healthy ? "" : "ConfigManager health check failed");
|
||||
checkedSystems++;
|
||||
}
|
||||
|
||||
// Check FileManager — SD absence is non-critical (device runs on defaults)
|
||||
if (_fileManager) {
|
||||
bool healthy = _fileManager->isHealthy();
|
||||
updateSubsystemHealth("FileManager",
|
||||
healthy ? HealthStatus::HEALTHY : HealthStatus::WARNING,
|
||||
healthy ? "" : "FileManager health check failed");
|
||||
checkedSystems++;
|
||||
}
|
||||
|
||||
unsigned long elapsed = millis() - startTime;
|
||||
LOG_VERBOSE(TAG, "🔍 Health check completed: %d systems in %lums", checkedSystems, elapsed);
|
||||
|
||||
return calculateOverallHealth();
|
||||
}
|
||||
|
||||
HealthStatus HealthMonitor::checkSubsystemHealth(const String& subsystemName) {
|
||||
// Perform health check on specific subsystem
|
||||
auto it = _subsystemHealth.find(subsystemName);
|
||||
if (it == _subsystemHealth.end()) {
|
||||
LOG_WARNING(TAG, "❓ Unknown subsystem: %s", subsystemName.c_str());
|
||||
return HealthStatus::FAILED;
|
||||
}
|
||||
|
||||
bool healthy = false;
|
||||
|
||||
// Check specific subsystem
|
||||
if (subsystemName == "BellEngine" && _bellEngine) {
|
||||
healthy = _bellEngine->isHealthy();
|
||||
} else if (subsystemName == "OutputManager" && _outputManager) {
|
||||
healthy = _outputManager->isHealthy();
|
||||
} else if (subsystemName == "Communication" && _communication) {
|
||||
healthy = _communication->isHealthy();
|
||||
} else if (subsystemName == "Player" && _player) {
|
||||
healthy = _player->isHealthy();
|
||||
} else if (subsystemName == "TimeKeeper" && _timeKeeper) {
|
||||
healthy = _timeKeeper->isHealthy();
|
||||
} else if (subsystemName == "Telemetry" && _telemetry) {
|
||||
healthy = _telemetry->isHealthy();
|
||||
} else if (subsystemName == "OTAManager" && _otaManager) {
|
||||
healthy = _otaManager->isHealthy();
|
||||
} else if (subsystemName == "Networking" && _networking) {
|
||||
healthy = _networking->isHealthy();
|
||||
} else if (subsystemName == "ConfigManager" && _configManager) {
|
||||
healthy = _configManager->isHealthy();
|
||||
} else if (subsystemName == "FileManager" && _fileManager) {
|
||||
healthy = _fileManager->isHealthy();
|
||||
} else {
|
||||
LOG_WARNING(TAG, "🔌 Subsystem %s not connected to health monitor", subsystemName.c_str());
|
||||
return HealthStatus::FAILED;
|
||||
}
|
||||
|
||||
HealthStatus status = healthy ? HealthStatus::HEALTHY :
|
||||
(it->second.isCritical ? HealthStatus::CRITICAL : HealthStatus::WARNING);
|
||||
|
||||
updateSubsystemHealth(subsystemName, status,
|
||||
healthy ? "" : subsystemName + " health check failed");
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
const std::map<String, SubsystemHealth>& HealthMonitor::getAllSubsystemHealth() const {
|
||||
return _subsystemHealth;
|
||||
}
|
||||
|
||||
SubsystemHealth HealthMonitor::getSubsystemHealth(const String& subsystemName) const {
|
||||
auto it = _subsystemHealth.find(subsystemName);
|
||||
if (it != _subsystemHealth.end()) {
|
||||
return it->second;
|
||||
}
|
||||
|
||||
// Return default unhealthy status for unknown subsystems
|
||||
SubsystemHealth unknown(subsystemName);
|
||||
unknown.status = HealthStatus::FAILED;
|
||||
unknown.lastError = "Subsystem not found";
|
||||
return unknown;
|
||||
}
|
||||
|
||||
bool HealthMonitor::isFirmwareStable() const {
|
||||
return areCriticalSubsystemsHealthy() && (getCriticalFailureCount() == 0);
|
||||
}
|
||||
|
||||
uint8_t HealthMonitor::getCriticalFailureCount() const {
|
||||
uint8_t count = 0;
|
||||
|
||||
for (const auto& [name, health] : _subsystemHealth) {
|
||||
if (health.isCritical &&
|
||||
(health.status == HealthStatus::CRITICAL || health.status == HealthStatus::FAILED)) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
uint8_t HealthMonitor::getWarningCount() const {
|
||||
uint8_t count = 0;
|
||||
|
||||
for (const auto& [name, health] : _subsystemHealth) {
|
||||
if (health.status == HealthStatus::WARNING) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
bool HealthMonitor::shouldRollbackFirmware() const {
|
||||
uint8_t criticalFailures = getCriticalFailureCount();
|
||||
|
||||
// Rollback if more than 2 critical subsystems have failed
|
||||
// This is configurable based on system requirements
|
||||
const uint8_t MAX_CRITICAL_FAILURES = 2;
|
||||
|
||||
return criticalFailures > MAX_CRITICAL_FAILURES;
|
||||
}
|
||||
|
||||
String HealthMonitor::generateHealthReport() const {
|
||||
StaticJsonDocument<2048> doc;
|
||||
|
||||
doc["timestamp"] = millis();
|
||||
doc["overall_health"] = healthStatusToString(calculateOverallHealth());
|
||||
doc["critical_failures"] = getCriticalFailureCount();
|
||||
doc["warnings"] = getWarningCount();
|
||||
doc["firmware_stable"] = isFirmwareStable();
|
||||
doc["rollback_recommended"] = shouldRollbackFirmware();
|
||||
|
||||
JsonObject subsystems = doc.createNestedObject("subsystems");
|
||||
|
||||
for (const auto& [name, health] : _subsystemHealth) {
|
||||
JsonObject subsystem = subsystems.createNestedObject(name);
|
||||
subsystem["status"] = healthStatusToString(health.status);
|
||||
subsystem["critical"] = health.isCritical;
|
||||
subsystem["last_check"] = health.lastCheck;
|
||||
|
||||
if (!health.lastError.isEmpty()) {
|
||||
subsystem["error"] = health.lastError;
|
||||
}
|
||||
}
|
||||
|
||||
String report;
|
||||
serializeJsonPretty(doc, report);
|
||||
return report;
|
||||
}
|
||||
|
||||
String HealthMonitor::getHealthSummary() const {
|
||||
HealthStatus overall = calculateOverallHealth();
|
||||
uint8_t critical = getCriticalFailureCount();
|
||||
uint8_t warnings = getWarningCount();
|
||||
|
||||
String summary = "System Health: " + healthStatusToString(overall);
|
||||
|
||||
if (critical > 0) {
|
||||
summary += " (" + String(critical) + " critical failures)";
|
||||
}
|
||||
|
||||
if (warnings > 0) {
|
||||
summary += " (" + String(warnings) + " warnings)";
|
||||
}
|
||||
|
||||
if (shouldRollbackFirmware()) {
|
||||
summary += " - ROLLBACK RECOMMENDED";
|
||||
}
|
||||
|
||||
return summary;
|
||||
}
|
||||
|
||||
void HealthMonitor::updateSubsystemHealth(const String& name, HealthStatus status, const String& error) {
|
||||
auto it = _subsystemHealth.find(name);
|
||||
if (it != _subsystemHealth.end()) {
|
||||
it->second.status = status;
|
||||
it->second.lastError = error;
|
||||
it->second.lastCheck = millis();
|
||||
|
||||
LOG_VERBOSE(TAG, "🔍 %s: %s %s",
|
||||
name.c_str(),
|
||||
healthStatusToString(status).c_str(),
|
||||
error.isEmpty() ? "" : ("(" + error + ")").c_str());
|
||||
}
|
||||
}
|
||||
|
||||
bool HealthMonitor::areCriticalSubsystemsHealthy() const {
|
||||
for (const auto& [name, health] : _subsystemHealth) {
|
||||
if (health.isCritical &&
|
||||
(health.status == HealthStatus::CRITICAL || health.status == HealthStatus::FAILED)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
HealthStatus HealthMonitor::calculateOverallHealth() const {
|
||||
bool hasCriticalFailures = (getCriticalFailureCount() > 0);
|
||||
bool hasWarnings = (getWarningCount() > 0);
|
||||
|
||||
if (hasCriticalFailures) {
|
||||
return HealthStatus::CRITICAL;
|
||||
} else if (hasWarnings) {
|
||||
return HealthStatus::WARNING;
|
||||
} else {
|
||||
return HealthStatus::HEALTHY;
|
||||
}
|
||||
}
|
||||
|
||||
String HealthMonitor::healthStatusToString(HealthStatus status) const {
|
||||
switch (status) {
|
||||
case HealthStatus::HEALTHY:
|
||||
return "HEALTHY";
|
||||
case HealthStatus::WARNING:
|
||||
return "WARNING";
|
||||
case HealthStatus::CRITICAL:
|
||||
return "CRITICAL";
|
||||
case HealthStatus::FAILED:
|
||||
return "FAILED";
|
||||
default:
|
||||
return "UNKNOWN";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* HEALTHMONITOR.HPP - System Health Monitoring and Firmware Validation
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 🏥 THE SYSTEM HEALTH GUARDIAN OF VESPER 🏥
|
||||
*
|
||||
* This class provides comprehensive system health monitoring across all subsystems.
|
||||
* It determines whether the current firmware is stable and functional, or if a
|
||||
* rollback to the previous firmware version should be performed.
|
||||
*
|
||||
* 🏗️ ARCHITECTURE:
|
||||
* • Periodic health checks across all major subsystems
|
||||
* • Critical vs non-critical failure classification
|
||||
* • Firmware stability validation and rollback decision making
|
||||
* • Centralized health status reporting
|
||||
* • Thread-safe operation with configurable check intervals
|
||||
*
|
||||
* 🔍 MONITORED SUBSYSTEMS:
|
||||
* • BellEngine: Core timing and bell control system
|
||||
* • OutputManager: Hardware abstraction layer
|
||||
* • Communication: MQTT, WebSocket, and UDP protocols
|
||||
* • Player: Melody playback management
|
||||
* • TimeKeeper: RTC and time synchronization
|
||||
* • Telemetry: System monitoring and analytics
|
||||
* • OTAManager: Firmware update management
|
||||
* • Networking: Network connectivity management
|
||||
* • ConfigManager: Configuration and persistence
|
||||
* • FileManager: SD card and file operations
|
||||
*
|
||||
* 🚨 FAILURE CLASSIFICATION:
|
||||
* • CRITICAL: Failures that make the device unusable
|
||||
* • WARNING: Failures that affect functionality but allow operation
|
||||
* • INFO: Minor issues that don't affect core functionality
|
||||
*
|
||||
* 🔄 FIRMWARE VALIDATION:
|
||||
* • Boot-time stability check
|
||||
* • Runtime health monitoring
|
||||
* • Automatic rollback decision making
|
||||
* • Health status persistence
|
||||
*
|
||||
* 📋 VERSION: 1.0 (Initial health monitoring system)
|
||||
* 📅 DATE: 2025
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "../Logging/Logging.hpp"
|
||||
|
||||
// Forward declarations for all monitored subsystems
|
||||
class BellEngine;
|
||||
class OutputManager;
|
||||
class CommunicationRouter;
|
||||
class Player;
|
||||
class Timekeeper;
|
||||
class Telemetry;
|
||||
class OTAManager;
|
||||
class Networking;
|
||||
class ConfigManager;
|
||||
class FileManager;
|
||||
|
||||
/**
|
||||
* @enum HealthStatus
|
||||
* @brief Health status levels for subsystems
|
||||
*/
|
||||
enum class HealthStatus {
|
||||
HEALTHY, // System is functioning normally
|
||||
WARNING, // System has minor issues but is operational
|
||||
CRITICAL, // System has major issues affecting functionality
|
||||
FAILED // System is non-functional
|
||||
};
|
||||
|
||||
/**
|
||||
* @struct SubsystemHealth
|
||||
* @brief Health information for a single subsystem
|
||||
*/
|
||||
struct SubsystemHealth {
|
||||
String name; // Subsystem name
|
||||
HealthStatus status; // Current health status
|
||||
String lastError; // Last error message (if any)
|
||||
unsigned long lastCheck; // Timestamp of last health check
|
||||
bool isCritical; // Whether this subsystem is critical for operation
|
||||
|
||||
// Default constructor for std::map compatibility
|
||||
SubsystemHealth()
|
||||
: name(""), status(HealthStatus::HEALTHY), lastCheck(0), isCritical(false) {}
|
||||
|
||||
SubsystemHealth(const String& n, bool critical = false)
|
||||
: name(n), status(HealthStatus::HEALTHY), lastCheck(0), isCritical(critical) {}
|
||||
};
|
||||
|
||||
/**
|
||||
* @class HealthMonitor
|
||||
* @brief Comprehensive system health monitoring and firmware validation
|
||||
*
|
||||
* The HealthMonitor continuously monitors all subsystems to ensure the firmware
|
||||
* is stable and functional. It can make decisions about firmware rollbacks
|
||||
* based on the overall system health.
|
||||
*/
|
||||
class HealthMonitor {
|
||||
public:
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// CONSTRUCTOR & INITIALIZATION
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Constructor - Initialize health monitoring system
|
||||
*/
|
||||
HealthMonitor();
|
||||
|
||||
/**
|
||||
* @brief Destructor - Clean up resources
|
||||
*/
|
||||
~HealthMonitor();
|
||||
|
||||
/**
|
||||
* @brief Initialize health monitoring system
|
||||
* @return true if initialization successful
|
||||
*/
|
||||
bool begin();
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// SUBSYSTEM REGISTRATION
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/** @brief Register BellEngine for monitoring */
|
||||
void setBellEngine(BellEngine* bellEngine) { _bellEngine = bellEngine; }
|
||||
|
||||
/** @brief Register OutputManager for monitoring */
|
||||
void setOutputManager(OutputManager* outputManager) { _outputManager = outputManager; }
|
||||
|
||||
/** @brief Register Communication for monitoring */
|
||||
void setCommunication(CommunicationRouter* communication) { _communication = communication; }
|
||||
|
||||
/** @brief Register Player for monitoring */
|
||||
void setPlayer(Player* player) { _player = player; }
|
||||
|
||||
/** @brief Register TimeKeeper for monitoring */
|
||||
void setTimeKeeper(Timekeeper* timeKeeper) { _timeKeeper = timeKeeper; }
|
||||
|
||||
/** @brief Register Telemetry for monitoring */
|
||||
void setTelemetry(Telemetry* telemetry) { _telemetry = telemetry; }
|
||||
|
||||
/** @brief Register OTAManager for monitoring */
|
||||
void setOTAManager(OTAManager* otaManager) { _otaManager = otaManager; }
|
||||
|
||||
/** @brief Register Networking for monitoring */
|
||||
void setNetworking(Networking* networking) { _networking = networking; }
|
||||
|
||||
/** @brief Register ConfigManager for monitoring */
|
||||
void setConfigManager(ConfigManager* configManager) { _configManager = configManager; }
|
||||
|
||||
/** @brief Register FileManager for monitoring */
|
||||
void setFileManager(FileManager* fileManager) { _fileManager = fileManager; }
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// HEALTH CHECK METHODS
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Perform comprehensive health check on all subsystems
|
||||
* @return Overall system health status
|
||||
*/
|
||||
HealthStatus performFullHealthCheck();
|
||||
|
||||
/**
|
||||
* @brief Perform health check on a specific subsystem
|
||||
* @param subsystemName Name of the subsystem to check
|
||||
* @return Health status of the specified subsystem
|
||||
*/
|
||||
HealthStatus checkSubsystemHealth(const String& subsystemName);
|
||||
|
||||
/**
|
||||
* @brief Get current health status of all subsystems
|
||||
* @return Map of subsystem names to their health information
|
||||
*/
|
||||
const std::map<String, SubsystemHealth>& getAllSubsystemHealth() const;
|
||||
|
||||
/**
|
||||
* @brief Get health status of a specific subsystem
|
||||
* @param subsystemName Name of the subsystem
|
||||
* @return Health information for the subsystem
|
||||
*/
|
||||
SubsystemHealth getSubsystemHealth(const String& subsystemName) const;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// FIRMWARE VALIDATION
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Check if current firmware is stable and should be kept
|
||||
* @return true if firmware is stable, false if rollback is recommended
|
||||
*/
|
||||
bool isFirmwareStable() const;
|
||||
|
||||
/**
|
||||
* @brief Get the number of critical failures detected
|
||||
* @return Count of subsystems with critical failures
|
||||
*/
|
||||
uint8_t getCriticalFailureCount() const;
|
||||
|
||||
/**
|
||||
* @brief Get the number of warning-level issues detected
|
||||
* @return Count of subsystems with warning-level issues
|
||||
*/
|
||||
uint8_t getWarningCount() const;
|
||||
|
||||
/**
|
||||
* @brief Check if a firmware rollback is recommended
|
||||
* @return true if rollback is recommended due to critical failures
|
||||
*/
|
||||
bool shouldRollbackFirmware() const;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// HEALTH REPORTING
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Generate a comprehensive health report
|
||||
* @return JSON string containing detailed health information
|
||||
*/
|
||||
String generateHealthReport() const;
|
||||
|
||||
/**
|
||||
* @brief Get a summary of system health
|
||||
* @return Brief health summary string
|
||||
*/
|
||||
String getHealthSummary() const;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// CONFIGURATION
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Set health check interval
|
||||
* @param intervalMs Interval between health checks in milliseconds
|
||||
*/
|
||||
void setHealthCheckInterval(unsigned long intervalMs) { _healthCheckInterval = intervalMs; }
|
||||
|
||||
/**
|
||||
* @brief Enable or disable automatic health monitoring
|
||||
* @param enabled Whether to enable automatic monitoring
|
||||
*/
|
||||
void setAutoMonitoring(bool enabled) { _autoMonitoring = enabled; }
|
||||
|
||||
private:
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// SUBSYSTEM REFERENCES
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
BellEngine* _bellEngine = nullptr;
|
||||
OutputManager* _outputManager = nullptr;
|
||||
CommunicationRouter* _communication = nullptr;
|
||||
Player* _player = nullptr;
|
||||
Timekeeper* _timeKeeper = nullptr;
|
||||
Telemetry* _telemetry = nullptr;
|
||||
OTAManager* _otaManager = nullptr;
|
||||
Networking* _networking = nullptr;
|
||||
ConfigManager* _configManager = nullptr;
|
||||
FileManager* _fileManager = nullptr;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// HEALTH MONITORING STATE
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
std::map<String, SubsystemHealth> _subsystemHealth;
|
||||
TaskHandle_t _monitoringTaskHandle = nullptr;
|
||||
unsigned long _healthCheckInterval = 300000; // 5 minutes default
|
||||
bool _autoMonitoring = true;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// PRIVATE HELPER METHODS
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Initialize all subsystem health entries
|
||||
*/
|
||||
void initializeSubsystemHealth();
|
||||
|
||||
/**
|
||||
* @brief Monitoring task function
|
||||
*/
|
||||
static void monitoringTask(void* parameter);
|
||||
|
||||
/**
|
||||
* @brief Main monitoring loop
|
||||
*/
|
||||
void monitoringLoop();
|
||||
|
||||
/**
|
||||
* @brief Update health status for a specific subsystem
|
||||
*/
|
||||
void updateSubsystemHealth(const String& name, HealthStatus status, const String& error = "");
|
||||
|
||||
/**
|
||||
* @brief Check if enough critical subsystems are healthy
|
||||
*/
|
||||
bool areCriticalSubsystemsHealthy() const;
|
||||
|
||||
/**
|
||||
* @brief Calculate overall system health based on subsystem status
|
||||
*/
|
||||
HealthStatus calculateOverallHealth() const;
|
||||
|
||||
/**
|
||||
* @brief Convert health status to string
|
||||
*/
|
||||
String healthStatusToString(HealthStatus status) const;
|
||||
};
|
||||
@@ -0,0 +1,268 @@
|
||||
#include "InputManager.hpp"
|
||||
|
||||
#define TAG "InputManager"
|
||||
#include "../Logging/Logging.hpp"
|
||||
|
||||
// Static instance pointer
|
||||
InputManager* InputManager::_instance = nullptr;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// CONSTRUCTOR & DESTRUCTOR
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
InputManager::InputManager()
|
||||
: _initialized(false)
|
||||
, _inputTaskHandle(nullptr) {
|
||||
// Initialize factory reset button configuration
|
||||
// GPIO 0, Active LOW (pull-up), 50ms debounce, 10s long press
|
||||
_factoryResetButton.config = ButtonConfig(0, false, 50, 10000);
|
||||
|
||||
_instance = this;
|
||||
}
|
||||
|
||||
InputManager::~InputManager() {
|
||||
end();
|
||||
_instance = nullptr;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// INITIALIZATION
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
bool InputManager::begin() {
|
||||
LOG_INFO(TAG, "InputManager: Initializing input handling system");
|
||||
|
||||
// Configure factory reset button
|
||||
configureButton(_factoryResetButton.config);
|
||||
|
||||
// Initialize button state
|
||||
_factoryResetButton.state = ButtonState::IDLE;
|
||||
_factoryResetButton.lastRawState = false;
|
||||
_factoryResetButton.stateChangeTime = millis();
|
||||
_factoryResetButton.pressStartTime = 0;
|
||||
_factoryResetButton.longPressTriggered = false;
|
||||
|
||||
// Create FreeRTOS task for input polling
|
||||
BaseType_t result = xTaskCreate(
|
||||
inputTaskFunction, // Task function
|
||||
"InputTask", // Task name
|
||||
INPUT_TASK_STACK_SIZE, // Stack size
|
||||
this, // Parameter (this instance)
|
||||
INPUT_TASK_PRIORITY, // Priority
|
||||
&_inputTaskHandle // Task handle
|
||||
);
|
||||
|
||||
if (result != pdPASS) {
|
||||
LOG_ERROR(TAG, "InputManager: Failed to create input task!");
|
||||
return false;
|
||||
}
|
||||
|
||||
_initialized = true;
|
||||
|
||||
LOG_INFO(TAG, "InputManager: Initialization complete - Factory Reset on GPIO 0 (Task running)");
|
||||
return true;
|
||||
}
|
||||
|
||||
void InputManager::end() {
|
||||
if (_inputTaskHandle != nullptr) {
|
||||
vTaskDelete(_inputTaskHandle);
|
||||
_inputTaskHandle = nullptr;
|
||||
LOG_INFO(TAG, "InputManager: Input task stopped");
|
||||
}
|
||||
_initialized = false;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// CALLBACK REGISTRATION
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void InputManager::setFactoryResetPressCallback(ButtonCallback callback) {
|
||||
_factoryResetButton.config.onPress = callback;
|
||||
LOG_DEBUG(TAG, "InputManager: Factory reset press callback registered");
|
||||
}
|
||||
|
||||
void InputManager::setFactoryResetLongPressCallback(ButtonCallback callback) {
|
||||
_factoryResetButton.config.onLongPress = callback;
|
||||
LOG_DEBUG(TAG, "InputManager: Factory reset long press callback registered");
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// STATUS METHODS
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
bool InputManager::isFactoryResetPressed() const {
|
||||
return _factoryResetButton.state != ButtonState::IDLE;
|
||||
}
|
||||
|
||||
uint32_t InputManager::getFactoryResetPressDuration() const {
|
||||
if (_factoryResetButton.state == ButtonState::IDLE) {
|
||||
return 0;
|
||||
}
|
||||
return millis() - _factoryResetButton.pressStartTime;
|
||||
}
|
||||
|
||||
bool InputManager::isHealthy() const {
|
||||
if (!_initialized) {
|
||||
LOG_DEBUG(TAG, "InputManager: Unhealthy - not initialized");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Could add more health checks here if needed
|
||||
return true;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// FREERTOS TASK
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void InputManager::inputTaskFunction(void* parameter) {
|
||||
InputManager* manager = static_cast<InputManager*>(parameter);
|
||||
|
||||
LOG_INFO(TAG, "InputManager: Input task started (polling every %dms)", INPUT_POLL_RATE_MS);
|
||||
|
||||
TickType_t lastWakeTime = xTaskGetTickCount();
|
||||
const TickType_t pollInterval = pdMS_TO_TICKS(INPUT_POLL_RATE_MS);
|
||||
|
||||
while (true) {
|
||||
// Update button states
|
||||
manager->update();
|
||||
|
||||
// Wait for next poll interval
|
||||
vTaskDelayUntil(&lastWakeTime, pollInterval);
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// UPDATE LOGIC (Called by task)
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void InputManager::update() {
|
||||
if (!_initialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Update factory reset button
|
||||
updateButton(_factoryResetButton);
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// PRIVATE METHODS
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void InputManager::configureButton(const ButtonConfig& config) {
|
||||
// Configure pin as input with pull-up (for active-low buttons)
|
||||
if (config.activeHigh) {
|
||||
pinMode(config.pin, INPUT);
|
||||
} else {
|
||||
pinMode(config.pin, INPUT_PULLUP);
|
||||
}
|
||||
|
||||
LOG_DEBUG(TAG, "InputManager: Configured GPIO %d as input (%s)",
|
||||
config.pin, config.activeHigh ? "active-high" : "active-low");
|
||||
}
|
||||
|
||||
bool InputManager::readButtonState(const ButtonData& button) const {
|
||||
bool rawState = digitalRead(button.config.pin);
|
||||
|
||||
// Invert reading if active-low
|
||||
if (!button.config.activeHigh) {
|
||||
rawState = !rawState;
|
||||
}
|
||||
|
||||
return rawState;
|
||||
}
|
||||
|
||||
void InputManager::updateButton(ButtonData& button) {
|
||||
uint32_t now = millis();
|
||||
bool currentState = readButtonState(button);
|
||||
|
||||
// State machine for button handling
|
||||
switch (button.state) {
|
||||
case ButtonState::IDLE:
|
||||
// Waiting for button press
|
||||
if (currentState && !button.lastRawState) {
|
||||
// Button just pressed - start debouncing
|
||||
button.state = ButtonState::DEBOUNCING_PRESS;
|
||||
button.stateChangeTime = now;
|
||||
LOG_DEBUG(TAG, "InputManager: Button press detected on GPIO %d - debouncing",
|
||||
button.config.pin);
|
||||
}
|
||||
break;
|
||||
|
||||
case ButtonState::DEBOUNCING_PRESS:
|
||||
// Debouncing press
|
||||
if (!currentState) {
|
||||
// Button released during debounce - false trigger
|
||||
button.state = ButtonState::IDLE;
|
||||
LOG_DEBUG(TAG, "InputManager: False trigger on GPIO %d (released during debounce)",
|
||||
button.config.pin);
|
||||
} else if (now - button.stateChangeTime >= button.config.debounceMs) {
|
||||
// Debounce time passed - confirm press
|
||||
button.state = ButtonState::LONG_PRESS_PENDING;
|
||||
button.pressStartTime = now;
|
||||
button.longPressTriggered = false;
|
||||
LOG_INFO(TAG, "InputManager: Button press confirmed on GPIO %d",
|
||||
button.config.pin);
|
||||
}
|
||||
break;
|
||||
|
||||
case ButtonState::LONG_PRESS_PENDING:
|
||||
// Button is pressed, waiting to see if it's a long press
|
||||
if (!currentState) {
|
||||
// Button released before long press threshold - it's a short press
|
||||
button.state = ButtonState::DEBOUNCING_RELEASE;
|
||||
button.stateChangeTime = now;
|
||||
LOG_INFO(TAG, "InputManager: Short press detected on GPIO %d (held for %lums)",
|
||||
button.config.pin, now - button.pressStartTime);
|
||||
} else if (now - button.pressStartTime >= button.config.longPressMs) {
|
||||
// Long press threshold reached
|
||||
button.state = ButtonState::LONG_PRESSED;
|
||||
button.longPressTriggered = true;
|
||||
|
||||
LOG_WARNING(TAG, "InputManager: LONG PRESS DETECTED on GPIO %d (held for %lums)",
|
||||
button.config.pin, now - button.pressStartTime);
|
||||
|
||||
// Trigger long press callback
|
||||
if (button.config.onLongPress) {
|
||||
button.config.onLongPress();
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case ButtonState::LONG_PRESSED:
|
||||
// Long press has been triggered, waiting for release
|
||||
if (!currentState) {
|
||||
button.state = ButtonState::DEBOUNCING_RELEASE;
|
||||
button.stateChangeTime = now;
|
||||
LOG_INFO(TAG, "InputManager: Long press released on GPIO %d (total duration: %lums)",
|
||||
button.config.pin, now - button.pressStartTime);
|
||||
}
|
||||
break;
|
||||
|
||||
case ButtonState::DEBOUNCING_RELEASE:
|
||||
// Debouncing release
|
||||
if (currentState) {
|
||||
// Button pressed again during release debounce - go back to pressed state
|
||||
button.state = ButtonState::LONG_PRESS_PENDING;
|
||||
LOG_DEBUG(TAG, "InputManager: Button re-pressed during release debounce on GPIO %d",
|
||||
button.config.pin);
|
||||
} else if (now - button.stateChangeTime >= button.config.debounceMs) {
|
||||
// Debounce time passed - confirm release
|
||||
button.state = ButtonState::IDLE;
|
||||
|
||||
// If it was a short press (not long press), trigger the press callback
|
||||
if (!button.longPressTriggered && button.config.onPress) {
|
||||
LOG_INFO(TAG, "InputManager: Triggering press callback for GPIO %d",
|
||||
button.config.pin);
|
||||
button.config.onPress();
|
||||
}
|
||||
|
||||
LOG_DEBUG(TAG, "InputManager: Button release confirmed on GPIO %d",
|
||||
button.config.pin);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// Store last raw state for edge detection
|
||||
button.lastRawState = currentState;
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* INPUTMANAGER.HPP - Button and Input Handling System
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 🎛️ INPUT HANDLING FOR VESPER 🎛️
|
||||
*
|
||||
* This class manages all physical input handling including button presses,
|
||||
* long presses, and debouncing logic. It provides clean event-based callbacks
|
||||
* for different input actions.
|
||||
*
|
||||
* 🏗️ ARCHITECTURE:
|
||||
* • Non-blocking button state management
|
||||
* • Software debouncing with configurable timing
|
||||
* • Long press detection
|
||||
* • Event-driven callbacks for actions
|
||||
* • Easy expansion for multiple inputs
|
||||
*
|
||||
* 🔘 CURRENT INPUTS:
|
||||
* • GPIO 0: Factory Reset Button (Long Press = 10s)
|
||||
*
|
||||
* ⚙️ FEATURES:
|
||||
* • Debounce filtering (default 50ms)
|
||||
* • Long press detection (configurable, default 10s)
|
||||
* • Active-low button handling (pull-up enabled)
|
||||
* • Non-blocking state machine
|
||||
*
|
||||
* 📋 VERSION: 1.0
|
||||
* 📅 DATE: 2025
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <functional>
|
||||
|
||||
class InputManager {
|
||||
public:
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// CALLBACK TYPES
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
using ButtonCallback = std::function<void()>;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// BUTTON CONFIGURATION
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
struct ButtonConfig {
|
||||
uint8_t pin; // GPIO pin number
|
||||
bool activeHigh; // true = active high, false = active low
|
||||
uint32_t debounceMs; // Debounce time in milliseconds
|
||||
uint32_t longPressMs; // Long press threshold in milliseconds
|
||||
ButtonCallback onPress; // Callback for normal press
|
||||
ButtonCallback onLongPress; // Callback for long press
|
||||
|
||||
ButtonConfig(uint8_t p = 0, bool ah = false, uint32_t db = 50, uint32_t lp = 10000)
|
||||
: pin(p), activeHigh(ah), debounceMs(db), longPressMs(lp),
|
||||
onPress(nullptr), onLongPress(nullptr) {}
|
||||
};
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// CONSTRUCTOR & INITIALIZATION
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
InputManager();
|
||||
~InputManager();
|
||||
|
||||
/**
|
||||
* @brief Initialize the InputManager and start the input task
|
||||
* @return true if initialization successful
|
||||
*/
|
||||
bool begin();
|
||||
|
||||
/**
|
||||
* @brief Stop the input task and cleanup
|
||||
*/
|
||||
void end();
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// CALLBACK REGISTRATION
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Set callback for factory reset button press
|
||||
* @param callback Function to call on short press
|
||||
*/
|
||||
void setFactoryResetPressCallback(ButtonCallback callback);
|
||||
|
||||
/**
|
||||
* @brief Set callback for factory reset button long press
|
||||
* @param callback Function to call on long press (10s)
|
||||
*/
|
||||
void setFactoryResetLongPressCallback(ButtonCallback callback);
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// STATUS METHODS
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Check if factory reset button is currently pressed
|
||||
* @return true if button is pressed
|
||||
*/
|
||||
bool isFactoryResetPressed() const;
|
||||
|
||||
/**
|
||||
* @brief Get how long the factory reset button has been pressed
|
||||
* @return Duration in milliseconds (0 if not pressed)
|
||||
*/
|
||||
uint32_t getFactoryResetPressDuration() const;
|
||||
|
||||
/**
|
||||
* @brief Check if InputManager is healthy and functioning
|
||||
* @return true if all inputs are properly configured
|
||||
*/
|
||||
bool isHealthy() const;
|
||||
|
||||
private:
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// BUTTON STATE TRACKING
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
enum class ButtonState {
|
||||
IDLE, // Button not pressed
|
||||
DEBOUNCING_PRESS, // Waiting for debounce on press
|
||||
PRESSED, // Button confirmed pressed (short)
|
||||
LONG_PRESS_PENDING, // Button held, waiting for long press threshold
|
||||
LONG_PRESSED, // Long press confirmed and triggered
|
||||
DEBOUNCING_RELEASE // Waiting for debounce on release
|
||||
};
|
||||
|
||||
struct ButtonData {
|
||||
ButtonConfig config;
|
||||
ButtonState state;
|
||||
bool lastRawState; // Last raw reading from pin
|
||||
uint32_t stateChangeTime; // When state last changed
|
||||
uint32_t pressStartTime; // When button was first pressed
|
||||
bool longPressTriggered; // Has long press callback been fired?
|
||||
|
||||
ButtonData() : state(ButtonState::IDLE), lastRawState(false),
|
||||
stateChangeTime(0), pressStartTime(0),
|
||||
longPressTriggered(false) {}
|
||||
};
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// MEMBER VARIABLES
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
ButtonData _factoryResetButton;
|
||||
bool _initialized;
|
||||
|
||||
// FreeRTOS task management
|
||||
TaskHandle_t _inputTaskHandle;
|
||||
static constexpr uint32_t INPUT_TASK_STACK_SIZE = 4096;
|
||||
static constexpr UBaseType_t INPUT_TASK_PRIORITY = 2;
|
||||
static constexpr uint32_t INPUT_POLL_RATE_MS = 10; // Poll every 10ms
|
||||
|
||||
// Static instance for task callback
|
||||
static InputManager* _instance;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// PRIVATE METHODS
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Configure a single button pin
|
||||
* @param config Button configuration
|
||||
*/
|
||||
void configureButton(const ButtonConfig& config);
|
||||
|
||||
/**
|
||||
* @brief Update state of a single button
|
||||
* @param button Button data to update
|
||||
*/
|
||||
void updateButton(ButtonData& button);
|
||||
|
||||
/**
|
||||
* @brief Read current state of button (handles active high/low)
|
||||
* @param button Button to read
|
||||
* @return true if button is currently pressed
|
||||
*/
|
||||
bool readButtonState(const ButtonData& button) const;
|
||||
|
||||
/**
|
||||
* @brief Static task function for FreeRTOS
|
||||
* @param parameter Pointer to InputManager instance
|
||||
*/
|
||||
static void inputTaskFunction(void* parameter);
|
||||
|
||||
/**
|
||||
* @brief Internal update method called by task
|
||||
*/
|
||||
void update();
|
||||
};
|
||||
@@ -0,0 +1,251 @@
|
||||
#include "Logging.hpp"
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// STATIC MEMBER INITIALIZATION
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
Logging::LogLevel Logging::_serialLevel = Logging::VERBOSE;
|
||||
Logging::LogLevel Logging::_mqttLevel = Logging::NONE;
|
||||
Logging::LogLevel Logging::_sdLevel = Logging::NONE;
|
||||
|
||||
std::map<String, Logging::LogLevel> Logging::_serialOverrides;
|
||||
std::map<String, Logging::LogLevel> Logging::_mqttOverrides;
|
||||
std::map<String, Logging::LogLevel> Logging::_sdOverrides;
|
||||
|
||||
Logging::MqttPublishCallback Logging::_mqttCallback = nullptr;
|
||||
Logging::SdWriteCallback Logging::_sdCallback = nullptr;
|
||||
String Logging::_mqttLogTopic = "";
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// GLOBAL CHANNEL LEVEL SETTERS / GETTERS
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void Logging::setSerialLevel(LogLevel level) {
|
||||
_serialLevel = level;
|
||||
Serial.printf("[Logger] Serial level -> %d\n", level);
|
||||
}
|
||||
|
||||
void Logging::setMqttLevel(LogLevel level) {
|
||||
_mqttLevel = level;
|
||||
Serial.printf("[Logger] MQTT level -> %d\n", level);
|
||||
}
|
||||
|
||||
void Logging::setSdLevel(LogLevel level) {
|
||||
_sdLevel = level;
|
||||
Serial.printf("[Logger] SD level -> %d\n", level);
|
||||
}
|
||||
|
||||
Logging::LogLevel Logging::getSerialLevel() { return _serialLevel; }
|
||||
Logging::LogLevel Logging::getMqttLevel() { return _mqttLevel; }
|
||||
Logging::LogLevel Logging::getSdLevel() { return _sdLevel; }
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// PER-SUBSYSTEM OVERRIDES
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void Logging::setSubsystemSerialLevel(const char* tag, LogLevel level) {
|
||||
_serialOverrides[String(tag)] = level;
|
||||
}
|
||||
|
||||
void Logging::setSubsystemMqttLevel(const char* tag, LogLevel level) {
|
||||
_mqttOverrides[String(tag)] = level;
|
||||
}
|
||||
|
||||
void Logging::setSubsystemSdLevel(const char* tag, LogLevel level) {
|
||||
_sdOverrides[String(tag)] = level;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// CALLBACK REGISTRATION
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void Logging::setMqttPublishCallback(MqttPublishCallback callback, const String& logTopic) {
|
||||
_mqttCallback = callback;
|
||||
_mqttLogTopic = logTopic;
|
||||
Serial.printf("[Logger] MQTT publish callback registered: %s\n", logTopic.c_str());
|
||||
}
|
||||
|
||||
void Logging::setSdWriteCallback(SdWriteCallback callback) {
|
||||
_sdCallback = callback;
|
||||
Serial.printf("[Logger] SD write callback registered\n");
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// PUBLIC LOGGING FUNCTIONS
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void Logging::error(const char* tag, const char* format, ...) {
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
log(ERROR, "ERROR", tag, format, args);
|
||||
va_end(args);
|
||||
}
|
||||
|
||||
void Logging::warning(const char* tag, const char* format, ...) {
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
log(WARNING, "WARN", tag, format, args);
|
||||
va_end(args);
|
||||
}
|
||||
|
||||
void Logging::info(const char* tag, const char* format, ...) {
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
log(INFO, "INFO", tag, format, args);
|
||||
va_end(args);
|
||||
}
|
||||
|
||||
void Logging::debug(const char* tag, const char* format, ...) {
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
log(DEBUG, "DEBG", tag, format, args);
|
||||
va_end(args);
|
||||
}
|
||||
|
||||
void Logging::verbose(const char* tag, const char* format, ...) {
|
||||
va_list args;
|
||||
va_start(args, format);
|
||||
log(VERBOSE, "VERB", tag, format, args);
|
||||
va_end(args);
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// UTILITIES
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
bool Logging::isLevelEnabled(LogLevel level) {
|
||||
return _serialLevel >= level;
|
||||
}
|
||||
|
||||
String Logging::levelToString(LogLevel level) {
|
||||
switch (level) {
|
||||
case ERROR: return "ERROR";
|
||||
case WARNING: return "WARNING";
|
||||
case INFO: return "INFO";
|
||||
case DEBUG: return "DEBUG";
|
||||
case VERBOSE: return "VERBOSE";
|
||||
default: return "NONE";
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// PRIVATE: RESOLVE EFFECTIVE LEVEL FOR A TAG ON A CHANNEL
|
||||
// Returns the override level if one exists for this tag, otherwise the global level.
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
Logging::LogLevel Logging::resolveLevel(const char* tag, LogLevel globalLevel, const std::map<String, LogLevel>& overrides) {
|
||||
auto it = overrides.find(String(tag));
|
||||
if (it != overrides.end()) {
|
||||
return it->second;
|
||||
}
|
||||
return globalLevel;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// PRIVATE: CORE LOG DISPATCH
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void Logging::log(LogLevel level, const char* levelStr, const char* tag, const char* format, va_list args) {
|
||||
// Resolve effective level for each channel (override wins over global)
|
||||
LogLevel serialEffective = resolveLevel(tag, _serialLevel, _serialOverrides);
|
||||
LogLevel mqttEffective = resolveLevel(tag, _mqttLevel, _mqttOverrides);
|
||||
LogLevel sdEffective = resolveLevel(tag, _sdLevel, _sdOverrides);
|
||||
|
||||
bool serialEnabled = (serialEffective >= level);
|
||||
bool mqttEnabled = (mqttEffective >= level) && (_mqttCallback != nullptr);
|
||||
bool sdEnabled = (sdEffective >= level) && (_sdCallback != nullptr);
|
||||
|
||||
// Early exit if nothing will output this message
|
||||
if (!serialEnabled && !mqttEnabled && !sdEnabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Format the message once
|
||||
char buffer[512];
|
||||
vsnprintf(buffer, sizeof(buffer), format, args);
|
||||
|
||||
// Serial output
|
||||
if (serialEnabled) {
|
||||
Serial.printf("[%s][%s] %s\n", levelStr, tag, buffer);
|
||||
}
|
||||
|
||||
// MQTT output
|
||||
if (mqttEnabled) {
|
||||
publishToMqtt(level, levelStr, tag, buffer);
|
||||
}
|
||||
|
||||
// SD output
|
||||
if (sdEnabled) {
|
||||
writeToSd(level, levelStr, tag, buffer);
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// PRIVATE: MQTT PUBLISH
|
||||
// Uses a re-entrancy guard to prevent log-of-a-log recursion.
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void Logging::publishToMqtt(LogLevel level, const char* levelStr, const char* tag, const char* message) {
|
||||
if (!_mqttCallback || _mqttLogTopic.isEmpty()) return;
|
||||
|
||||
static bool isPublishing = false;
|
||||
if (isPublishing) return;
|
||||
isPublishing = true;
|
||||
|
||||
// JSON: {"level":"WARNING","subsystem":"BellEngine","message":"...","timestamp":12345}
|
||||
String payload;
|
||||
payload.reserve(600);
|
||||
payload = "{\"level\":\"";
|
||||
payload += levelStr;
|
||||
payload += "\",\"subsystem\":\"";
|
||||
payload += tag;
|
||||
payload += "\",\"message\":\"";
|
||||
|
||||
// Escape special JSON characters
|
||||
const char* p = message;
|
||||
while (*p) {
|
||||
char c = *p++;
|
||||
if (c == '\\') payload += "\\\\";
|
||||
else if (c == '"') payload += "\\\"";
|
||||
else if (c == '\n') payload += "\\n";
|
||||
else if (c == '\r') payload += "\\r";
|
||||
else payload += c;
|
||||
}
|
||||
|
||||
payload += "\",\"timestamp\":";
|
||||
payload += millis();
|
||||
payload += "}";
|
||||
|
||||
_mqttCallback(_mqttLogTopic, payload, 1);
|
||||
|
||||
isPublishing = false;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// PRIVATE: SD WRITE
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void Logging::writeToSd(LogLevel level, const char* levelStr, const char* tag, const char* message) {
|
||||
if (!_sdCallback) return;
|
||||
|
||||
static bool isWriting = false;
|
||||
if (isWriting) return;
|
||||
isWriting = true;
|
||||
|
||||
// Plain text line: [WARN][BellEngine] message (timestamp: 12345ms)
|
||||
String line;
|
||||
line.reserve(300);
|
||||
line = "[";
|
||||
line += levelStr;
|
||||
line += "][";
|
||||
line += tag;
|
||||
line += "] ";
|
||||
line += message;
|
||||
line += " (";
|
||||
line += millis();
|
||||
line += "ms)";
|
||||
|
||||
_sdCallback(line);
|
||||
|
||||
isWriting = false;
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* LOGGING.HPP - Subsystem-Aware Centralized Logging System
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 📝 THE INFORMATION CHRONICLER OF VESPER 📝
|
||||
*
|
||||
* Three independent output channels, each with their own level:
|
||||
* • Serial — USB debugging, local connection
|
||||
* • MQTT — Remote troubleshooting via web dashboard
|
||||
* • SD — Persistent log storage for post-mortem analysis
|
||||
*
|
||||
* Per-subsystem filtering: each subsystem tag can have its own level
|
||||
* overrides per channel. If no override is set, the global channel
|
||||
* level applies. Set a tag's level to NONE on a specific channel to
|
||||
* silence it entirely on that channel (e.g. MQTT internals on MQTT).
|
||||
*
|
||||
* Usage in each .cpp file:
|
||||
* #define TAG "BellEngine" // one line at the top
|
||||
* LOG_INFO(TAG, "Ring scheduled"); // all calls include the tag
|
||||
*
|
||||
* The JSON payload sent over MQTT includes the subsystem field:
|
||||
* {"level":"WARNING","subsystem":"BellEngine","message":"...","timestamp":12345}
|
||||
*
|
||||
* 📋 VERSION: 3.0 (Subsystem-aware logging)
|
||||
* 📅 DATE: 2025
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#ifndef LOGGING_HPP
|
||||
#define LOGGING_HPP
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <map>
|
||||
#include <functional>
|
||||
|
||||
class Logging {
|
||||
public:
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// LOG LEVELS
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
enum LogLevel {
|
||||
NONE = 0, // No output
|
||||
ERROR = 1, // Errors only
|
||||
WARNING = 2, // Warnings and errors
|
||||
INFO = 3, // Info, warnings, errors
|
||||
DEBUG = 4, // Debug detail
|
||||
VERBOSE = 5 // Everything
|
||||
};
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// CALLBACK TYPES
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
using MqttPublishCallback = std::function<void(const String& topic, const String& payload, int qos)>;
|
||||
using SdWriteCallback = std::function<void(const String& line)>;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// GLOBAL CHANNEL LEVELS
|
||||
// Set the baseline level for each output channel.
|
||||
// Per-subsystem overrides take precedence when set.
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
static void setSerialLevel(LogLevel level);
|
||||
static void setMqttLevel(LogLevel level);
|
||||
static void setSdLevel(LogLevel level);
|
||||
|
||||
static LogLevel getSerialLevel();
|
||||
static LogLevel getMqttLevel();
|
||||
static LogLevel getSdLevel();
|
||||
|
||||
// Legacy compatibility (maps to serial level)
|
||||
static void setLevel(LogLevel level) { setSerialLevel(level); }
|
||||
static LogLevel getLevel() { return getSerialLevel(); }
|
||||
static void setMqttLogLevel(LogLevel level) { setMqttLevel(level); }
|
||||
static LogLevel getMqttLogLevel() { return getMqttLevel(); }
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// PER-SUBSYSTEM LEVEL OVERRIDES
|
||||
// Call these at startup to silence or focus specific subsystems per channel.
|
||||
// Pass NONE to completely silence a subsystem on a channel.
|
||||
// Pass a level to cap that subsystem at that level on that channel.
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
static void setSubsystemSerialLevel(const char* tag, LogLevel level);
|
||||
static void setSubsystemMqttLevel(const char* tag, LogLevel level);
|
||||
static void setSubsystemSdLevel(const char* tag, LogLevel level);
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// OUTPUT CHANNEL REGISTRATION
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
static void setMqttPublishCallback(MqttPublishCallback callback, const String& logTopic);
|
||||
static void setSdWriteCallback(SdWriteCallback callback);
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// LOGGING FUNCTIONS (tag = subsystem name, e.g. "BellEngine")
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
static void error(const char* tag, const char* format, ...);
|
||||
static void warning(const char* tag, const char* format, ...);
|
||||
static void info(const char* tag, const char* format, ...);
|
||||
static void debug(const char* tag, const char* format, ...);
|
||||
static void verbose(const char* tag, const char* format, ...);
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// UTILITIES
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
static bool isLevelEnabled(LogLevel level);
|
||||
static String levelToString(LogLevel level);
|
||||
|
||||
private:
|
||||
// Global channel levels
|
||||
static LogLevel _serialLevel;
|
||||
static LogLevel _mqttLevel;
|
||||
static LogLevel _sdLevel;
|
||||
|
||||
// Per-subsystem overrides per channel (tag -> level)
|
||||
// A value of NONE means "suppress this subsystem on this channel entirely"
|
||||
static std::map<String, LogLevel> _serialOverrides;
|
||||
static std::map<String, LogLevel> _mqttOverrides;
|
||||
static std::map<String, LogLevel> _sdOverrides;
|
||||
|
||||
// Output channel callbacks
|
||||
static MqttPublishCallback _mqttCallback;
|
||||
static SdWriteCallback _sdCallback;
|
||||
static String _mqttLogTopic;
|
||||
|
||||
// Core internal methods
|
||||
static void log(LogLevel level, const char* levelStr, const char* tag, const char* format, va_list args);
|
||||
static void publishToMqtt(LogLevel level, const char* levelStr, const char* tag, const char* message);
|
||||
static void writeToSd(LogLevel level, const char* levelStr, const char* tag, const char* message);
|
||||
|
||||
// Resolve effective level for a tag on a channel
|
||||
static LogLevel resolveLevel(const char* tag, LogLevel globalLevel, const std::map<String, LogLevel>& overrides);
|
||||
};
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// MACROS
|
||||
// Each .cpp file defines: #define TAG "SubsystemName"
|
||||
// Then uses: LOG_INFO(TAG, "message %d", value)
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
#define LOG_ERROR(tag, ...) Logging::error(tag, __VA_ARGS__)
|
||||
#define LOG_WARNING(tag, ...) Logging::warning(tag, __VA_ARGS__)
|
||||
#define LOG_INFO(tag, ...) Logging::info(tag, __VA_ARGS__)
|
||||
#define LOG_DEBUG(tag, ...) Logging::debug(tag, __VA_ARGS__)
|
||||
#define LOG_VERBOSE(tag, ...) Logging::verbose(tag, __VA_ARGS__)
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,610 @@
|
||||
#include "Networking.hpp"
|
||||
|
||||
#define TAG "Networking"
|
||||
#include "../ConfigManager/ConfigManager.hpp"
|
||||
#include "../Logging/Logging.hpp"
|
||||
#include <WiFiManager.h>
|
||||
#include <SPI.h>
|
||||
|
||||
// Static instance for callbacks (with safety checks)
|
||||
Networking* Networking::_instance = nullptr;
|
||||
|
||||
Networking::Networking(ConfigManager& configManager)
|
||||
: _configManager(configManager)
|
||||
, _state(NetworkState::DISCONNECTED)
|
||||
, _activeConnection(ConnectionType::NONE)
|
||||
, _lastConnectionAttempt(0)
|
||||
, _bootSequenceComplete(false)
|
||||
, _ethernetCableConnected(false)
|
||||
, _wifiConnectionFailures(0)
|
||||
, _wifiManager(nullptr)
|
||||
, _reconnectionTimer(nullptr) {
|
||||
|
||||
// Safety check for multiple instances
|
||||
if (_instance != nullptr) {
|
||||
LOG_WARNING(TAG, "Multiple Networking instances detected! Previous instance will be overridden.");
|
||||
}
|
||||
|
||||
_instance = this;
|
||||
_wifiManager = new WiFiManager();
|
||||
}
|
||||
|
||||
Networking::~Networking() {
|
||||
// Clear static instance safely
|
||||
if (_instance == this) {
|
||||
_instance = nullptr;
|
||||
}
|
||||
|
||||
// Cleanup timer
|
||||
if (_reconnectionTimer) {
|
||||
xTimerDelete(_reconnectionTimer, portMAX_DELAY);
|
||||
_reconnectionTimer = nullptr;
|
||||
}
|
||||
|
||||
// Cleanup WiFiManager
|
||||
if (_wifiManager) {
|
||||
delete _wifiManager;
|
||||
_wifiManager = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void Networking::begin() {
|
||||
LOG_INFO(TAG, "Initializing Networking System");
|
||||
|
||||
// Create reconnection timer (one-shot — restarted manually only when still disconnected)
|
||||
_reconnectionTimer = xTimerCreate("reconnectionTimer", pdMS_TO_TICKS(RECONNECTION_INTERVAL),
|
||||
pdFALSE, (void*)0, reconnectionTimerCallback);
|
||||
|
||||
// Setup network event handler
|
||||
WiFi.onEvent(networkEventHandler);
|
||||
|
||||
// Configure WiFiManager
|
||||
_wifiManager->setDebugOutput(false);
|
||||
_wifiManager->setConfigPortalTimeout(300); // 5 minutes
|
||||
|
||||
// Clear Previous Settings, USE once to test.
|
||||
//_wifiManager->resetSettings();
|
||||
|
||||
// Check if permanent AP mode is enabled
|
||||
if (_configManager.getPermanentAPMode()) {
|
||||
LOG_INFO(TAG, "Permanent AP mode enabled - starting AP mode on 192.168.4.1");
|
||||
startPermanentAPMode();
|
||||
return;
|
||||
}
|
||||
|
||||
// ETHERNET DISABLED - WiFi only mode
|
||||
// Start Ethernet hardware
|
||||
// auto& hwConfig = _configManager.getHardwareConfig();
|
||||
// ETH.begin(hwConfig.ethPhyType, hwConfig.ethPhyAddr, hwConfig.ethPhyCs,
|
||||
// hwConfig.ethPhyIrq, hwConfig.ethPhyRst, SPI);
|
||||
|
||||
// Start connection sequence - Skip Ethernet, go directly to WiFi
|
||||
LOG_INFO(TAG, "Starting WiFi connection (Ethernet disabled)...");
|
||||
startWiFiConnection();
|
||||
}
|
||||
|
||||
void Networking::startEthernetConnection() {
|
||||
// ETHERNET DISABLED - Skip to WiFi immediately
|
||||
LOG_DEBUG(TAG, "Ethernet connection disabled - falling back to WiFi");
|
||||
startWiFiConnection();
|
||||
|
||||
// Original Ethernet code (DISABLED):
|
||||
// LOG_INFO(TAG, "Attempting Ethernet connection...");
|
||||
// setState(NetworkState::CONNECTING_ETHERNET);
|
||||
//
|
||||
// // Check if Ethernet hardware initialization failed
|
||||
// if (!ETH.linkUp()) {
|
||||
// LOG_WARNING(TAG, "Ethernet hardware not detected or failed to initialize");
|
||||
// LOG_INFO(TAG, "Falling back to WiFi immediately");
|
||||
// startWiFiConnection();
|
||||
// return;
|
||||
// }
|
||||
//
|
||||
// // Ethernet will auto-connect via events
|
||||
// // Set timeout for Ethernet attempt (5 seconds)
|
||||
// _lastConnectionAttempt = millis();
|
||||
//
|
||||
// // Start reconnection timer to handle timeout
|
||||
// xTimerStart(_reconnectionTimer, 0);
|
||||
}
|
||||
|
||||
void Networking::startWiFiConnection() {
|
||||
LOG_INFO(TAG, "Attempting WiFi connection...");
|
||||
setState(NetworkState::CONNECTING_WIFI);
|
||||
|
||||
// ALWAYS try default credentials first (for bundled router deployment)
|
||||
auto& netConfig = _configManager.getNetworkConfig();
|
||||
|
||||
LOG_INFO(TAG, "Using DEFAULT WiFi credentials - SSID: %s", netConfig.defaultWifiSsid.c_str());
|
||||
|
||||
applyNetworkConfig(false); // false = WiFi config
|
||||
WiFi.mode(WIFI_STA);
|
||||
WiFi.begin(netConfig.defaultWifiSsid.c_str(), netConfig.defaultWifiPsk.c_str());
|
||||
|
||||
_lastConnectionAttempt = millis();
|
||||
xTimerStart(_reconnectionTimer, 0);
|
||||
|
||||
// Original WiFiManager fallback code (DISABLED for fixed deployment):
|
||||
// // First, try default credentials if this is the first boot attempt
|
||||
// if (!_bootSequenceComplete && !hasValidWiFiCredentials()) {
|
||||
// LOG_INFO(TAG, "No saved credentials - trying default WiFi credentials");
|
||||
// auto& netConfig = _configManager.getNetworkConfig();
|
||||
//
|
||||
// applyNetworkConfig(false); // false = WiFi config
|
||||
// WiFi.mode(WIFI_STA);
|
||||
// WiFi.begin(netConfig.defaultWifiSsid.c_str(), netConfig.defaultWifiPsk.c_str());
|
||||
//
|
||||
// _lastConnectionAttempt = millis();
|
||||
// xTimerStart(_reconnectionTimer, 0);
|
||||
// return;
|
||||
// }
|
||||
//
|
||||
// // Check if we have valid saved credentials
|
||||
// if (!hasValidWiFiCredentials()) {
|
||||
// LOG_WARNING(TAG, "No valid WiFi credentials found");
|
||||
// if (!_bootSequenceComplete) {
|
||||
// // No credentials during boot - start portal
|
||||
// startWiFiPortal();
|
||||
// }
|
||||
// return;
|
||||
// }
|
||||
//
|
||||
// // Get and log saved credentials (for debugging)
|
||||
// String savedSSID = _wifiManager->getWiFiSSID(true);
|
||||
// LOG_INFO(TAG, "Using WiFiManager saved credentials - SSID: %s", savedSSID.c_str());
|
||||
//
|
||||
// applyNetworkConfig(false); // false = WiFi config
|
||||
// WiFi.mode(WIFI_STA);
|
||||
//
|
||||
// // Let WiFiManager handle credentials (uses saved SSID/password)
|
||||
// WiFi.begin();
|
||||
//
|
||||
// _lastConnectionAttempt = millis();
|
||||
//
|
||||
// // Start reconnection timer to handle timeout
|
||||
// xTimerStart(_reconnectionTimer, 0);
|
||||
}
|
||||
|
||||
void Networking::startWiFiPortal() {
|
||||
LOG_INFO(TAG, "Starting WiFi configuration portal...");
|
||||
setState(NetworkState::WIFI_PORTAL_MODE);
|
||||
|
||||
WiFi.mode(WIFI_AP_STA);
|
||||
|
||||
auto& netConfig = _configManager.getNetworkConfig();
|
||||
String apName = "Vesper-" + _configManager.getDeviceUID();
|
||||
|
||||
LOG_INFO(TAG, "WiFi Portal: SSID='%s', Password='%s'", apName.c_str(), netConfig.apPass.c_str());
|
||||
|
||||
// Add custom HTML to WiFiManager portal for permanent AP mode toggle
|
||||
String customHTML = "<br/><br/><h3>Network Mode</h3>";
|
||||
customHTML += "<p>Choose how to operate this device:</p>";
|
||||
customHTML += "<form action='/settings' method='get'>";
|
||||
customHTML += "<button type='submit' style='width:100%; padding:15px; margin:10px 0; background:#667eea; color:white; border:none; border-radius:8px; cursor:pointer; font-size:16px;'>";
|
||||
customHTML += "Open Settings (Switch to Permanent AP Mode)";
|
||||
customHTML += "</button>";
|
||||
customHTML += "</form>";
|
||||
customHTML += "<br/><p style='font-size:12px; color:#666;'>Note: You can configure network mode later at <b>http://192.168.4.1/settings</b> (AP mode) or <b>http://{device-ip}/settings</b> (Router mode)</p>";
|
||||
|
||||
_wifiManager->setCustomHeadElement(customHTML.c_str());
|
||||
|
||||
if (_wifiManager->autoConnect(apName.c_str(), netConfig.apPass.c_str())) {
|
||||
LOG_INFO(TAG, "WiFi configured successfully via portal");
|
||||
onWiFiConnected();
|
||||
} else {
|
||||
LOG_ERROR(TAG, "WiFi portal configuration failed");
|
||||
setState(NetworkState::DISCONNECTED);
|
||||
// Start reconnection timer to try again
|
||||
xTimerStart(_reconnectionTimer, 0);
|
||||
}
|
||||
}
|
||||
|
||||
void Networking::handleReconnection() {
|
||||
if (_state == NetworkState::CONNECTED_ETHERNET || _state == NetworkState::CONNECTED_WIFI) {
|
||||
return; // Already connected — timer is stopped in onWiFiConnected(), nothing to do
|
||||
}
|
||||
|
||||
LOG_DEBUG(TAG, "Attempting reconnection...");
|
||||
|
||||
// ETHERNET DISABLED - Skip Ethernet timeout checks
|
||||
// Check for Ethernet timeout (fall back to WiFi)
|
||||
// if (_state == NetworkState::CONNECTING_ETHERNET) {
|
||||
// unsigned long now = millis();
|
||||
// if (now - _lastConnectionAttempt > 5000) { // 5 second timeout
|
||||
// LOG_INFO(TAG, "Ethernet connection timeout - falling back to WiFi");
|
||||
// startWiFiConnection();
|
||||
// return;
|
||||
// }
|
||||
// return; // Still waiting for Ethernet
|
||||
// }
|
||||
|
||||
// Check for WiFi timeout
|
||||
if (_state == NetworkState::CONNECTING_WIFI) {
|
||||
unsigned long now = millis();
|
||||
if (now - _lastConnectionAttempt > 10000) { // 10 second timeout
|
||||
_wifiConnectionFailures++;
|
||||
LOG_WARNING(TAG, "WiFi connection timeout (failure #%d)", _wifiConnectionFailures);
|
||||
|
||||
// After 3 failed attempts during boot, start portal
|
||||
if (_wifiConnectionFailures >= MAX_WIFI_FAILURES) {
|
||||
LOG_ERROR(TAG, "Multiple WiFi connection failures - credentials may be invalid");
|
||||
|
||||
if (!_bootSequenceComplete) {
|
||||
// Boot not complete yet - open portal
|
||||
LOG_INFO(TAG, "Opening WiFi portal for reconfiguration");
|
||||
_wifiConnectionFailures = 0; // Reset counter
|
||||
startWiFiPortal();
|
||||
} else {
|
||||
// Boot already complete - just keep retrying
|
||||
LOG_WARNING(TAG, "WiFi connection lost - continuing retry attempts");
|
||||
// Reset counter after extended failure to prevent overflow
|
||||
if (_wifiConnectionFailures > 10) {
|
||||
_wifiConnectionFailures = 3;
|
||||
}
|
||||
_lastConnectionAttempt = now;
|
||||
startWiFiConnection(); // startWiFiConnection re-arms the timer
|
||||
}
|
||||
} else {
|
||||
// Retry WiFi connection — startWiFiConnection re-arms the timer
|
||||
startWiFiConnection();
|
||||
}
|
||||
} else {
|
||||
// Still within timeout window — re-arm timer to check again later
|
||||
xTimerStart(_reconnectionTimer, 0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// State is DISCONNECTED - WiFi only mode (Ethernet disabled)
|
||||
LOG_INFO(TAG, "Disconnected - trying WiFi");
|
||||
if (hasValidWiFiCredentials()) {
|
||||
startWiFiConnection(); // re-arms timer
|
||||
} else if (!_bootSequenceComplete) {
|
||||
// No credentials during boot - start portal
|
||||
startWiFiPortal();
|
||||
} else {
|
||||
LOG_WARNING(TAG, "No WiFi credentials and boot sequence complete - waiting");
|
||||
// Re-arm so we keep checking in case credentials arrive
|
||||
xTimerStart(_reconnectionTimer, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// HEALTH CHECK IMPLEMENTATION
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
bool Networking::isHealthy() const {
|
||||
// Check if we have any active connection
|
||||
if (_activeConnection == ConnectionType::NONE) {
|
||||
LOG_DEBUG(TAG, "Networking: Unhealthy - No active connection");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check connection state (Ethernet disabled, only check WiFi or AP)
|
||||
if (_state != NetworkState::CONNECTED_WIFI && _state != NetworkState::AP_MODE_PERMANENT) {
|
||||
LOG_DEBUG(TAG, "Networking: Unhealthy - Not in connected state");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check IP address validity
|
||||
String ip = getLocalIP();
|
||||
if (ip == "0.0.0.0" || ip.isEmpty()) {
|
||||
LOG_DEBUG(TAG, "Networking: Unhealthy - Invalid IP address");
|
||||
return false;
|
||||
}
|
||||
|
||||
// For WiFi connections, check signal strength
|
||||
if (_activeConnection == ConnectionType::WIFI) {
|
||||
if (WiFi.status() != WL_CONNECTED) {
|
||||
LOG_DEBUG(TAG, "Networking: Unhealthy - WiFi not connected");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check signal strength (RSSI should be better than -80 dBm)
|
||||
int32_t rssi = WiFi.RSSI();
|
||||
if (rssi < -80) {
|
||||
LOG_DEBUG(TAG, "Networking: Unhealthy - Poor WiFi signal: %d dBm", rssi);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ETHERNET DISABLED - Removed Ethernet link check
|
||||
// For Ethernet connections, check link status
|
||||
// if (_activeConnection == ConnectionType::ETHERNET) {
|
||||
// if (!ETH.linkUp()) {
|
||||
// LOG_DEBUG(TAG, "Networking: Unhealthy - Ethernet link down");
|
||||
// return false;
|
||||
// }
|
||||
// }
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void Networking::setState(NetworkState newState) {
|
||||
if (_state != newState) {
|
||||
LOG_DEBUG(TAG, "Network state: %d -> %d", (int)_state, (int)newState);
|
||||
_state = newState;
|
||||
}
|
||||
}
|
||||
|
||||
void Networking::setActiveConnection(ConnectionType type) {
|
||||
if (_activeConnection != type) {
|
||||
LOG_INFO(TAG, "Active connection changed: %d -> %d", (int)_activeConnection, (int)type);
|
||||
_activeConnection = type;
|
||||
}
|
||||
}
|
||||
|
||||
void Networking::notifyConnectionChange(bool connected) {
|
||||
if (connected && _onNetworkConnected) {
|
||||
_onNetworkConnected();
|
||||
} else if (!connected && _onNetworkDisconnected) {
|
||||
_onNetworkDisconnected();
|
||||
}
|
||||
}
|
||||
|
||||
// Event handlers (ETHERNET DISABLED)
|
||||
void Networking::onEthernetConnected() {
|
||||
// ETHERNET DISABLED - This should never be called
|
||||
LOG_WARNING(TAG, "Ethernet event received but Ethernet is disabled - ignoring");
|
||||
|
||||
// Original code (DISABLED):
|
||||
// LOG_INFO(TAG, "Ethernet connected successfully");
|
||||
// setState(NetworkState::CONNECTED_ETHERNET);
|
||||
// setActiveConnection(ConnectionType::ETHERNET);
|
||||
//
|
||||
// // Stop WiFi if it was running
|
||||
// if (WiFi.getMode() != WIFI_OFF) {
|
||||
// WiFi.disconnect(true);
|
||||
// WiFi.mode(WIFI_OFF);
|
||||
// }
|
||||
//
|
||||
// // Stop reconnection timer
|
||||
// xTimerStop(_reconnectionTimer, 0);
|
||||
//
|
||||
// notifyConnectionChange(true);
|
||||
}
|
||||
|
||||
void Networking::onEthernetDisconnected() {
|
||||
// ETHERNET DISABLED - This should never be called
|
||||
LOG_WARNING(TAG, "Ethernet disconnect event received but Ethernet is disabled - ignoring");
|
||||
|
||||
// Original code (DISABLED):
|
||||
// LOG_WARNING(TAG, "Ethernet disconnected");
|
||||
//
|
||||
// if (_activeConnection == ConnectionType::ETHERNET) {
|
||||
// setState(NetworkState::DISCONNECTED);
|
||||
// setActiveConnection(ConnectionType::NONE);
|
||||
// notifyConnectionChange(false);
|
||||
//
|
||||
// // Start reconnection attempts
|
||||
// xTimerStart(_reconnectionTimer, 0);
|
||||
// }
|
||||
}
|
||||
|
||||
void Networking::onWiFiConnected() {
|
||||
LOG_INFO(TAG, "WiFi connected successfully - IP: %s", WiFi.localIP().toString().c_str());
|
||||
setState(NetworkState::CONNECTED_WIFI);
|
||||
setActiveConnection(ConnectionType::WIFI);
|
||||
|
||||
// Reset failure counter on successful connection
|
||||
_wifiConnectionFailures = 0;
|
||||
|
||||
// Stop reconnection timer
|
||||
xTimerStop(_reconnectionTimer, 0);
|
||||
|
||||
// Mark boot sequence as complete
|
||||
_bootSequenceComplete = true;
|
||||
|
||||
notifyConnectionChange(true);
|
||||
}
|
||||
|
||||
void Networking::onWiFiDisconnected() {
|
||||
LOG_WARNING(TAG, "WiFi disconnected");
|
||||
|
||||
if (_activeConnection == ConnectionType::WIFI) {
|
||||
setState(NetworkState::DISCONNECTED);
|
||||
setActiveConnection(ConnectionType::NONE);
|
||||
notifyConnectionChange(false);
|
||||
|
||||
// Start reconnection attempts
|
||||
xTimerStart(_reconnectionTimer, 0);
|
||||
}
|
||||
}
|
||||
|
||||
void Networking::onEthernetCableChange(bool connected) {
|
||||
// ETHERNET DISABLED - Ignore cable events
|
||||
LOG_DEBUG(TAG, "Ethernet cable event ignored (Ethernet disabled)");
|
||||
|
||||
// Original code (DISABLED):
|
||||
// _ethernetCableConnected = connected;
|
||||
// LOG_INFO(TAG, "Ethernet cable %s", connected ? "connected" : "disconnected");
|
||||
//
|
||||
// if (connected && _activeConnection != ConnectionType::ETHERNET) {
|
||||
// // Cable connected and we're not using Ethernet - try to connect
|
||||
// startEthernetConnection();
|
||||
// }
|
||||
}
|
||||
|
||||
// Utility methods
|
||||
void Networking::applyNetworkConfig(bool ethernet) {
|
||||
auto& netConfig = _configManager.getNetworkConfig();
|
||||
|
||||
// ETHERNET DISABLED - Only apply WiFi config
|
||||
if (ethernet) {
|
||||
LOG_WARNING(TAG, "applyNetworkConfig called with ethernet=true but Ethernet is disabled");
|
||||
return;
|
||||
}
|
||||
|
||||
if (netConfig.useStaticIP) {
|
||||
LOG_INFO(TAG, "Applying static IP configuration");
|
||||
WiFi.config(netConfig.ip, netConfig.gateway, netConfig.subnet, netConfig.dns1, netConfig.dns2);
|
||||
} else {
|
||||
LOG_INFO(TAG, "Using DHCP configuration");
|
||||
}
|
||||
|
||||
WiFi.setHostname(netConfig.hostname.c_str());
|
||||
}
|
||||
|
||||
bool Networking::hasValidWiFiCredentials() {
|
||||
// Use WiFiManager's method to check if credentials are saved
|
||||
return _wifiManager->getWiFiIsSaved();
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Returns if Networking is connected
|
||||
bool Networking::isConnected() const {
|
||||
return _activeConnection != ConnectionType::NONE;
|
||||
}
|
||||
|
||||
String Networking::getLocalIP() const {
|
||||
switch (_activeConnection) {
|
||||
case ConnectionType::ETHERNET:
|
||||
// ETHERNET DISABLED - Should never reach here
|
||||
LOG_WARNING(TAG, "getLocalIP called with ETHERNET type but Ethernet is disabled");
|
||||
return "0.0.0.0";
|
||||
case ConnectionType::WIFI:
|
||||
return WiFi.localIP().toString();
|
||||
case ConnectionType::AP:
|
||||
return WiFi.softAPIP().toString();
|
||||
default:
|
||||
return "0.0.0.0";
|
||||
}
|
||||
}
|
||||
|
||||
String Networking::getGateway() const {
|
||||
switch (_activeConnection) {
|
||||
case ConnectionType::ETHERNET:
|
||||
// ETHERNET DISABLED - Should never reach here
|
||||
LOG_WARNING(TAG, "getGateway called with ETHERNET type but Ethernet is disabled");
|
||||
return "0.0.0.0";
|
||||
case ConnectionType::WIFI:
|
||||
return WiFi.gatewayIP().toString();
|
||||
default:
|
||||
return "0.0.0.0";
|
||||
}
|
||||
}
|
||||
|
||||
void Networking::forceReconnect() {
|
||||
LOG_INFO(TAG, "Forcing reconnection...");
|
||||
setState(NetworkState::RECONNECTING);
|
||||
setActiveConnection(ConnectionType::NONE);
|
||||
|
||||
// Disconnect everything
|
||||
if (WiFi.getMode() != WIFI_OFF) {
|
||||
WiFi.disconnect(true);
|
||||
WiFi.mode(WIFI_OFF);
|
||||
}
|
||||
|
||||
// Restart connection sequence - WiFi only (Ethernet disabled)
|
||||
delay(1000);
|
||||
startWiFiConnection();
|
||||
}
|
||||
|
||||
// Static callbacks
|
||||
void Networking::networkEventHandler(arduino_event_id_t event, arduino_event_info_t info) {
|
||||
if (!_instance) return;
|
||||
|
||||
LOG_DEBUG(TAG, "Network event: %d", event);
|
||||
|
||||
switch (event) {
|
||||
// ETHERNET EVENTS DISABLED - Ignored
|
||||
case ARDUINO_EVENT_ETH_START:
|
||||
case ARDUINO_EVENT_ETH_CONNECTED:
|
||||
case ARDUINO_EVENT_ETH_GOT_IP:
|
||||
case ARDUINO_EVENT_ETH_DISCONNECTED:
|
||||
case ARDUINO_EVENT_ETH_STOP:
|
||||
LOG_DEBUG(TAG, "Ethernet event ignored (Ethernet disabled)");
|
||||
break;
|
||||
|
||||
// WiFi events (ACTIVE)
|
||||
case ARDUINO_EVENT_WIFI_STA_GOT_IP:
|
||||
LOG_INFO(TAG, "WiFi Got IP: %s", WiFi.localIP().toString().c_str());
|
||||
_instance->onWiFiConnected();
|
||||
break;
|
||||
|
||||
case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:
|
||||
LOG_WARNING(TAG, "WiFi Disconnected");
|
||||
_instance->onWiFiDisconnected();
|
||||
break;
|
||||
|
||||
case ARDUINO_EVENT_WIFI_STA_CONNECTED:
|
||||
LOG_DEBUG(TAG, "WiFi STA Connected");
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void Networking::networkReconnectTaskFn(void* param) {
|
||||
Networking* net = static_cast<Networking*>(param);
|
||||
net->handleReconnection();
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
void Networking::reconnectionTimerCallback(TimerHandle_t xTimer) {
|
||||
if (_instance) {
|
||||
xTaskCreate(networkReconnectTaskFn, "netRecon", 3072, _instance, 5, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
void Networking::startPermanentAPMode() {
|
||||
LOG_INFO(TAG, "Starting Permanent AP Mode");
|
||||
setState(NetworkState::AP_MODE_PERMANENT);
|
||||
|
||||
// Stop any existing connections
|
||||
WiFi.disconnect(true);
|
||||
WiFi.mode(WIFI_OFF);
|
||||
delay(100);
|
||||
|
||||
// Configure AP mode with fixed 192.168.4.1 IP
|
||||
WiFi.mode(WIFI_AP);
|
||||
|
||||
auto& netConfig = _configManager.getNetworkConfig();
|
||||
String apName = netConfig.apSsid;
|
||||
String apPass = netConfig.apPass;
|
||||
|
||||
// Configure AP with fixed IP: 192.168.4.1
|
||||
IPAddress local_IP(192, 168, 4, 1);
|
||||
IPAddress gateway(192, 168, 4, 1);
|
||||
IPAddress subnet(255, 255, 255, 0);
|
||||
|
||||
if (!WiFi.softAPConfig(local_IP, gateway, subnet)) {
|
||||
LOG_ERROR(TAG, "Failed to configure AP IP address");
|
||||
}
|
||||
|
||||
// Start AP
|
||||
bool apStarted;
|
||||
if (apPass.isEmpty()) {
|
||||
apStarted = WiFi.softAP(apName.c_str());
|
||||
LOG_INFO(TAG, "Starting open AP (no password): %s", apName.c_str());
|
||||
} else {
|
||||
apStarted = WiFi.softAP(apName.c_str(), apPass.c_str());
|
||||
LOG_INFO(TAG, "Starting AP with password: %s", apName.c_str());
|
||||
}
|
||||
|
||||
if (apStarted) {
|
||||
LOG_INFO(TAG, "✅ Permanent AP Mode active");
|
||||
LOG_INFO(TAG, " SSID: %s", apName.c_str());
|
||||
LOG_INFO(TAG, " IP: 192.168.4.1");
|
||||
LOG_INFO(TAG, " Subnet: 255.255.255.0");
|
||||
|
||||
setActiveConnection(ConnectionType::AP);
|
||||
|
||||
// Stop reconnection timer (not needed in permanent AP mode)
|
||||
if (_reconnectionTimer) {
|
||||
xTimerStop(_reconnectionTimer, 0);
|
||||
}
|
||||
|
||||
// Mark boot sequence as complete
|
||||
_bootSequenceComplete = true;
|
||||
|
||||
// Notify connected
|
||||
notifyConnectionChange(true);
|
||||
} else {
|
||||
LOG_ERROR(TAG, "❌ Failed to start AP Mode");
|
||||
setState(NetworkState::DISCONNECTED);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* NETWORKING.HPP - Intelligent Network Connection Manager
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 🌐 THE NETWORK BRAIN OF VESPER 🌐
|
||||
*
|
||||
* This class provides intelligent network connectivity management with
|
||||
* automatic failover between Ethernet and WiFi. It handles all aspects
|
||||
* of network connectivity, configuration, and state management.
|
||||
*
|
||||
* 🏗️ INTELLIGENT CONNECTIVITY:
|
||||
* • Dual-stack support: Ethernet (primary) + WiFi (fallback)
|
||||
* • Automatic failover and recovery
|
||||
* • Smart connection prioritization
|
||||
* • State machine-based connection management
|
||||
* • Comprehensive event handling
|
||||
*
|
||||
* 🔄 AUTO-RECOVERY FEATURES:
|
||||
* • Automatic reconnection on connection loss
|
||||
* • Exponential backoff for failed attempts
|
||||
* • Cable detection for Ethernet
|
||||
* • WiFi portal fallback for configuration
|
||||
* • Boot timeout handling
|
||||
*
|
||||
* ⚙️ CONFIGURATION MANAGEMENT:
|
||||
* • Static IP configuration support
|
||||
* • Dynamic IP with DHCP fallback
|
||||
* • DNS configuration
|
||||
* • Hostname management
|
||||
* • WiFi credential management
|
||||
*
|
||||
* 📊 STATE MONITORING:
|
||||
* • Real-time connection status tracking
|
||||
* • Connection type identification
|
||||
* • Network quality monitoring
|
||||
* • Event-driven status updates
|
||||
* • Comprehensive logging
|
||||
*
|
||||
* 🔗 INTEGRATION:
|
||||
* • Clean callback interface for status changes
|
||||
* • ConfigManager integration for settings
|
||||
* • WiFiManager integration for portal mode
|
||||
* • Event-driven architecture
|
||||
*
|
||||
* 📋 VERSION: 2.0 (Intelligent dual-stack networking)
|
||||
* 📅 DATE: 2025
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <WiFi.h>
|
||||
#include <ETH.h>
|
||||
#include <functional>
|
||||
|
||||
class ConfigManager;
|
||||
class WiFiManager; // Forward declaration
|
||||
|
||||
enum class NetworkState {
|
||||
DISCONNECTED,
|
||||
CONNECTING_ETHERNET,
|
||||
CONNECTING_WIFI,
|
||||
WIFI_PORTAL_MODE,
|
||||
CONNECTED_ETHERNET,
|
||||
CONNECTED_WIFI,
|
||||
RECONNECTING,
|
||||
AP_MODE_PERMANENT
|
||||
};
|
||||
|
||||
enum class ConnectionType {
|
||||
NONE,
|
||||
ETHERNET,
|
||||
WIFI,
|
||||
AP
|
||||
};
|
||||
|
||||
class Networking {
|
||||
public:
|
||||
explicit Networking(ConfigManager& configManager);
|
||||
~Networking(); // Destructor to clean up WiFiManager
|
||||
|
||||
void begin();
|
||||
|
||||
// Returns whether the network is currently connected
|
||||
bool isConnected() const;
|
||||
String getLocalIP() const;
|
||||
String getGateway() const;
|
||||
ConnectionType getActiveConnection() const { return _activeConnection; }
|
||||
NetworkState getState() const { return _state; }
|
||||
|
||||
// Network event callbacks
|
||||
void setNetworkCallbacks(std::function<void()> onConnected, std::function<void()> onDisconnected) {
|
||||
_onNetworkConnected = onConnected;
|
||||
_onNetworkDisconnected = onDisconnected;
|
||||
}
|
||||
|
||||
// Manual connection control (for testing/debugging)
|
||||
void forceReconnect();
|
||||
|
||||
// AP Mode control
|
||||
void startPermanentAPMode();
|
||||
bool isInAPMode() const { return _state == NetworkState::AP_MODE_PERMANENT; }
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// HEALTH CHECK METHOD
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/** @brief Check if Networking is in healthy state */
|
||||
bool isHealthy() const;
|
||||
|
||||
// Static instance for callbacks
|
||||
static Networking* _instance;
|
||||
|
||||
// Static event handler
|
||||
static void networkEventHandler(arduino_event_id_t event, arduino_event_info_t info);
|
||||
|
||||
private:
|
||||
// Dependencies
|
||||
ConfigManager& _configManager;
|
||||
WiFiManager* _wifiManager;
|
||||
|
||||
// State
|
||||
NetworkState _state;
|
||||
ConnectionType _activeConnection;
|
||||
unsigned long _lastConnectionAttempt;
|
||||
bool _bootSequenceComplete;
|
||||
bool _ethernetCableConnected;
|
||||
int _wifiConnectionFailures; // Track consecutive WiFi failures
|
||||
|
||||
// Callbacks
|
||||
std::function<void()> _onNetworkConnected;
|
||||
std::function<void()> _onNetworkDisconnected;
|
||||
|
||||
// Timers
|
||||
TimerHandle_t _reconnectionTimer;
|
||||
|
||||
// Connection methods
|
||||
void startEthernetConnection();
|
||||
void startWiFiConnection();
|
||||
void startWiFiPortal();
|
||||
void handleReconnection();
|
||||
|
||||
// State management
|
||||
void setState(NetworkState newState);
|
||||
void setActiveConnection(ConnectionType type);
|
||||
void notifyConnectionChange(bool connected);
|
||||
|
||||
// Event handlers
|
||||
void onEthernetConnected();
|
||||
void onEthernetDisconnected();
|
||||
void onWiFiConnected();
|
||||
void onWiFiDisconnected();
|
||||
void onEthernetCableChange(bool connected);
|
||||
|
||||
// Utility methods
|
||||
void applyNetworkConfig(bool ethernet = false);
|
||||
bool hasValidWiFiCredentials();
|
||||
|
||||
// Timer callback and its task function
|
||||
static void reconnectionTimerCallback(TimerHandle_t xTimer);
|
||||
static void networkReconnectTaskFn(void* param);
|
||||
|
||||
// Constants
|
||||
static const unsigned long RECONNECTION_INTERVAL = 5000; // 5 seconds
|
||||
static const int MAX_WIFI_FAILURES = 3; // Portal after 3 failures
|
||||
};
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,171 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* OTAMANAGER.HPP - Over-The-Air Update Management System
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 🔄 THE UPDATE ORCHESTRATOR OF VESPER 🔄
|
||||
*
|
||||
* This class manages over-the-air firmware updates with safe, reliable
|
||||
* update mechanisms, version checking, and comprehensive error handling.
|
||||
*
|
||||
* 📋 VERSION: 2.1 (Enhanced with scheduled checks and full validation)
|
||||
* 📅 DATE: 2025
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <HTTPClient.h>
|
||||
#include <Update.h>
|
||||
#include <WiFi.h>
|
||||
#include <SD.h>
|
||||
#include <mbedtls/md.h>
|
||||
#include <ArduinoJson.h>
|
||||
#include <functional>
|
||||
#include <time.h>
|
||||
#include "../FileManager/FileManager.hpp"
|
||||
#include "../Telemetry/Telemetry.hpp"
|
||||
#include "../TimeKeeper/TimeKeeper.hpp"
|
||||
|
||||
class ConfigManager; // Forward declaration
|
||||
class Player; // Forward declaration for idle check
|
||||
class Timekeeper; // Forward declaration for freeze mode
|
||||
class Telemetry; // Forward declaration for freeze mode
|
||||
|
||||
class OTAManager {
|
||||
public:
|
||||
enum class Status {
|
||||
IDLE,
|
||||
CHECKING_VERSION,
|
||||
DOWNLOADING,
|
||||
INSTALLING,
|
||||
SUCCESS,
|
||||
FAILED
|
||||
};
|
||||
|
||||
enum class ErrorCode {
|
||||
NONE,
|
||||
HTTP_ERROR,
|
||||
VERSION_CHECK_FAILED,
|
||||
DOWNLOAD_FAILED,
|
||||
INSUFFICIENT_SPACE,
|
||||
WRITE_FAILED,
|
||||
VERIFICATION_FAILED,
|
||||
CHECKSUM_MISMATCH,
|
||||
METADATA_PARSE_FAILED,
|
||||
SIZE_MISMATCH,
|
||||
VERSION_TOO_LOW,
|
||||
CHANNEL_MISMATCH,
|
||||
PLAYER_ACTIVE
|
||||
};
|
||||
|
||||
// Callback types
|
||||
using ProgressCallback = std::function<void(size_t current, size_t total)>;
|
||||
using StatusCallback = std::function<void(Status status, ErrorCode error)>;
|
||||
|
||||
explicit OTAManager(ConfigManager& configManager);
|
||||
~OTAManager();
|
||||
|
||||
void begin();
|
||||
void setFileManager(FileManager* fm);
|
||||
void setPlayer(Player* player); // Set player reference for idle check
|
||||
void setTimeKeeper(Timekeeper* tk); // Set timekeeper reference for freeze mode
|
||||
void setTelemetry(Telemetry* telemetry); // Set telemetry reference for freeze mode
|
||||
|
||||
void checkForUpdates();
|
||||
void checkForUpdates(const String& channel); // Check specific channel
|
||||
void checkForEmergencyUpdates(); // NEW: Scheduled emergency-only check
|
||||
|
||||
void update();
|
||||
void update(const String& channel); // Update from specific channel
|
||||
void checkFirmwareUpdateFromSD(); // Check SD for firmware update
|
||||
bool performManualUpdate(); // Manual update triggered by app
|
||||
bool performManualUpdate(const String& channel); // Manual update from specific channel
|
||||
bool performCustomUpdate(const String& firmwareUrl, const String& checksum = "", size_t fileSize = 0, uint16_t version = 0); // Custom firmware update
|
||||
|
||||
// Hardware identification
|
||||
String getHardwareVariant() const;
|
||||
void setHardwareVariant(const String& variant); // Deprecated: Use ConfigManager instead
|
||||
|
||||
// Status and info
|
||||
Status getStatus() const { return _status; }
|
||||
ErrorCode getLastError() const { return _lastError; }
|
||||
uint16_t getCurrentVersion() const;
|
||||
uint16_t getAvailableVersion() const { return _availableVersion; }
|
||||
bool isUpdateAvailable() const { return _updateAvailable; }
|
||||
|
||||
// Callbacks
|
||||
void setProgressCallback(ProgressCallback callback) { _progressCallback = callback; }
|
||||
void setStatusCallback(StatusCallback callback) { _statusCallback = callback; }
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// HEALTH CHECK METHOD
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/** @brief Check if OTAManager is in healthy state */
|
||||
bool isHealthy() const;
|
||||
|
||||
private:
|
||||
ConfigManager& _configManager;
|
||||
FileManager* _fileManager;
|
||||
Player* _player; // Player reference for idle check
|
||||
Timekeeper* _timeKeeper; // TimeKeeper reference for freeze mode
|
||||
Telemetry* _telemetry; // Telemetry reference for freeze mode
|
||||
Status _status;
|
||||
ErrorCode _lastError;
|
||||
uint16_t _availableVersion;
|
||||
uint16_t _minVersion; // NEW: Minimum required version
|
||||
size_t _expectedFileSize; // NEW: Expected firmware file size
|
||||
bool _updateAvailable;
|
||||
String _availableChecksum;
|
||||
String _updateChannel;
|
||||
bool _isMandatory;
|
||||
bool _isEmergency;
|
||||
|
||||
ProgressCallback _progressCallback;
|
||||
StatusCallback _statusCallback;
|
||||
|
||||
// NEW: Scheduled check timer
|
||||
TimerHandle_t _scheduledCheckTimer;
|
||||
static void scheduledCheckCallback(TimerHandle_t xTimer);
|
||||
|
||||
// Initial boot check timer (non-blocking delayed check)
|
||||
TimerHandle_t _initialCheckTimer;
|
||||
static void initialCheckCallback(TimerHandle_t xTimer);
|
||||
void performInitialCheck(); // Async initial check after boot
|
||||
|
||||
// Worker task for OTA operations (prevents stack overflow in timer callbacks)
|
||||
TaskHandle_t _otaWorkerTask;
|
||||
SemaphoreHandle_t _otaWorkSignal;
|
||||
static void otaWorkerTaskFunction(void* parameter);
|
||||
void otaWorkerLoop();
|
||||
|
||||
enum class OTAWorkType {
|
||||
NONE,
|
||||
INITIAL_CHECK,
|
||||
SCHEDULED_CHECK
|
||||
};
|
||||
OTAWorkType _pendingWork;
|
||||
|
||||
void setStatus(Status status, ErrorCode error = ErrorCode::NONE);
|
||||
void notifyProgress(size_t current, size_t total);
|
||||
bool checkVersion();
|
||||
bool checkVersion(const String& channel);
|
||||
bool checkChannelsMetadata();
|
||||
bool downloadAndInstall();
|
||||
bool downloadAndInstall(const String& channel);
|
||||
bool downloadDirectToFlash(const String& url, size_t expectedSize); // NEW: Direct to flash (bypasses SD)
|
||||
bool downloadToSD(const String& url, const String& expectedChecksum, size_t expectedSize); // OLD: Via SD card
|
||||
bool verifyChecksum(const String& filePath, const String& expectedChecksum);
|
||||
String calculateSHA256(const String& filePath);
|
||||
bool installFromSD(const String& filePath);
|
||||
String buildChannelUrl(const String& channel) const;
|
||||
String buildMetadataUrl(const String& channel) const;
|
||||
String buildFirmwareUrl(const String& channel) const;
|
||||
|
||||
// NEW: Helper methods
|
||||
bool isPlayerActive() const;
|
||||
bool checkAvailableSpace(size_t requiredBytes) const;
|
||||
};
|
||||
@@ -0,0 +1,627 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* OUTPUTMANAGER - FIXED VERSION - Complete Implementation
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#include "OutputManager.hpp"
|
||||
|
||||
#define TAG "OutputManager"
|
||||
#include "../ConfigManager/ConfigManager.hpp"
|
||||
#include "../Logging/Logging.hpp"
|
||||
#include <Adafruit_PCF8574.h>
|
||||
#include <Adafruit_PCF8575.h>
|
||||
|
||||
// ==================== BASE CLASS IMPLEMENTATION ====================
|
||||
|
||||
OutputManager::~OutputManager() {
|
||||
stopDurationTask();
|
||||
if (_durationTaskHandle != nullptr) {
|
||||
vTaskDelay(pdMS_TO_TICKS(10));
|
||||
}
|
||||
}
|
||||
|
||||
void OutputManager::startDurationTask() {
|
||||
if (_durationTaskHandle != nullptr) {
|
||||
return;
|
||||
}
|
||||
_activeOutputs.reserve(32); // Support up to 32 virtual outputs
|
||||
xTaskCreatePinnedToCore(durationTask, "OutputDuration", 4096, this, 5, &_durationTaskHandle, 1);
|
||||
LOG_INFO(TAG, "⚡ Output Duration Management Task Initialized");
|
||||
}
|
||||
|
||||
void OutputManager::stopDurationTask() {
|
||||
if (_durationTaskHandle != nullptr) {
|
||||
vTaskDelete(_durationTaskHandle);
|
||||
_durationTaskHandle = nullptr;
|
||||
portENTER_CRITICAL(&_outputMutex);
|
||||
_activeOutputs.clear();
|
||||
portEXIT_CRITICAL(&_outputMutex);
|
||||
LOG_INFO(TAG, "⚡ Output Duration Management Task Stopped");
|
||||
}
|
||||
}
|
||||
|
||||
void OutputManager::durationTask(void* parameter) {
|
||||
OutputManager* manager = static_cast<OutputManager*>(parameter);
|
||||
LOG_DEBUG(TAG, "⚡ Output duration management task running on Core %d", xPortGetCoreID());
|
||||
while (true) {
|
||||
manager->processExpiredOutputs();
|
||||
vTaskDelay(pdMS_TO_TICKS(1));
|
||||
}
|
||||
}
|
||||
|
||||
void OutputManager::processExpiredOutputs() {
|
||||
uint64_t now = getMicros();
|
||||
portENTER_CRITICAL(&_outputMutex);
|
||||
for (auto it = _activeOutputs.begin(); it != _activeOutputs.end(); ++it) {
|
||||
uint64_t duration_micros = it->durationMs * 1000;
|
||||
if ((now - it->activationTime) >= duration_micros) {
|
||||
uint8_t outputIndex = it->outputIndex;
|
||||
_activeOutputs.erase(it);
|
||||
portEXIT_CRITICAL(&_outputMutex);
|
||||
extinguishOutput(outputIndex);
|
||||
LOG_VERBOSE(TAG, "⚡ AUTO-EXTINGUISH Output:%d after %dms", outputIndex, duration_micros / 1000);
|
||||
return;
|
||||
}
|
||||
}
|
||||
portEXIT_CRITICAL(&_outputMutex);
|
||||
}
|
||||
|
||||
uint8_t OutputManager::getPhysicalOutput(uint8_t virtualOutput) const {
|
||||
if (!_configManager) {
|
||||
LOG_WARNING(TAG, "⚠️ ConfigManager not available, using direct mapping for virtual output %d", virtualOutput);
|
||||
return virtualOutput;
|
||||
}
|
||||
if (!isValidVirtualOutput(virtualOutput)) {
|
||||
LOG_ERROR(TAG, "❌ Invalid virtual output %d, using direct mapping", virtualOutput);
|
||||
return virtualOutput;
|
||||
}
|
||||
|
||||
// Get 0-indexed bell output from config
|
||||
uint16_t bellOutput = _configManager->getBellOutput(virtualOutput);
|
||||
|
||||
// Handle unconfigured bells (255 = disabled)
|
||||
if (bellOutput == 255) {
|
||||
LOG_WARNING(TAG, "⚠️ Bell %d not configured (255)", virtualOutput);
|
||||
return 255; // Return invalid to prevent firing
|
||||
}
|
||||
|
||||
// Physical output is already 0-indexed from config
|
||||
uint8_t physicalOutput = (uint8_t)bellOutput;
|
||||
|
||||
LOG_DEBUG(TAG, "🔗 Bell %d → 0-indexed output %d",
|
||||
virtualOutput, physicalOutput);
|
||||
|
||||
return physicalOutput;
|
||||
}
|
||||
|
||||
bool OutputManager::isValidVirtualOutput(uint8_t virtualOutput) const {
|
||||
return virtualOutput < getMaxOutputs();
|
||||
}
|
||||
|
||||
bool OutputManager::isValidPhysicalOutput(uint8_t physicalOutput) const {
|
||||
if (physicalOutput == 255) { return false; }
|
||||
return physicalOutput < getMaxOutputs();
|
||||
}
|
||||
|
||||
void OutputManager::fireClockOutput(uint8_t virtualOutput, uint16_t durationMs) {
|
||||
if (!_initialized) {
|
||||
LOG_ERROR(TAG, "❌ OutputManager not initialized for clock output!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_configManager) {
|
||||
LOG_ERROR(TAG, "❌ ConfigManager not available for clock output mapping!");
|
||||
return;
|
||||
}
|
||||
|
||||
// Map virtual clock output to physical output using clock configuration
|
||||
uint8_t physicalOutput;
|
||||
if (virtualOutput == 0) {
|
||||
// Virtual clock output 0 = C1
|
||||
physicalOutput = _configManager->getClockOutput1();
|
||||
if (physicalOutput == 255) {
|
||||
LOG_WARNING(TAG, "⚠️ Clock C1 not configured (255)");
|
||||
return;
|
||||
}
|
||||
} else if (virtualOutput == 1) {
|
||||
// Virtual clock output 1 = C2
|
||||
physicalOutput = _configManager->getClockOutput2();
|
||||
if (physicalOutput == 255) {
|
||||
LOG_WARNING(TAG, "⚠️ Clock C2 not configured (255)");
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
LOG_ERROR(TAG, "❌ Invalid virtual clock output: %d (only 0=C1, 1=C2 supported)", virtualOutput);
|
||||
return;
|
||||
}
|
||||
|
||||
// Physical output is already 0-indexed from config
|
||||
if (!isValidPhysicalOutput(physicalOutput)) {
|
||||
LOG_ERROR(TAG, "❌ Invalid physical output for clock: %d (max outputs: %d)",
|
||||
physicalOutput, getMaxOutputs());
|
||||
return;
|
||||
}
|
||||
|
||||
// Fire the physical output directly
|
||||
fireOutputForDuration(physicalOutput, durationMs);
|
||||
|
||||
LOG_DEBUG(TAG, "🕐 FIRE Clock Virtual %d (C%d) → 0-indexed output %d for %dms",
|
||||
virtualOutput, virtualOutput + 1, physicalOutput, durationMs);
|
||||
}
|
||||
|
||||
// ==================== PCF8574/PCF8575 MULTI-CHIP IMPLEMENTATION ====================
|
||||
|
||||
// Single chip constructor
|
||||
PCF8574OutputManager::PCF8574OutputManager(uint8_t i2cAddress, ChipType chipType, uint8_t activeOutputs)
|
||||
: _chipCount(1), _totalOutputs(0), _allChipsInitialized(false) {
|
||||
_chips[0] = ChipConfig(i2cAddress, chipType, activeOutputs);
|
||||
updateTotalOutputs();
|
||||
}
|
||||
|
||||
// Dual chip constructor
|
||||
PCF8574OutputManager::PCF8574OutputManager(uint8_t addr1, ChipType chip1, uint8_t active1, uint8_t addr2, ChipType chip2, uint8_t active2)
|
||||
: _chipCount(2), _totalOutputs(0), _allChipsInitialized(false) {
|
||||
_chips[0] = ChipConfig(addr1, chip1, active1);
|
||||
_chips[1] = ChipConfig(addr2, chip2, active2);
|
||||
updateTotalOutputs();
|
||||
}
|
||||
|
||||
PCF8574OutputManager::~PCF8574OutputManager() {
|
||||
if (_allChipsInitialized) {
|
||||
emergencyShutdown();
|
||||
}
|
||||
for (uint8_t i = 0; i < _chipCount; i++) {
|
||||
shutdownChip(i);
|
||||
}
|
||||
}
|
||||
|
||||
bool PCF8574OutputManager::initialize() {
|
||||
LOG_INFO(TAG, "🔌 Initializing Multi-Chip PCF857x Output Manager (%d chips)", _chipCount);
|
||||
delay(100);
|
||||
|
||||
bool allSuccess = true;
|
||||
for (uint8_t i = 0; i < _chipCount; i++) {
|
||||
if (!initializeChip(i)) {
|
||||
LOG_ERROR(TAG, "❌ Failed to initialize chip %d!", i);
|
||||
allSuccess = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!allSuccess) {
|
||||
LOG_ERROR(TAG, "❌ Not all chips initialized successfully!");
|
||||
return false;
|
||||
}
|
||||
|
||||
emergencyShutdown();
|
||||
startDurationTask();
|
||||
_allChipsInitialized = true;
|
||||
_initialized = true; // Set base class flag too!
|
||||
|
||||
LOG_INFO(TAG, "✅ Multi-Chip PCF857x Output Manager Initialized (%d total outputs)", _totalOutputs);
|
||||
generateHardwareTypeString();
|
||||
|
||||
if (_configManager) {
|
||||
LOG_INFO(TAG, "📋 Virtual Output Configuration Mappings:");
|
||||
for (uint8_t i = 0; i < min(16, (int)_totalOutputs); i++) { // Check virtual outputs
|
||||
uint16_t configOutput = _configManager->getBellOutput(i);
|
||||
if (configOutput < _totalOutputs) {
|
||||
VirtualOutputInfo info = getVirtualOutputInfo(configOutput);
|
||||
LOG_DEBUG(TAG, " Bell %d → Virtual Output %d → %s[%d] Pin %d", i, configOutput, info.chipType, info.chipIndex, info.localPin);
|
||||
} else if (configOutput == 255) {
|
||||
LOG_DEBUG(TAG, " Bell %d → Not configured (255)", i);
|
||||
} else {
|
||||
LOG_WARNING(TAG, "⚠️ Bell %d mapped to invalid virtual output %d (max: %d)", i, configOutput, _totalOutputs - 1);
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t c1 = _configManager->getClockOutput1();
|
||||
uint8_t c2 = _configManager->getClockOutput2();
|
||||
LOG_INFO(TAG, "🕐 Clock Virtual Output Mappings:");
|
||||
|
||||
if (c1 != 255 && c1 < _totalOutputs) {
|
||||
VirtualOutputInfo info = getVirtualOutputInfo(c1);
|
||||
LOG_DEBUG(TAG, " Clock C1 → Virtual Output %d → %s[%d] Pin %d", c1, info.chipType, info.chipIndex, info.localPin);
|
||||
} else {
|
||||
LOG_DEBUG(TAG, " Clock C1 → Not configured");
|
||||
}
|
||||
|
||||
if (c2 != 255 && c2 < _totalOutputs) {
|
||||
VirtualOutputInfo info = getVirtualOutputInfo(c2);
|
||||
LOG_DEBUG(TAG, " Clock C2 → Virtual Output %d → %s[%d] Pin %d", c2, info.chipType, info.chipIndex, info.localPin);
|
||||
} else {
|
||||
LOG_DEBUG(TAG, " Clock C2 → Not configured");
|
||||
}
|
||||
|
||||
// Show virtual output mapping
|
||||
LOG_INFO(TAG, "🔗 Virtual Output Mapping:");
|
||||
for (uint8_t i = 0; i < _totalOutputs; i++) {
|
||||
VirtualOutputInfo info = getVirtualOutputInfo(i);
|
||||
LOG_DEBUG(TAG, " Virtual Output %d → %s[%d] Pin %d", i, info.chipType, info.chipIndex, info.localPin);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void PCF8574OutputManager::fireOutput(uint8_t outputIndex) {
|
||||
if (!_allChipsInitialized) {
|
||||
LOG_ERROR(TAG, "❌ PCF857x chips not initialized!");
|
||||
return;
|
||||
}
|
||||
if (!isValidVirtualOutput(outputIndex)) {
|
||||
LOG_ERROR(TAG, "❌ Invalid virtual output: %d (max: %d)", outputIndex, _totalOutputs - 1);
|
||||
return;
|
||||
}
|
||||
|
||||
VirtualOutputInfo info = getVirtualOutputInfo(outputIndex);
|
||||
writeOutputToChip(info.chipIndex, info.localPin, false);
|
||||
|
||||
LOG_DEBUG(TAG, "🔥 FIRE Virtual Output %d → %s[%d] Pin %d", outputIndex, info.chipType, info.chipIndex, info.localPin);
|
||||
}
|
||||
|
||||
void PCF8574OutputManager::extinguishOutput(uint8_t outputIndex) {
|
||||
if (!_allChipsInitialized) return;
|
||||
if (!isValidVirtualOutput(outputIndex)) return;
|
||||
|
||||
VirtualOutputInfo info = getVirtualOutputInfo(outputIndex);
|
||||
writeOutputToChip(info.chipIndex, info.localPin, true);
|
||||
|
||||
LOG_DEBUG(TAG, "💧 EXTINGUISH Virtual Output %d → %s[%d] Pin %d", outputIndex, info.chipType, info.chipIndex, info.localPin);
|
||||
}
|
||||
|
||||
void PCF8574OutputManager::fireOutputForDuration(uint8_t outputIndex, uint16_t durationMs) {
|
||||
if (!_allChipsInitialized || !isValidVirtualOutput(outputIndex)) return;
|
||||
fireOutput(outputIndex);
|
||||
uint64_t now = getMicros();
|
||||
portENTER_CRITICAL(&_outputMutex);
|
||||
_activeOutputs.push_back({outputIndex, now, durationMs});
|
||||
portEXIT_CRITICAL(&_outputMutex);
|
||||
}
|
||||
|
||||
void PCF8574OutputManager::firePhysicalOutput(uint8_t physicalOutput, bool state) {
|
||||
if (!_allChipsInitialized || !isValidPhysicalOutput(physicalOutput)) return;
|
||||
OutputMapping mapping = getOutputMapping(physicalOutput);
|
||||
writeOutputToChip(mapping.chipIndex, mapping.localPin, !state); // Invert because we're using active LOW
|
||||
}
|
||||
|
||||
void PCF8574OutputManager::fireOutputsBatch(const std::vector<uint8_t>& outputIndices) {
|
||||
if (!_allChipsInitialized) return;
|
||||
for (uint8_t outputIndex : outputIndices) {
|
||||
if (!isValidVirtualOutput(outputIndex)) continue;
|
||||
VirtualOutputInfo info = getVirtualOutputInfo(outputIndex);
|
||||
writeOutputToChip(info.chipIndex, info.localPin, false);
|
||||
}
|
||||
}
|
||||
|
||||
void PCF8574OutputManager::extinguishOutputsBatch(const std::vector<uint8_t>& outputIndices) {
|
||||
if (!_allChipsInitialized) return;
|
||||
for (uint8_t outputIndex : outputIndices) {
|
||||
if (!isValidVirtualOutput(outputIndex)) continue;
|
||||
VirtualOutputInfo info = getVirtualOutputInfo(outputIndex);
|
||||
writeOutputToChip(info.chipIndex, info.localPin, true);
|
||||
}
|
||||
}
|
||||
|
||||
void PCF8574OutputManager::fireOutputsBatchForDuration(const std::vector<std::pair<uint8_t, uint16_t>>& outputDurations) {
|
||||
if (!_allChipsInitialized) return;
|
||||
uint64_t now = getMicros();
|
||||
std::vector<uint8_t> outputsToFire;
|
||||
portENTER_CRITICAL(&_outputMutex);
|
||||
for (const auto& [outputIndex, durationMs] : outputDurations) {
|
||||
if (isValidVirtualOutput(outputIndex)) {
|
||||
outputsToFire.push_back(outputIndex);
|
||||
_activeOutputs.push_back({outputIndex, now, durationMs});
|
||||
}
|
||||
}
|
||||
portEXIT_CRITICAL(&_outputMutex);
|
||||
fireOutputsBatch(outputsToFire);
|
||||
}
|
||||
|
||||
void PCF8574OutputManager::emergencyShutdown() {
|
||||
LOG_WARNING(TAG, "🚨 PCF857x EMERGENCY SHUTDOWN - All outputs HIGH");
|
||||
portENTER_CRITICAL(&_outputMutex);
|
||||
_activeOutputs.clear();
|
||||
portEXIT_CRITICAL(&_outputMutex);
|
||||
|
||||
for (uint8_t chipIndex = 0; chipIndex < _chipCount; chipIndex++) {
|
||||
if (_chips[chipIndex].initialized) {
|
||||
for (uint8_t pin = 0; pin < _chips[chipIndex].activeOutputs; pin++) {
|
||||
writeOutputToChip(chipIndex, pin, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const char* PCF8574OutputManager::getHardwareType() const {
|
||||
generateHardwareTypeString();
|
||||
return _hardwareTypeBuffer;
|
||||
}
|
||||
|
||||
ChipConfig PCF8574OutputManager::getChipConfig(uint8_t chipIndex) const {
|
||||
if (chipIndex < _chipCount) {
|
||||
return _chips[chipIndex];
|
||||
}
|
||||
return ChipConfig(); // Return default config if invalid index
|
||||
}
|
||||
|
||||
bool PCF8574OutputManager::addChip(uint8_t i2cAddress, ChipType chipType, uint8_t activeOutputs) {
|
||||
if (_chipCount >= MAX_CHIPS) {
|
||||
LOG_ERROR(TAG, "❌ Cannot add more chips - maximum %d chips supported", MAX_CHIPS);
|
||||
return false;
|
||||
}
|
||||
|
||||
_chips[_chipCount] = ChipConfig(i2cAddress, chipType, activeOutputs);
|
||||
_chipCount++;
|
||||
updateTotalOutputs();
|
||||
|
||||
LOG_INFO(TAG, "✅ Added chip %d: %s at 0x%02X (%d/%d active outputs)",
|
||||
_chipCount - 1,
|
||||
(chipType == ChipType::PCF8574) ? "PCF8574" : "PCF8575",
|
||||
i2cAddress,
|
||||
_chips[_chipCount - 1].activeOutputs,
|
||||
_chips[_chipCount - 1].maxOutputs);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
PCF8574OutputManager::VirtualOutputInfo PCF8574OutputManager::getVirtualOutputInfo(uint8_t virtualOutput) const {
|
||||
VirtualOutputInfo info;
|
||||
|
||||
if (virtualOutput >= _totalOutputs) {
|
||||
// Invalid - return chip 0, pin 0 as fallback
|
||||
info.chipIndex = 0;
|
||||
info.localPin = 0;
|
||||
info.chipType = (_chipCount > 0 && _chips[0].chipType == ChipType::PCF8574) ? "PCF8574" : "PCF8575";
|
||||
LOG_ERROR(TAG, "❌ Invalid virtual output %d (max: %d)", virtualOutput, _totalOutputs - 1);
|
||||
return info;
|
||||
}
|
||||
|
||||
// Map virtual output to physical chip and pin
|
||||
if (virtualOutput < _chips[0].activeOutputs) {
|
||||
// Output is on first chip
|
||||
info.chipIndex = 0;
|
||||
info.localPin = virtualOutput;
|
||||
info.chipType = (_chips[0].chipType == ChipType::PCF8574) ? "PCF8574" : "PCF8575";
|
||||
} else if (_chipCount > 1) {
|
||||
// Output is on second chip
|
||||
info.chipIndex = 1;
|
||||
info.localPin = virtualOutput - _chips[0].activeOutputs;
|
||||
info.chipType = (_chips[1].chipType == ChipType::PCF8574) ? "PCF8574" : "PCF8575";
|
||||
} else {
|
||||
// Should not happen, but fallback to chip 0
|
||||
info.chipIndex = 0;
|
||||
info.localPin = 0;
|
||||
info.chipType = (_chips[0].chipType == ChipType::PCF8574) ? "PCF8574" : "PCF8575";
|
||||
LOG_ERROR(TAG, "❌ Virtual output %d exceeds available outputs on single chip", virtualOutput);
|
||||
}
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
void PCF8574OutputManager::setChipActiveOutputs(uint8_t chipIndex, uint8_t activeOutputs) {
|
||||
if (chipIndex >= _chipCount) {
|
||||
LOG_ERROR(TAG, "❌ Invalid chip index %d (max: %d)", chipIndex, _chipCount - 1);
|
||||
return;
|
||||
}
|
||||
|
||||
uint8_t maxOutputs = _chips[chipIndex].maxOutputs;
|
||||
_chips[chipIndex].activeOutputs = min(activeOutputs, maxOutputs);
|
||||
updateTotalOutputs();
|
||||
|
||||
LOG_INFO(TAG, "✅ Updated chip %d active outputs: %d/%d", chipIndex, _chips[chipIndex].activeOutputs, maxOutputs);
|
||||
}
|
||||
|
||||
uint8_t PCF8574OutputManager::getChipActiveOutputs(uint8_t chipIndex) const {
|
||||
if (chipIndex >= _chipCount) {
|
||||
LOG_ERROR(TAG, "❌ Invalid chip index %d (max: %d)", chipIndex, _chipCount - 1);
|
||||
return 0;
|
||||
}
|
||||
return _chips[chipIndex].activeOutputs;
|
||||
}
|
||||
|
||||
// Private helper methods
|
||||
bool PCF8574OutputManager::initializeChip(uint8_t chipIndex) {
|
||||
if (chipIndex >= _chipCount) return false;
|
||||
|
||||
ChipConfig& chip = _chips[chipIndex];
|
||||
const char* chipTypeStr = (chip.chipType == ChipType::PCF8574) ? "PCF8574" : "PCF8575";
|
||||
|
||||
LOG_DEBUG(TAG, "🔌 Initializing %s at address 0x%02X", chipTypeStr, chip.i2cAddress);
|
||||
|
||||
try {
|
||||
if (chip.chipType == ChipType::PCF8574) {
|
||||
// Use static instance to avoid memory allocation issues
|
||||
static Adafruit_PCF8574 pcf8574Instances[MAX_CHIPS];
|
||||
chip.chipInstance = &pcf8574Instances[chipIndex];
|
||||
Adafruit_PCF8574* pcf = static_cast<Adafruit_PCF8574*>(chip.chipInstance);
|
||||
|
||||
if (!pcf->begin(chip.i2cAddress, &Wire)) {
|
||||
LOG_ERROR(TAG, "❌ Failed to initialize PCF8574 at address 0x%02X", chip.i2cAddress);
|
||||
chip.chipInstance = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Configure all pins as outputs and set them HIGH (inactive)
|
||||
for (uint8_t pin = 0; pin < 8; pin++) {
|
||||
pcf->pinMode(pin, OUTPUT);
|
||||
pcf->digitalWrite(pin, HIGH);
|
||||
}
|
||||
} else { // PCF8575
|
||||
// Use static instance to avoid memory allocation issues
|
||||
static Adafruit_PCF8575 pcf8575Instances[MAX_CHIPS];
|
||||
chip.chipInstance = &pcf8575Instances[chipIndex];
|
||||
Adafruit_PCF8575* pcf = static_cast<Adafruit_PCF8575*>(chip.chipInstance);
|
||||
|
||||
if (!pcf->begin(chip.i2cAddress, &Wire)) {
|
||||
LOG_ERROR(TAG, "❌ Failed to initialize PCF8575 at address 0x%02X", chip.i2cAddress);
|
||||
chip.chipInstance = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Configure all pins as outputs and set them HIGH (inactive)
|
||||
for (uint8_t pin = 0; pin < 16; pin++) {
|
||||
pcf->pinMode(pin, OUTPUT);
|
||||
pcf->digitalWrite(pin, HIGH);
|
||||
}
|
||||
}
|
||||
|
||||
chip.initialized = true;
|
||||
LOG_DEBUG(TAG, "✅ %s at 0x%02X initialized successfully", chipTypeStr, chip.i2cAddress);
|
||||
return true;
|
||||
|
||||
} catch (...) {
|
||||
LOG_ERROR(TAG, "❌ Exception during %s initialization at 0x%02X", chipTypeStr, chip.i2cAddress);
|
||||
chip.chipInstance = nullptr;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void PCF8574OutputManager::shutdownChip(uint8_t chipIndex) {
|
||||
if (chipIndex >= _chipCount) return;
|
||||
|
||||
ChipConfig& chip = _chips[chipIndex];
|
||||
if (chip.initialized && chip.chipInstance) {
|
||||
// Set all outputs to HIGH (inactive) before shutdown
|
||||
for (uint8_t pin = 0; pin < chip.activeOutputs; pin++) {
|
||||
writeOutputToChip(chipIndex, pin, true);
|
||||
}
|
||||
chip.initialized = false;
|
||||
chip.chipInstance = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
PCF8574OutputManager::OutputMapping PCF8574OutputManager::getOutputMapping(uint8_t physicalOutput) const {
|
||||
OutputMapping mapping;
|
||||
|
||||
if (physicalOutput < _chips[0].activeOutputs) {
|
||||
// Output is on first chip
|
||||
mapping.chipIndex = 0;
|
||||
mapping.localPin = physicalOutput;
|
||||
} else if (_chipCount > 1 && physicalOutput < _totalOutputs) {
|
||||
// Output is on second chip
|
||||
mapping.chipIndex = 1;
|
||||
mapping.localPin = physicalOutput - _chips[0].activeOutputs;
|
||||
} else {
|
||||
// Invalid output - return chip 0, pin 0 as safe fallback
|
||||
mapping.chipIndex = 0;
|
||||
mapping.localPin = 0;
|
||||
LOG_ERROR(TAG, "❌ Invalid physical output %d mapped to fallback", physicalOutput);
|
||||
}
|
||||
|
||||
return mapping;
|
||||
}
|
||||
|
||||
void PCF8574OutputManager::writeOutputToChip(uint8_t chipIndex, uint8_t pin, bool state) {
|
||||
if (chipIndex >= _chipCount || !_chips[chipIndex].initialized) return;
|
||||
if (!isValidOutputForChip(chipIndex, pin)) return;
|
||||
|
||||
ChipConfig& chip = _chips[chipIndex];
|
||||
|
||||
if (chip.chipType == ChipType::PCF8574) {
|
||||
Adafruit_PCF8574* pcf = static_cast<Adafruit_PCF8574*>(chip.chipInstance);
|
||||
pcf->digitalWrite(pin, state ? HIGH : LOW);
|
||||
} else { // PCF8575
|
||||
Adafruit_PCF8575* pcf = static_cast<Adafruit_PCF8575*>(chip.chipInstance);
|
||||
pcf->digitalWrite(pin, state ? HIGH : LOW);
|
||||
}
|
||||
}
|
||||
|
||||
bool PCF8574OutputManager::isValidOutputForChip(uint8_t chipIndex, uint8_t pin) const {
|
||||
if (chipIndex >= _chipCount) return false;
|
||||
return pin < _chips[chipIndex].activeOutputs;
|
||||
}
|
||||
|
||||
void PCF8574OutputManager::updateTotalOutputs() {
|
||||
_totalOutputs = 0;
|
||||
for (uint8_t i = 0; i < _chipCount; i++) {
|
||||
_totalOutputs += _chips[i].activeOutputs;
|
||||
}
|
||||
}
|
||||
|
||||
void PCF8574OutputManager::generateHardwareTypeString() const {
|
||||
if (_chipCount == 1) {
|
||||
const char* chipType = (_chips[0].chipType == ChipType::PCF8574) ? "PCF8574" : "PCF8575";
|
||||
snprintf(_hardwareTypeBuffer, sizeof(_hardwareTypeBuffer), "%s I2C Expander (%d/%d outputs)",
|
||||
chipType, _chips[0].activeOutputs, _chips[0].maxOutputs);
|
||||
} else {
|
||||
const char* chip1Type = (_chips[0].chipType == ChipType::PCF8574) ? "PCF8574" : "PCF8575";
|
||||
const char* chip2Type = (_chips[1].chipType == ChipType::PCF8574) ? "PCF8574" : "PCF8575";
|
||||
snprintf(_hardwareTypeBuffer, sizeof(_hardwareTypeBuffer), "%s+%s I2C Expanders (%d outputs total)",
|
||||
chip1Type, chip2Type, _totalOutputs);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== HEALTH CHECK IMPLEMENTATION ====================
|
||||
|
||||
bool OutputManager::isHealthy() const {
|
||||
// Basic health checks
|
||||
if (!_initialized) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if ConfigManager is available
|
||||
if (!_configManager) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if duration task is running when it should be
|
||||
if (_initialized && _durationTaskHandle == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if max outputs is reasonable
|
||||
if (getMaxOutputs() == 0 || getMaxOutputs() > 64) { // Sanity check
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool PCF8574OutputManager::isHealthy() const {
|
||||
// Call base class health check first
|
||||
if (!OutputManager::isHealthy()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check chip-specific health
|
||||
if (_chipCount == 0 || _chipCount > MAX_CHIPS) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!_allChipsInitialized) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check each chip's health
|
||||
for (uint8_t i = 0; i < _chipCount; i++) {
|
||||
const ChipConfig& chip = _chips[i];
|
||||
|
||||
// Check if chip is properly initialized
|
||||
if (!chip.initialized || chip.chipInstance == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if active outputs are within valid range
|
||||
if (chip.activeOutputs == 0 || chip.activeOutputs > chip.maxOutputs) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if I2C address is in valid range
|
||||
if (chip.i2cAddress < 0x20 || chip.i2cAddress > 0x27) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Check total outputs consistency
|
||||
uint8_t calculatedTotal = 0;
|
||||
for (uint8_t i = 0; i < _chipCount; i++) {
|
||||
calculatedTotal += _chips[i].activeOutputs;
|
||||
}
|
||||
|
||||
if (calculatedTotal != _totalOutputs) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* OUTPUTMANAGER.HPP - FIXED VERSION - Hardware Abstraction Layer for Relay Control
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* FIXES APPLIED:
|
||||
* - Better validation for physical outputs (handles 255 = unconfigured)
|
||||
* - Enhanced logging for debugging configuration issues
|
||||
* - Clear separation between bell outputs and clock outputs
|
||||
* - Improved error messages with context
|
||||
*
|
||||
* ⚡ THE HARDWARE ABSTRACTION POWERHOUSE ⚡
|
||||
*
|
||||
* This module provides a clean, unified interface for controlling different
|
||||
* types of relay/output hardware. It completely abstracts the hardware details
|
||||
* from the rest of the system, allowing easy swapping between different
|
||||
* relay control methods.
|
||||
*
|
||||
* 🏗️ CLEAN ARCHITECTURE:
|
||||
* • Abstract base class with polymorphic interface
|
||||
* • Multiple concrete implementations for different hardware
|
||||
* • Automatic duration management with microsecond precision
|
||||
* • Thread-safe operation with FreeRTOS integration
|
||||
* • Comprehensive error handling and safety features
|
||||
*
|
||||
* 🔧 SUPPORTED HARDWARE:
|
||||
* • PCF8574OutputManager: I2C GPIO expanders (PCF8574: 8 outputs, PCF8575: 16 outputs)
|
||||
* • Multi-chip support: Up to 2 chips for maximum flexibility
|
||||
*
|
||||
* ⏱️ PRECISION TIMING:
|
||||
* • Microsecond-accurate duration control
|
||||
* • Automatic relay timeout management
|
||||
* • Non-blocking operation with background task
|
||||
* • Configurable duration per bell/relay
|
||||
*
|
||||
* 🔒 SAFETY FEATURES:
|
||||
* • Emergency shutdown capability
|
||||
* • Bounds checking on all operations
|
||||
* • Hardware initialization validation
|
||||
* • Automatic cleanup on failure
|
||||
*
|
||||
* 📌 USAGE:
|
||||
* Choose the appropriate implementation in main.cpp:
|
||||
* - PCF8574OutputManager for I2C expander setups
|
||||
* - GPIOOutputManager for direct pin control
|
||||
* - MockOutputManager for testing and development
|
||||
*
|
||||
* 🔔 BELL vs CLOCK OUTPUTS:
|
||||
* - Bell outputs: Managed via ConfigManager->getBellOutput(bellIndex)
|
||||
* - Clock outputs: Managed via ConfigManager->getClockOutput1()/getClockOutput2()
|
||||
* - Both use the same OutputManager but for different purposes
|
||||
* - Bell indices: 0-15 (for 16 bells)
|
||||
* - Clock outputs: c1, c2 (for clock mechanism)
|
||||
*
|
||||
* 📋 VERSION: 2.1 (Fixed configuration validation)
|
||||
* 📅 DATE: 2025
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
// SYSTEM INCLUDES - Core libraries for hardware control
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
#include <Arduino.h> // Arduino core functionality
|
||||
#include <cstdint> // Fixed-width integer types
|
||||
#include <vector> // STL vector for active relay tracking
|
||||
#include "freertos/FreeRTOS.h" // FreeRTOS kernel
|
||||
#include "freertos/task.h" // FreeRTOS task management
|
||||
#include "esp_timer.h" // ESP32 high-precision timers
|
||||
#include "../Logging/Logging.hpp" // Centralized logging system
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
// FORWARD DECLARATIONS
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
class ConfigManager; // Configuration management system
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
// ACTIVE OUTPUT TRACKING STRUCTURE
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @struct ActiveOutput
|
||||
* @brief Tracks active outputs with microsecond precision timing
|
||||
*
|
||||
* This structure maintains the state of currently active outputs,
|
||||
* including their activation time and configured duration for
|
||||
* automatic timeout management.
|
||||
*/
|
||||
struct ActiveOutput {
|
||||
uint8_t outputIndex; // 🔌 Virtual output index (0-31)
|
||||
uint64_t activationTime; // ⏱️ Activation start time (microseconds)
|
||||
uint16_t durationMs; // ⏳ Duration in milliseconds
|
||||
};
|
||||
|
||||
/**
|
||||
* @class OutputManager
|
||||
* @brief Abstract base class for hardware output management
|
||||
*
|
||||
* Provides a clean abstraction layer for different relay/output systems.
|
||||
* This class defines the interface that all concrete implementations must
|
||||
* follow, ensuring consistent behavior across different hardware types.
|
||||
*
|
||||
* 🏗️ KEY DESIGN PRINCIPLES:
|
||||
* • Hardware-agnostic interface
|
||||
* • Automatic duration management
|
||||
* • Thread-safe operation
|
||||
* • Comprehensive error handling
|
||||
* • Emergency shutdown capability
|
||||
*
|
||||
* 🔌 SUPPORTED OPERATIONS:
|
||||
* • Immediate relay control (fire/extinguish)
|
||||
* • Timed relay activation with automatic shutoff
|
||||
* • Emergency shutdown of all outputs
|
||||
* • Hardware status monitoring
|
||||
*
|
||||
* ⏱️ TIMING FEATURES:
|
||||
* • Microsecond-precision activation timing
|
||||
* • Background task for duration management
|
||||
* • Non-blocking operation
|
||||
* • Configurable per-bell durations
|
||||
*/
|
||||
class OutputManager {
|
||||
public:
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// CONSTRUCTOR & DESTRUCTOR
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
OutputManager() = default;
|
||||
|
||||
/**
|
||||
* @brief Virtual destructor for proper cleanup
|
||||
*
|
||||
* Ensures derived classes can properly clean up their resources.
|
||||
*/
|
||||
virtual ~OutputManager();
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// PURE VIRTUAL INTERFACE - Must be implemented by derived classes
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/** @brief Initialize hardware - must be implemented */
|
||||
virtual bool initialize() = 0;
|
||||
|
||||
/** @brief Activate output immediately - hardware agnostic */
|
||||
virtual void fireOutput(uint8_t outputIndex) = 0;
|
||||
|
||||
/** @brief Deactivate output immediately - hardware agnostic */
|
||||
virtual void extinguishOutput(uint8_t outputIndex) = 0;
|
||||
|
||||
/** @brief Emergency shutdown all outputs - must be implemented */
|
||||
virtual void emergencyShutdown() = 0;
|
||||
|
||||
/** @brief Timed output activation - hardware agnostic */
|
||||
virtual void fireOutputForDuration(uint8_t outputIndex, uint16_t durationMs) = 0;
|
||||
|
||||
/** @brief Batch operations for simultaneous firing (CRITICAL for synchronization!) */
|
||||
virtual void fireOutputsBatch(const std::vector<uint8_t>& outputIndices) = 0;
|
||||
virtual void extinguishOutputsBatch(const std::vector<uint8_t>& outputIndices) = 0;
|
||||
virtual void fireOutputsBatchForDuration(const std::vector<std::pair<uint8_t, uint16_t>>& outputDurations) = 0;
|
||||
|
||||
|
||||
/** @brief Check if hardware is initialized - must be implemented */
|
||||
virtual bool isInitialized() const = 0;
|
||||
|
||||
/** @brief Get maximum number of outputs - must be implemented */
|
||||
virtual uint8_t getMaxOutputs() const = 0;
|
||||
|
||||
/** @brief Get hardware type description - must be implemented */
|
||||
virtual const char* getHardwareType() const = 0;
|
||||
|
||||
/** @brief Set configuration manager reference */
|
||||
virtual void setConfigManager(ConfigManager* config) { _configManager = config; }
|
||||
|
||||
/** @brief Get physical output mapping from virtual output (for validation) */
|
||||
uint8_t getPhysicalOutput(uint8_t virtualOutput) const;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// HEALTH CHECK METHOD
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/** @brief Check if OutputManager is in healthy state */
|
||||
virtual bool isHealthy() const;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// CLOCK-SPECIFIC OUTPUT METHODS - For TimeKeeper integration
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/** @brief Fire clock output directly by virtual output number (for TimeKeeper) */
|
||||
virtual void fireClockOutput(uint8_t virtualOutput, uint16_t durationMs);
|
||||
|
||||
/** @brief Get total virtual outputs available */
|
||||
virtual uint8_t getTotalVirtualOutputs() const { return getMaxOutputs(); }
|
||||
|
||||
protected:
|
||||
ConfigManager* _configManager = nullptr;
|
||||
bool _initialized = false;
|
||||
|
||||
// Active outputs tracking
|
||||
std::vector<ActiveOutput> _activeOutputs;
|
||||
portMUX_TYPE _outputMutex = portMUX_INITIALIZER_UNLOCKED;
|
||||
|
||||
// Duration management task
|
||||
TaskHandle_t _durationTaskHandle = nullptr;
|
||||
|
||||
// Bounds checking
|
||||
bool isValidVirtualOutput(uint8_t virtualOutput) const;
|
||||
bool isValidPhysicalOutput(uint8_t physicalOutput) const;
|
||||
|
||||
|
||||
// Duration management
|
||||
void startDurationTask();
|
||||
void stopDurationTask();
|
||||
void processExpiredOutputs();
|
||||
static void durationTask(void* parameter);
|
||||
|
||||
// Direct physical output access (for clock outputs)
|
||||
virtual void firePhysicalOutput(uint8_t physicalOutput, bool state) = 0;
|
||||
|
||||
// Timing utilities
|
||||
uint64_t getMicros() const { return esp_timer_get_time(); }
|
||||
};
|
||||
|
||||
/**
|
||||
* Chip Type Enumeration
|
||||
* Defines the supported I2C GPIO expander types
|
||||
*/
|
||||
enum class ChipType {
|
||||
PCF8574, // 8 outputs
|
||||
PCF8575 // 16 outputs
|
||||
};
|
||||
|
||||
/**
|
||||
* Chip Configuration Structure
|
||||
* Holds configuration for each I2C GPIO expander chip
|
||||
*/
|
||||
struct ChipConfig {
|
||||
uint8_t i2cAddress; // I2C address (0x20-0x27 for PCF8574, 0x20-0x27 for PCF8575)
|
||||
ChipType chipType; // Type of chip (PCF8574 or PCF8575)
|
||||
uint8_t maxOutputs; // Maximum outputs chip supports (8 for PCF8574, 16 for PCF8575)
|
||||
uint8_t activeOutputs; // Number of active outputs (user-configurable, <= maxOutputs)
|
||||
void* chipInstance; // Pointer to chip instance
|
||||
bool initialized; // Initialization status
|
||||
|
||||
ChipConfig() : i2cAddress(0x20), chipType(ChipType::PCF8574), maxOutputs(8), activeOutputs(8), chipInstance(nullptr), initialized(false) {}
|
||||
|
||||
ChipConfig(uint8_t addr, ChipType type, uint8_t activeOuts = 0) : i2cAddress(addr), chipType(type), chipInstance(nullptr), initialized(false) {
|
||||
maxOutputs = (type == ChipType::PCF8574) ? 8 : 16;
|
||||
activeOutputs = (activeOuts == 0) ? maxOutputs : min(activeOuts, maxOutputs);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* PCF8574/PCF8575 I2C GPIO Expander Implementation
|
||||
* Supports single or dual chip configurations with configurable active outputs:
|
||||
* - Single PCF8574: 1-8 active outputs
|
||||
* - Single PCF8575: 1-16 active outputs
|
||||
* - PCF8574 + PCF8575: (1-8) + (1-16) active outputs
|
||||
* - Dual PCF8575: (1-16) + (1-16) active outputs
|
||||
*
|
||||
* Virtual Output Mapping:
|
||||
* - Virtual outputs 0 to (chip1_active-1) → Chip 1, pins 0 to (chip1_active-1)
|
||||
* - Virtual outputs chip1_active to (total_active-1) → Chip 2, pins 0 to (chip2_active-1)
|
||||
*/
|
||||
class PCF8574OutputManager : public OutputManager {
|
||||
public:
|
||||
// Single chip constructors
|
||||
PCF8574OutputManager(uint8_t i2cAddress = 0x20, ChipType chipType = ChipType::PCF8574, uint8_t activeOutputs = 0);
|
||||
|
||||
// Dual chip constructor
|
||||
PCF8574OutputManager(uint8_t addr1, ChipType chip1, uint8_t active1, uint8_t addr2, ChipType chip2, uint8_t active2);
|
||||
|
||||
virtual ~PCF8574OutputManager();
|
||||
|
||||
// OutputManager interface - NEW GENERIC METHODS
|
||||
bool initialize() override;
|
||||
void fireOutput(uint8_t outputIndex) override;
|
||||
void extinguishOutput(uint8_t outputIndex) override;
|
||||
void emergencyShutdown() override;
|
||||
void fireOutputForDuration(uint8_t outputIndex, uint16_t durationMs) override;
|
||||
|
||||
// Batch operations for simultaneous firing
|
||||
void fireOutputsBatch(const std::vector<uint8_t>& outputIndices) override;
|
||||
void extinguishOutputsBatch(const std::vector<uint8_t>& outputIndices) override;
|
||||
void fireOutputsBatchForDuration(const std::vector<std::pair<uint8_t, uint16_t>>& outputDurations) override;
|
||||
|
||||
bool isInitialized() const override { return _allChipsInitialized; }
|
||||
uint8_t getMaxOutputs() const override { return _totalOutputs; }
|
||||
const char* getHardwareType() const override;
|
||||
|
||||
// Multi-chip specific methods
|
||||
uint8_t getChipCount() const { return _chipCount; }
|
||||
ChipConfig getChipConfig(uint8_t chipIndex) const;
|
||||
bool addChip(uint8_t i2cAddress, ChipType chipType, uint8_t activeOutputs = 0);
|
||||
|
||||
// Virtual output mapping information
|
||||
struct VirtualOutputInfo {
|
||||
uint8_t chipIndex;
|
||||
uint8_t localPin;
|
||||
const char* chipType;
|
||||
};
|
||||
VirtualOutputInfo getVirtualOutputInfo(uint8_t virtualOutput) const;
|
||||
|
||||
// Configuration methods
|
||||
void setChipActiveOutputs(uint8_t chipIndex, uint8_t activeOutputs);
|
||||
uint8_t getChipActiveOutputs(uint8_t chipIndex) const;
|
||||
|
||||
// Legacy single-chip methods (for backward compatibility)
|
||||
void setI2CAddress(uint8_t address) { if (_chipCount > 0) _chips[0].i2cAddress = address; }
|
||||
uint8_t getI2CAddress() const { return (_chipCount > 0) ? _chips[0].i2cAddress : 0x20; }
|
||||
|
||||
bool isHealthy() const override;
|
||||
|
||||
protected:
|
||||
// Direct physical output access
|
||||
void firePhysicalOutput(uint8_t physicalOutput, bool state) override;
|
||||
|
||||
private:
|
||||
static const uint8_t MAX_CHIPS = 2; // Maximum supported chips
|
||||
ChipConfig _chips[MAX_CHIPS]; // Chip configurations
|
||||
uint8_t _chipCount; // Number of configured chips
|
||||
uint8_t _totalOutputs; // Total outputs across all chips
|
||||
bool _allChipsInitialized; // True if all chips are initialized
|
||||
mutable char _hardwareTypeBuffer[64]; // Buffer for hardware type string
|
||||
|
||||
// Chip management
|
||||
bool initializeChip(uint8_t chipIndex);
|
||||
void shutdownChip(uint8_t chipIndex);
|
||||
|
||||
// Output routing
|
||||
struct OutputMapping {
|
||||
uint8_t chipIndex; // Which chip (0 or 1)
|
||||
uint8_t localPin; // Pin on that chip (0-7 for PCF8574, 0-15 for PCF8575)
|
||||
};
|
||||
OutputMapping getOutputMapping(uint8_t physicalOutput) const;
|
||||
|
||||
// Low-level I/O operations
|
||||
void writeOutputToChip(uint8_t chipIndex, uint8_t pin, bool state);
|
||||
bool isValidOutputForChip(uint8_t chipIndex, uint8_t pin) const;
|
||||
|
||||
// Initialization helpers
|
||||
void updateTotalOutputs();
|
||||
void generateHardwareTypeString() const;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,504 @@
|
||||
#include "Player.hpp"
|
||||
|
||||
#define TAG "Player"
|
||||
#include "../Communication/CommunicationRouter/CommunicationRouter.hpp"
|
||||
#include "../BellEngine/BellEngine.hpp"
|
||||
#include "../Telemetry/Telemetry.hpp"
|
||||
#include "../TimeKeeper/TimeKeeper.hpp" // 🔥 Include for Timekeeper class definition
|
||||
#include "../BuiltInMelodies/BuiltInMelodies.hpp"
|
||||
|
||||
// Note: Removed global melody_steps dependency for cleaner architecture
|
||||
|
||||
// Constructor with dependencies
|
||||
Player::Player(CommunicationRouter* comm, FileManager* fm)
|
||||
: id(0)
|
||||
, name("melody1")
|
||||
, uid("x")
|
||||
, url("-")
|
||||
, noteAssignments{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
|
||||
, speed(500)
|
||||
, segment_duration(15000)
|
||||
, pause_duration(0)
|
||||
, total_duration(0)
|
||||
, segmentCmpltTime(0)
|
||||
, segmentStartTime(0)
|
||||
, startTime(0)
|
||||
, pauseTime(0)
|
||||
, continuous_loop(false)
|
||||
, infinite_play(false)
|
||||
, isPlaying(false)
|
||||
, isPaused(false)
|
||||
, hardStop(false)
|
||||
, _status(PlayerStatus::STOPPED)
|
||||
, _commManager(comm)
|
||||
, _fileManager(fm)
|
||||
, _bellEngine(nullptr)
|
||||
, _telemetry(nullptr)
|
||||
, _timekeeper(nullptr)
|
||||
, _durationTimerHandle(NULL) {
|
||||
}
|
||||
|
||||
// Default constructor (for backward compatibility)
|
||||
Player::Player()
|
||||
: id(0)
|
||||
, name("melody1")
|
||||
, uid("x")
|
||||
, url("-")
|
||||
, noteAssignments{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}
|
||||
, speed(500)
|
||||
, segment_duration(15000)
|
||||
, pause_duration(0)
|
||||
, total_duration(0)
|
||||
, segmentCmpltTime(0)
|
||||
, segmentStartTime(0)
|
||||
, startTime(0)
|
||||
, pauseTime(0)
|
||||
, continuous_loop(false)
|
||||
, infinite_play(false)
|
||||
, isPlaying(false)
|
||||
, isPaused(false)
|
||||
, hardStop(false)
|
||||
, _status(PlayerStatus::STOPPED)
|
||||
, _commManager(nullptr)
|
||||
, _fileManager(nullptr)
|
||||
, _bellEngine(nullptr)
|
||||
, _telemetry(nullptr)
|
||||
, _timekeeper(nullptr)
|
||||
, _durationTimerHandle(NULL) {
|
||||
}
|
||||
|
||||
void Player::setDependencies(CommunicationRouter* comm, FileManager* fm) {
|
||||
_commManager = comm;
|
||||
_fileManager = fm;
|
||||
}
|
||||
|
||||
// Destructor
|
||||
Player::~Player() {
|
||||
// Stop any ongoing playback
|
||||
if (isPlaying) {
|
||||
forceStop();
|
||||
}
|
||||
|
||||
// Properly cleanup timer
|
||||
if (_durationTimerHandle != NULL) {
|
||||
xTimerDelete(_durationTimerHandle, portMAX_DELAY);
|
||||
_durationTimerHandle = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
void Player::begin() {
|
||||
LOG_INFO(TAG, "Initializing Player with FreeRTOS Timer (saves 4KB RAM!)");
|
||||
|
||||
// Create a periodic timer that fires every 500ms
|
||||
_durationTimerHandle = xTimerCreate(
|
||||
"PlayerTimer", // Timer name
|
||||
pdMS_TO_TICKS(500), // Period (500ms)
|
||||
pdTRUE, // Auto-reload (periodic)
|
||||
this, // Timer ID (pass Player instance)
|
||||
durationTimerCallback // Callback function
|
||||
);
|
||||
|
||||
if (_durationTimerHandle != NULL) {
|
||||
xTimerStart(_durationTimerHandle, 0);
|
||||
LOG_INFO(TAG, "Player initialized successfully with timer");
|
||||
} else {
|
||||
LOG_ERROR(TAG, "Failed to create Player timer!");
|
||||
}
|
||||
}
|
||||
|
||||
void Player::play() {
|
||||
if (_melodySteps.empty()) {
|
||||
LOG_ERROR(TAG, "Cannot play: No melody loaded");
|
||||
return;
|
||||
}
|
||||
|
||||
// 🔥 CRITICAL: Interrupt any active clock alerts - user playback has priority!
|
||||
if (_timekeeper) {
|
||||
_timekeeper->interruptActiveAlert();
|
||||
LOG_DEBUG(TAG, "Player: Interrupted any active clock alerts");
|
||||
}
|
||||
|
||||
if (_bellEngine) {
|
||||
_bellEngine->setMelodyData(_melodySteps);
|
||||
_bellEngine->start();
|
||||
}
|
||||
|
||||
isPlaying = true;
|
||||
hardStop = false;
|
||||
startTime = segmentStartTime = millis();
|
||||
setStatus(PlayerStatus::PLAYING); // Update status and notify clients
|
||||
LOG_DEBUG(TAG, "Plbck: PLAY");
|
||||
}
|
||||
|
||||
void Player::forceStop() {
|
||||
if (_bellEngine) {
|
||||
_bellEngine->emergencyStop();
|
||||
}
|
||||
|
||||
hardStop = true;
|
||||
isPlaying = false;
|
||||
setStatus(PlayerStatus::STOPPED); // Immediate stop, notify clients
|
||||
|
||||
// Save strike counters after melody stops
|
||||
if (_telemetry) {
|
||||
_telemetry->saveStrikeCounters();
|
||||
}
|
||||
|
||||
LOG_DEBUG(TAG, "Plbck: FORCE STOP");
|
||||
}
|
||||
|
||||
void Player::stop() {
|
||||
if (_bellEngine) {
|
||||
_bellEngine->stop();
|
||||
}
|
||||
|
||||
hardStop = false;
|
||||
isPlaying = false;
|
||||
|
||||
// Set STOPPING status - actual stop message will be sent when BellEngine finishes
|
||||
if (isPaused) {
|
||||
setStatus(PlayerStatus::STOPPED);
|
||||
|
||||
// Save strike counters after melody stops
|
||||
if (_telemetry) {
|
||||
_telemetry->saveStrikeCounters();
|
||||
}
|
||||
|
||||
LOG_DEBUG(TAG, "Plbck: STOP from PAUSED state");
|
||||
} else {
|
||||
setStatus(PlayerStatus::STOPPING);
|
||||
LOG_DEBUG(TAG, "Plbck: SOFT STOP (waiting for melody to complete)");
|
||||
}
|
||||
// NOTE: The actual "stop" message is now sent in onMelodyLoopCompleted()
|
||||
// when the BellEngine actually finishes the current loop
|
||||
}
|
||||
|
||||
void Player::pause() {
|
||||
isPaused = true;
|
||||
setStatus(PlayerStatus::PAUSED);
|
||||
LOG_DEBUG(TAG, "Plbck: PAUSE");
|
||||
}
|
||||
|
||||
void Player::unpause() {
|
||||
isPaused = false;
|
||||
segmentStartTime = millis();
|
||||
setStatus(PlayerStatus::PLAYING);
|
||||
LOG_DEBUG(TAG, "Plbck: RESUME");
|
||||
}
|
||||
|
||||
bool Player::command(JsonVariant data) {
|
||||
setMelodyAttributes(data);
|
||||
loadMelodyInRAM(); // Removed parameter - use internal storage
|
||||
|
||||
String action = data["action"];
|
||||
LOG_DEBUG(TAG, "Incoming Command: %s", action.c_str());
|
||||
|
||||
// Play or Stop Logic
|
||||
if (action == "play") {
|
||||
play();
|
||||
return true;
|
||||
} else if (action == "stop") {
|
||||
forceStop();
|
||||
return true;
|
||||
} else {
|
||||
LOG_WARNING(TAG, "Unknown playback action: %s", action.c_str());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void Player::setMelodyAttributes(JsonVariant doc) {
|
||||
if (doc.containsKey("name")) {
|
||||
name = doc["name"].as<const char*>();
|
||||
}
|
||||
if (doc.containsKey("uid")) {
|
||||
uid = doc["uid"].as<const char*>();
|
||||
}
|
||||
if (doc.containsKey("url")) {
|
||||
url = doc["url"].as<const char*>();
|
||||
}
|
||||
if (doc.containsKey("speed")) {
|
||||
speed = doc["speed"].as<uint16_t>();
|
||||
}
|
||||
if (doc.containsKey("note_assignments")) {
|
||||
JsonArray noteArray = doc["note_assignments"];
|
||||
size_t arraySize = min(noteArray.size(), (size_t)16);
|
||||
for (size_t i = 0; i < arraySize; i++) {
|
||||
noteAssignments[i] = noteArray[i];
|
||||
}
|
||||
}
|
||||
if (doc.containsKey("segment_duration")) {
|
||||
segment_duration = doc["segment_duration"].as<uint32_t>();
|
||||
}
|
||||
if (doc.containsKey("pause_duration")) {
|
||||
pause_duration = doc["pause_duration"].as<uint32_t>();
|
||||
}
|
||||
if (doc.containsKey("total_duration")) {
|
||||
total_duration = doc["total_duration"].as<uint32_t>();
|
||||
}
|
||||
if (doc.containsKey("continuous_loop")) {
|
||||
continuous_loop = doc["continuous_loop"].as<bool>();
|
||||
}
|
||||
|
||||
// Recalculate infinite_play based on current values (reset first!)
|
||||
infinite_play = (continuous_loop && total_duration == 0);
|
||||
|
||||
if (!continuous_loop) {
|
||||
total_duration = segment_duration;
|
||||
}
|
||||
|
||||
// Print Just for Debugging Purposes
|
||||
LOG_DEBUG(TAG, "Set Melody Vars / Name: %s, UID: %s",
|
||||
name.c_str(), uid.c_str());
|
||||
LOG_DEBUG(TAG, "URL: %s", url.c_str());
|
||||
LOG_DEBUG(TAG, "Speed: %d, Per Segment Duration: %lu, Pause Duration: %lu, Total Duration: %d, Continuous: %s, Infinite: %s",
|
||||
speed, segment_duration, pause_duration, total_duration,
|
||||
continuous_loop ? "true" : "false", infinite_play ? "true" : "false");
|
||||
}
|
||||
|
||||
void Player::loadMelodyInRAM() {
|
||||
String uidStr = String(uid.c_str());
|
||||
|
||||
// 🎵 PRIORITY 1: Check if this is a built-in melody
|
||||
if (BuiltInMelodies::isBuiltInMelody(uidStr)) {
|
||||
LOG_INFO(TAG, "Loading built-in melody: %s", uidStr.c_str());
|
||||
|
||||
if (BuiltInMelodies::loadBuiltInMelody(uidStr, _melodySteps)) {
|
||||
LOG_INFO(TAG, "✅ Built-in melody loaded successfully: %d steps", _melodySteps.size());
|
||||
return;
|
||||
} else {
|
||||
LOG_ERROR(TAG, "Failed to load built-in melody: %s", uidStr.c_str());
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 🎵 PRIORITY 2: Load from SD card
|
||||
String filePath = "/melodies/" + uidStr;
|
||||
|
||||
File bin_file = SD.open(filePath.c_str(), FILE_READ);
|
||||
if (!bin_file) {
|
||||
LOG_ERROR(TAG, "Failed to open file: %s", filePath.c_str());
|
||||
LOG_ERROR(TAG, "Check Servers for the File...");
|
||||
|
||||
// Try to download the file using FileManager
|
||||
if (_fileManager) {
|
||||
StaticJsonDocument<128> doc;
|
||||
doc["download_url"] = url;
|
||||
doc["melodys_uid"] = uid;
|
||||
|
||||
if (!_fileManager->addMelody(doc)) {
|
||||
LOG_ERROR(TAG, "Failed to Download File. Check Internet Connection");
|
||||
return;
|
||||
} else {
|
||||
bin_file = SD.open(filePath.c_str(), FILE_READ);
|
||||
}
|
||||
} else {
|
||||
LOG_ERROR(TAG, "FileManager not available for download");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
size_t fileSize = bin_file.size();
|
||||
if (fileSize % 2 != 0) {
|
||||
LOG_ERROR(TAG, "Invalid file size: %u (not a multiple of 2)", fileSize);
|
||||
bin_file.close();
|
||||
return;
|
||||
}
|
||||
|
||||
// Load into Player's internal melody storage only
|
||||
_melodySteps.resize(fileSize / 2);
|
||||
|
||||
for (size_t i = 0; i < _melodySteps.size(); i++) {
|
||||
uint8_t high = bin_file.read();
|
||||
uint8_t low = bin_file.read();
|
||||
_melodySteps[i] = (high << 8) | low;
|
||||
}
|
||||
|
||||
LOG_INFO(TAG, "Melody loaded successfully from SD: %d steps", _melodySteps.size());
|
||||
bin_file.close();
|
||||
}
|
||||
|
||||
// Static timer callback function for FreeRTOS
|
||||
void Player::durationTimerCallback(TimerHandle_t xTimer) {
|
||||
// Get Player instance from timer ID
|
||||
Player* player = static_cast<Player*>(pvTimerGetTimerID(xTimer));
|
||||
|
||||
// Only run checks when actually playing
|
||||
if (!player->isPlaying) {
|
||||
return;
|
||||
}
|
||||
|
||||
unsigned long now = millis();
|
||||
|
||||
if (player->timeToStop(now)) {
|
||||
player->stop();
|
||||
} else if (player->timeToPause(now)) {
|
||||
player->pause();
|
||||
} else if (player->timeToResume(now)) {
|
||||
player->unpause();
|
||||
}
|
||||
}
|
||||
|
||||
// Check if it's time to stop playback
|
||||
bool Player::timeToStop(unsigned long now) {
|
||||
if (isPlaying && !infinite_play) {
|
||||
uint64_t stopTime = startTime + total_duration;
|
||||
if (now >= stopTime) {
|
||||
LOG_DEBUG(TAG, "(TimerFunction) Total Run Duration Reached. Soft Stopping.");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Status management and BellEngine callback
|
||||
void Player::setStatus(PlayerStatus newStatus) {
|
||||
if (_status == newStatus) {
|
||||
return; // No change, don't send duplicate messages
|
||||
}
|
||||
|
||||
PlayerStatus oldStatus = _status;
|
||||
_status = newStatus;
|
||||
|
||||
// Send appropriate message to ALL clients (WebSocket + MQTT) based on status change
|
||||
if (_commManager) {
|
||||
StaticJsonDocument<256> doc;
|
||||
doc["status"] = "INFO";
|
||||
doc["type"] = "playback";
|
||||
|
||||
// Create payload object for complex data
|
||||
JsonObject payload = doc.createNestedObject("payload");
|
||||
|
||||
switch (newStatus) {
|
||||
case PlayerStatus::PLAYING:
|
||||
payload["action"] = "playing";
|
||||
payload["time_elapsed"] = (millis() - startTime) / 1000; // Convert to seconds
|
||||
break;
|
||||
case PlayerStatus::PAUSED:
|
||||
payload["action"] = "paused";
|
||||
payload["time_elapsed"] = (millis() - startTime) / 1000;
|
||||
break;
|
||||
case PlayerStatus::STOPPED:
|
||||
payload["action"] = "idle";
|
||||
payload["time_elapsed"] = 0;
|
||||
break;
|
||||
case PlayerStatus::STOPPING:
|
||||
payload["action"] = "stopping";
|
||||
payload["time_elapsed"] = (millis() - startTime) / 1000;
|
||||
break;
|
||||
}
|
||||
|
||||
// Add projected run time for all states (0 if not applicable)
|
||||
uint64_t projectedRunTime = calculateProjectedRunTime();
|
||||
payload["projected_run_time"] = projectedRunTime;
|
||||
|
||||
// 🔥 Use broadcastStatus() to send to BOTH WebSocket AND MQTT clients!
|
||||
_commManager->broadcastStatus(doc);
|
||||
|
||||
LOG_DEBUG(TAG, "Status changed: %d → %d, broadcast sent with runTime: %llu",
|
||||
(int)oldStatus, (int)newStatus, projectedRunTime);
|
||||
}
|
||||
}
|
||||
|
||||
void Player::onMelodyLoopCompleted() {
|
||||
// This is called by BellEngine when a melody loop actually finishes
|
||||
if (_status == PlayerStatus::STOPPING) {
|
||||
// We were in soft stop mode, now actually stop
|
||||
setStatus(PlayerStatus::STOPPED);
|
||||
LOG_DEBUG(TAG, "Plbck: ACTUAL STOP (melody loop completed)");
|
||||
}
|
||||
|
||||
// Mark segment completion time
|
||||
segmentCmpltTime = millis();
|
||||
}
|
||||
|
||||
// Check if it's time to pause playback
|
||||
bool Player::timeToPause(unsigned long now) {
|
||||
if (isPlaying && continuous_loop) {
|
||||
uint64_t timeToPause = segmentStartTime + segment_duration;
|
||||
LOG_DEBUG(TAG, "PTL: %llu // NOW: %lu", timeToPause, now);
|
||||
if (now >= timeToPause && !isPaused) {
|
||||
LOG_DEBUG(TAG, "(TimerFunction) Segment Duration Reached. Pausing.");
|
||||
pauseTime = now;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if it's time to resume playback
|
||||
bool Player::timeToResume(unsigned long now) {
|
||||
if (isPaused) {
|
||||
uint64_t timeToResume = segmentCmpltTime + pause_duration;
|
||||
if (now >= timeToResume) {
|
||||
LOG_DEBUG(TAG, "(TimerFunction) Pause Duration Reached. Resuming");
|
||||
segmentStartTime = now; // Reset segment start time for next cycle
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Calculate the projected total run time of current playback
|
||||
uint64_t Player::calculateProjectedRunTime() const {
|
||||
if (_melodySteps.empty() || (_status == PlayerStatus::STOPPED)) {
|
||||
return 0; // No melody loaded or actually stopped
|
||||
}
|
||||
|
||||
// Calculate single loop duration: steps * speed (in milliseconds)
|
||||
uint32_t singleLoopDuration = _melodySteps.size() * speed;
|
||||
|
||||
if (infinite_play || total_duration == 0) {
|
||||
return 0; // Infinite playback has no end time
|
||||
}
|
||||
|
||||
// Calculate how many loops are needed to meet or exceed total_duration
|
||||
uint32_t loopsNeeded = (total_duration + singleLoopDuration - 1) / singleLoopDuration; // Ceiling division
|
||||
|
||||
// Calculate actual total duration (this is the projected run time)
|
||||
uint32_t actualTotalDuration = singleLoopDuration * loopsNeeded;
|
||||
|
||||
// Return the total duration (offset from start), not a timestamp
|
||||
return actualTotalDuration;
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// HEALTH CHECK IMPLEMENTATION
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
bool Player::isHealthy() const {
|
||||
// Check if dependencies are properly set
|
||||
if (!_commManager) {
|
||||
LOG_DEBUG(TAG, "Player: Unhealthy - Communication manager not set");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!_fileManager) {
|
||||
LOG_DEBUG(TAG, "Player: Unhealthy - File manager not set");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!_bellEngine) {
|
||||
LOG_DEBUG(TAG, "Player: Unhealthy - BellEngine not set");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if timer is properly created
|
||||
if (_durationTimerHandle == NULL) {
|
||||
LOG_DEBUG(TAG, "Player: Unhealthy - Duration timer not created");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if timer is actually running
|
||||
if (xTimerIsTimerActive(_durationTimerHandle) == pdFALSE) {
|
||||
LOG_DEBUG(TAG, "Player: Unhealthy - Duration timer not active");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check for consistent playback state
|
||||
if (isPlaying && (_status == PlayerStatus::STOPPED)) {
|
||||
LOG_DEBUG(TAG, "Player: Unhealthy - Inconsistent playback state");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* PLAYER.HPP - Melody Playback and Control System
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 🎵 THE MELODY MAESTRO OF VESPER 🎵
|
||||
*
|
||||
* This class manages melody playback, timing control, and coordination with
|
||||
* the BellEngine for precise bell activation. It handles melody loading,
|
||||
* duration management, and playback state control.
|
||||
*
|
||||
* 🏗️ ARCHITECTURE:
|
||||
* • Clean separation between playback logic and timing engine
|
||||
* • FreeRTOS timer-based duration control (saves 4KB RAM vs tasks!)
|
||||
* • Dependency injection for loose coupling
|
||||
* • Thread-safe state management
|
||||
* • Comprehensive melody metadata handling
|
||||
*
|
||||
* 🎶 KEY FEATURES:
|
||||
* • Multi-format melody support with note assignments
|
||||
* • Flexible timing control (speed, segments, loops)
|
||||
* • Pause/resume functionality
|
||||
* • Duration-based automatic stopping
|
||||
* • Continuous and finite loop modes
|
||||
* • Real-time playback status tracking
|
||||
*
|
||||
* ⏱️ TIMING MANAGEMENT:
|
||||
* • Segment-based playback with configurable pauses
|
||||
* • Total duration limiting
|
||||
* • Precision timing coordination with BellEngine
|
||||
* • Memory-efficient timer implementation
|
||||
*
|
||||
* 🔗 INTEGRATION:
|
||||
* The Player coordinates with BellEngine for precise timing,
|
||||
* Communication for command handling, and FileManager for
|
||||
* melody file operations.
|
||||
*
|
||||
* 📋 VERSION: 2.0 (Modular architecture with dependency injection)
|
||||
* 📅 DATE: 2025
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
// SYSTEM INCLUDES - Core libraries for melody playback
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
#include <Arduino.h> // Arduino core functionality
|
||||
#include <vector> // STL vector for melody data storage
|
||||
#include <string> // STL string for melody metadata
|
||||
#include <cstdint> // Fixed-width integer types
|
||||
#include <ArduinoJson.h> // JSON parsing for melody configuration
|
||||
#include <ESPAsyncWebServer.h> // WebSocket client handling
|
||||
#include <SD.h> // SD card operations for melody files
|
||||
#include "freertos/FreeRTOS.h" // FreeRTOS kernel
|
||||
#include "freertos/task.h" // FreeRTOS task management
|
||||
#include "../Logging/Logging.hpp" // Centralized logging system
|
||||
#include "../FileManager/FileManager.hpp" // File operations abstraction
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
// FORWARD DECLARATIONS - Dependencies injected at runtime
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
class CommunicationRouter; // Command handling and communication
|
||||
class BellEngine; // High-precision timing engine
|
||||
class Telemetry; // System telemetry and monitoring
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
// PLAYER STATUS ENUMERATION
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
/**
|
||||
* @enum PlayerStatus
|
||||
* @brief Defines the current state of the player
|
||||
*/
|
||||
enum class PlayerStatus {
|
||||
STOPPED, // ⏹️ Not playing, engine stopped
|
||||
PLAYING, // ▶️ Actively playing melody
|
||||
PAUSED, // ⏸️ Temporarily paused between segments
|
||||
STOPPING // 🔄 Soft stop triggered, waiting for melody to complete
|
||||
};
|
||||
|
||||
/**
|
||||
* @class Player
|
||||
* @brief Melody playback and timing control system
|
||||
*
|
||||
* The Player class manages all aspects of melody playback including timing,
|
||||
* duration control, pause/resume functionality, and coordination with the
|
||||
* BellEngine for precise bell activation.
|
||||
*
|
||||
* Key responsibilities:
|
||||
* - Melody metadata management (name, speed, duration, etc.)
|
||||
* - Playback state control (play, pause, stop)
|
||||
* - Duration-based automatic stopping
|
||||
* - Note assignment mapping for bell activation
|
||||
* - Integration with BellEngine for precision timing
|
||||
*/
|
||||
class Player {
|
||||
public:
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// CONSTRUCTORS & DEPENDENCY INJECTION
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Constructor with dependency injection
|
||||
* @param comm Pointer to communication manager
|
||||
* @param fm Pointer to file manager
|
||||
*/
|
||||
Player(CommunicationRouter* comm, FileManager* fm);
|
||||
|
||||
/**
|
||||
* @brief Default constructor for backward compatibility
|
||||
*
|
||||
* When using this constructor, must call setDependencies() before use.
|
||||
*/
|
||||
Player();
|
||||
|
||||
/**
|
||||
* @brief Set dependencies after construction
|
||||
* @param comm Pointer to communication manager
|
||||
* @param fm Pointer to file manager
|
||||
*/
|
||||
void setDependencies(CommunicationRouter* comm, FileManager* fm);
|
||||
|
||||
/**
|
||||
* @brief Set BellEngine reference for precision timing
|
||||
* @param engine Pointer to BellEngine instance
|
||||
*/
|
||||
void setBellEngine(BellEngine* engine) { _bellEngine = engine; }
|
||||
|
||||
/**
|
||||
* @brief Set Telemetry reference for strike counter persistence
|
||||
* @param telemetry Pointer to Telemetry instance
|
||||
*/
|
||||
void setTelemetry(Telemetry* telemetry) { _telemetry = telemetry; }
|
||||
|
||||
/**
|
||||
* @brief Set Timekeeper reference for alert coordination
|
||||
* @param timekeeper Pointer to Timekeeper instance
|
||||
*/
|
||||
void setTimekeeper(class Timekeeper* timekeeper) { _timekeeper = timekeeper; }
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// MELODY METADATA - Public access for compatibility
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
uint16_t id; // 🏷️ Internal ID of the selected melody
|
||||
std::string name; // 🏵️ Display name of the melody
|
||||
std::string uid; // 🆔 Unique identifier from Firestore
|
||||
std::string url; // 🌐 Download URL for melody binary
|
||||
uint16_t noteAssignments[16]; // 🎹 Note-to-bell mapping configuration
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// TIMING CONFIGURATION
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
uint16_t speed; // ⏱️ Time per beat in milliseconds
|
||||
uint32_t segment_duration; // ⏳ Duration per loop segment (milliseconds)
|
||||
uint32_t pause_duration; // ⏸️ Pause between segments (milliseconds)
|
||||
uint32_t total_duration; // ⏰ Total runtime limit (milliseconds)
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// RUNTIME STATE TRACKING
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
uint64_t segmentCmpltTime; // ✅ Timestamp of last segment completion
|
||||
uint64_t segmentStartTime; // 🚀 Timestamp when current segment started
|
||||
uint64_t startTime; // 🏁 Timestamp when melody playback began
|
||||
uint64_t pauseTime; // ⏸️ Timestamp when melody was paused
|
||||
bool isPlaying; // ▶️ Currently playing indicator
|
||||
bool isPaused; // ⏸️ Currently paused indicator
|
||||
bool hardStop; // 🚑 Emergency stop flag
|
||||
bool continuous_loop; // 🔄 Continuous loop mode flag
|
||||
bool infinite_play; // ∞ Infinite playback mode flag
|
||||
PlayerStatus _status; // 📊 Current player status
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// DESTRUCTOR
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @brief Destructor - Clean up resources
|
||||
*
|
||||
* Ensures proper cleanup of timers and resources.
|
||||
*/
|
||||
~Player();
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// INITIALIZATION & CONTROL METHODS
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/** @brief Initialize playback control system */
|
||||
void begin();
|
||||
|
||||
/** @brief Start melody playback */
|
||||
void play();
|
||||
|
||||
/** @brief Stop melody playback gracefully */
|
||||
void stop();
|
||||
|
||||
/** @brief Force immediate stop */
|
||||
void forceStop();
|
||||
|
||||
/** @brief Pause current playback */
|
||||
void pause();
|
||||
|
||||
/** @brief Resume paused playback */
|
||||
void unpause();
|
||||
|
||||
/** @brief Handle JSON commands from communication layer */
|
||||
bool command(JsonVariant data);
|
||||
|
||||
/** @brief Set melody attributes from JSON configuration */
|
||||
void setMelodyAttributes(JsonVariant doc);
|
||||
|
||||
/** @brief Load melody data into RAM for playback */
|
||||
void loadMelodyInRAM();
|
||||
|
||||
/** @brief Static timer callback for FreeRTOS duration control */
|
||||
static void durationTimerCallback(TimerHandle_t xTimer);
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
// STATUS QUERY METHODS
|
||||
// ═════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/** @brief Get current player status */
|
||||
PlayerStatus getStatus() const { return _status; }
|
||||
|
||||
/** @brief Check if player is currently playing */
|
||||
bool isCurrentlyPlaying() const { return _status == PlayerStatus::PLAYING; }
|
||||
|
||||
/** @brief Check if player is currently paused */
|
||||
bool isCurrentlyPaused() const { return _status == PlayerStatus::PAUSED; }
|
||||
|
||||
/** @brief Check if player is in stopping state (soft stop triggered) */
|
||||
bool isCurrentlyStopping() const { return _status == PlayerStatus::STOPPING; }
|
||||
|
||||
/** @brief Check if player is completely stopped */
|
||||
bool isCurrentlyStopped() const { return _status == PlayerStatus::STOPPED; }
|
||||
|
||||
/** @brief BellEngine callback when melody loop actually completes */
|
||||
void onMelodyLoopCompleted();
|
||||
|
||||
/** @brief Calculate the projected total run time of current playback */
|
||||
uint64_t calculateProjectedRunTime() const;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// HEALTH CHECK METHOD
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/** @brief Check if Player is in healthy state */
|
||||
bool isHealthy() const;
|
||||
|
||||
private:
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// PRIVATE DEPENDENCIES AND DATA
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
CommunicationRouter* _commManager; // 📡 Communication system reference
|
||||
FileManager* _fileManager; // 📁 File operations reference
|
||||
BellEngine* _bellEngine; // 🔥 High-precision timing engine reference
|
||||
Telemetry* _telemetry; // 📄 Telemetry system reference
|
||||
class Timekeeper* _timekeeper; // ⏰ Timekeeper reference for alert coordination
|
||||
|
||||
std::vector<uint16_t> _melodySteps; // 🎵 Melody data owned by Player
|
||||
TimerHandle_t _durationTimerHandle = NULL; // ⏱️ FreeRTOS timer (saves 4KB vs task!)
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// PRIVATE HELPER METHODS
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/** @brief Check if it's time to stop based on duration */
|
||||
bool timeToStop(unsigned long now);
|
||||
|
||||
/** @brief Check if it's time to pause based on segment timing */
|
||||
bool timeToPause(unsigned long now);
|
||||
|
||||
/** @brief Check if it's time to resume from pause */
|
||||
bool timeToResume(unsigned long now);
|
||||
|
||||
/** @brief Update player status and notify clients if changed */
|
||||
void setStatus(PlayerStatus newStatus);
|
||||
};
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// END OF PLAYER.HPP
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
@@ -0,0 +1,227 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════
|
||||
* SDCARDMUTEX.HPP - Thread-Safe SD Card Access Manager
|
||||
* ═══════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 🔒 THE SD CARD CONCURRENCY GUARDIAN OF VESPER 🔒
|
||||
*
|
||||
* This singleton class provides thread-safe access to the SD card by managing
|
||||
* a FreeRTOS mutex. All SD card operations MUST acquire this mutex to prevent
|
||||
* concurrent access that can lead to file corruption and write failures.
|
||||
*
|
||||
* CRITICAL: The ESP32 SD library is NOT thread-safe. Without this mutex,
|
||||
* simultaneous SD access from multiple FreeRTOS tasks will cause:
|
||||
* - File corruption
|
||||
* - Write failures
|
||||
* - SD card "not recognized" errors
|
||||
* - Random intermittent failures
|
||||
*
|
||||
* USAGE:
|
||||
*
|
||||
* // Lock before ANY SD operation
|
||||
* if (SDCardMutex::getInstance().lock()) {
|
||||
* File file = SD.open("/myfile.txt", FILE_WRITE);
|
||||
* file.println("data");
|
||||
* file.close();
|
||||
* SDCardMutex::getInstance().unlock();
|
||||
* }
|
||||
*
|
||||
* // Or use RAII helper for automatic unlock
|
||||
* {
|
||||
* SDCardLock lock; // Acquires mutex
|
||||
* File file = SD.open("/myfile.txt", FILE_WRITE);
|
||||
* file.println("data");
|
||||
* file.close();
|
||||
* } // Automatically releases mutex when going out of scope
|
||||
*
|
||||
* 📋 VERSION: 1.0
|
||||
* 📅 DATE: 2025-01-07
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/semphr.h>
|
||||
#include "../Logging/Logging.hpp"
|
||||
|
||||
/**
|
||||
* @brief Singleton class for thread-safe SD card access
|
||||
*
|
||||
* Manages a global mutex that all SD card operations must acquire
|
||||
* to prevent concurrent access from multiple FreeRTOS tasks.
|
||||
*/
|
||||
class SDCardMutex {
|
||||
public:
|
||||
/**
|
||||
* @brief Get the singleton instance
|
||||
* @return Reference to the singleton instance
|
||||
*/
|
||||
static SDCardMutex& getInstance() {
|
||||
static SDCardMutex instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Initialize the mutex (call once during setup)
|
||||
* @return true if initialization succeeded, false otherwise
|
||||
*/
|
||||
bool begin() {
|
||||
if (_mutex != NULL) {
|
||||
LOG_WARNING("SDCardMutex", "SDCardMutex already initialized");
|
||||
return true;
|
||||
}
|
||||
|
||||
_mutex = xSemaphoreCreateMutex();
|
||||
|
||||
if (_mutex == NULL) {
|
||||
LOG_ERROR("SDCardMutex", "Failed to create SD card mutex!");
|
||||
return false;
|
||||
}
|
||||
|
||||
LOG_INFO("SDCardMutex", "SD card mutex initialized");
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Acquire the SD card mutex
|
||||
* @param timeoutMs Maximum time to wait for mutex (default: 5 seconds)
|
||||
* @return true if mutex acquired, false if timeout
|
||||
*/
|
||||
bool lock(uint32_t timeoutMs = 5000) {
|
||||
if (_mutex == NULL) {
|
||||
LOG_ERROR("SDCardMutex", "SDCardMutex not initialized!");
|
||||
return false;
|
||||
}
|
||||
|
||||
TickType_t timeout = (timeoutMs == portMAX_DELAY)
|
||||
? portMAX_DELAY
|
||||
: pdMS_TO_TICKS(timeoutMs);
|
||||
|
||||
if (xSemaphoreTake(_mutex, timeout) == pdTRUE) {
|
||||
_lockCount++;
|
||||
return true;
|
||||
} else {
|
||||
LOG_ERROR("SDCardMutex", "SD card mutex timeout after %u ms!", timeoutMs);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Release the SD card mutex
|
||||
*/
|
||||
void unlock() {
|
||||
if (_mutex == NULL) {
|
||||
LOG_ERROR("SDCardMutex", "SDCardMutex not initialized!");
|
||||
return;
|
||||
}
|
||||
|
||||
xSemaphoreGive(_mutex);
|
||||
_unlockCount++;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Get mutex lock statistics
|
||||
* @param locks Reference to store lock count
|
||||
* @param unlocks Reference to store unlock count
|
||||
*/
|
||||
void getStats(uint32_t& locks, uint32_t& unlocks) const {
|
||||
locks = _lockCount;
|
||||
unlocks = _unlockCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Check if mutex is currently locked by THIS task
|
||||
* @return true if current task holds the mutex
|
||||
*/
|
||||
bool isLockedByMe() const {
|
||||
if (_mutex == NULL) {
|
||||
return false;
|
||||
}
|
||||
return xSemaphoreGetMutexHolder(_mutex) == xTaskGetCurrentTaskHandle();
|
||||
}
|
||||
|
||||
// Delete copy constructor and assignment operator (singleton)
|
||||
SDCardMutex(const SDCardMutex&) = delete;
|
||||
SDCardMutex& operator=(const SDCardMutex&) = delete;
|
||||
|
||||
private:
|
||||
SDCardMutex()
|
||||
: _mutex(NULL)
|
||||
, _lockCount(0)
|
||||
, _unlockCount(0) {
|
||||
}
|
||||
|
||||
~SDCardMutex() {
|
||||
if (_mutex != NULL) {
|
||||
vSemaphoreDelete(_mutex);
|
||||
_mutex = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
SemaphoreHandle_t _mutex;
|
||||
uint32_t _lockCount;
|
||||
uint32_t _unlockCount;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief RAII helper class for automatic mutex lock/unlock
|
||||
*
|
||||
* Acquires SD card mutex on construction and releases on destruction.
|
||||
* Use this for automatic cleanup when going out of scope.
|
||||
*
|
||||
* Example:
|
||||
* {
|
||||
* SDCardLock lock;
|
||||
* File file = SD.open("/test.txt", FILE_WRITE);
|
||||
* file.println("data");
|
||||
* file.close();
|
||||
* } // Mutex automatically released here
|
||||
*/
|
||||
class SDCardLock {
|
||||
public:
|
||||
/**
|
||||
* @brief Constructor - acquires mutex
|
||||
* @param timeoutMs Maximum time to wait for mutex
|
||||
*/
|
||||
explicit SDCardLock(uint32_t timeoutMs = 5000)
|
||||
: _locked(false) {
|
||||
_locked = SDCardMutex::getInstance().lock(timeoutMs);
|
||||
if (!_locked) {
|
||||
LOG_ERROR("SDCardMutex", "SDCardLock failed to acquire mutex!");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Destructor - releases mutex
|
||||
*/
|
||||
~SDCardLock() {
|
||||
if (_locked) {
|
||||
SDCardMutex::getInstance().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Check if lock was successfully acquired
|
||||
* @return true if mutex is locked
|
||||
*/
|
||||
bool isLocked() const {
|
||||
return _locked;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Explicit conversion to bool for easy checking
|
||||
*/
|
||||
explicit operator bool() const {
|
||||
return _locked;
|
||||
}
|
||||
|
||||
// Delete copy constructor and assignment operator
|
||||
SDCardLock(const SDCardLock&) = delete;
|
||||
SDCardLock& operator=(const SDCardLock&) = delete;
|
||||
|
||||
private:
|
||||
bool _locked;
|
||||
};
|
||||
@@ -0,0 +1,281 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* SETTINGSPAGE.H - HTML Content for Settings Web Interface
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* This file contains the HTML/CSS/JavaScript for the VESPER network settings page.
|
||||
* Separated from the main implementation for better maintainability.
|
||||
*
|
||||
* 📋 VERSION: 1.0
|
||||
* 📅 DATE: 2025-12-29
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
// HTML template for the settings page
|
||||
// Use placeholders for dynamic content:
|
||||
// %MODE_BADGE_CLASS% - "ap" or "station"
|
||||
// %MODE_TEXT% - "AP Mode" or "Station Mode"
|
||||
// %CURRENT_IP% - Current IP address
|
||||
// %DEVICE_UID% - Device unique ID
|
||||
// %FW_VERSION% - Firmware version
|
||||
// %AP_ACTIVE_CLASS% - "active" if in AP mode, "" otherwise
|
||||
// %STATION_ACTIVE_CLASS% - "active" if in station mode, "" otherwise
|
||||
// %SELECTED_MODE% - "ap" or "station"
|
||||
|
||||
const char SETTINGS_PAGE_HTML[] PROGMEM = R"rawliteral(
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>VESPER Network Settings</title>
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
body {
|
||||
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 20px;
|
||||
}
|
||||
.container {
|
||||
background: white;
|
||||
border-radius: 20px;
|
||||
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
|
||||
padding: 40px;
|
||||
max-width: 500px;
|
||||
width: 100%;
|
||||
}
|
||||
.header {
|
||||
text-align: center;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
.header h1 {
|
||||
color: #667eea;
|
||||
font-size: 32px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.header p {
|
||||
color: #666;
|
||||
font-size: 14px;
|
||||
}
|
||||
.status-card {
|
||||
background: #f8f9fa;
|
||||
border-radius: 12px;
|
||||
padding: 20px;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
.status-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 12px;
|
||||
font-size: 14px;
|
||||
}
|
||||
.status-item:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.status-label {
|
||||
color: #666;
|
||||
font-weight: 500;
|
||||
}
|
||||
.status-value {
|
||||
color: #333;
|
||||
font-weight: 600;
|
||||
}
|
||||
.mode-badge {
|
||||
display: inline-block;
|
||||
padding: 4px 12px;
|
||||
border-radius: 20px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.mode-badge.ap {
|
||||
background: #e3f2fd;
|
||||
color: #1976d2;
|
||||
}
|
||||
.mode-badge.station {
|
||||
background: #e8f5e9;
|
||||
color: #388e3c;
|
||||
}
|
||||
.section-title {
|
||||
font-size: 18px;
|
||||
color: #333;
|
||||
margin-bottom: 20px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.mode-selector {
|
||||
display: flex;
|
||||
gap: 15px;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
.mode-option {
|
||||
flex: 1;
|
||||
background: #f8f9fa;
|
||||
border: 2px solid #e0e0e0;
|
||||
border-radius: 12px;
|
||||
padding: 20px;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
text-align: center;
|
||||
}
|
||||
.mode-option:hover {
|
||||
border-color: #667eea;
|
||||
background: #f0f4ff;
|
||||
}
|
||||
.mode-option.active {
|
||||
border-color: #667eea;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
}
|
||||
.mode-option h3 {
|
||||
font-size: 16px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.mode-option p {
|
||||
font-size: 12px;
|
||||
opacity: 0.8;
|
||||
}
|
||||
.btn {
|
||||
width: 100%;
|
||||
padding: 15px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.btn-primary {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
}
|
||||
.btn-primary:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
|
||||
}
|
||||
.btn-secondary {
|
||||
background: #f8f9fa;
|
||||
color: #666;
|
||||
}
|
||||
.btn-secondary:hover {
|
||||
background: #e9ecef;
|
||||
}
|
||||
.info-box {
|
||||
background: #fff3cd;
|
||||
border-left: 4px solid #ffc107;
|
||||
padding: 15px;
|
||||
border-radius: 8px;
|
||||
margin-top: 20px;
|
||||
font-size: 13px;
|
||||
color: #856404;
|
||||
}
|
||||
.footer {
|
||||
text-align: center;
|
||||
margin-top: 30px;
|
||||
padding-top: 20px;
|
||||
border-top: 1px solid #e0e0e0;
|
||||
color: #999;
|
||||
font-size: 12px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>VESPER Settings</h1>
|
||||
<p>Network Configuration</p>
|
||||
</div>
|
||||
|
||||
<div class="status-card">
|
||||
<div class="status-item">
|
||||
<span class="status-label">Current Mode:</span>
|
||||
<span class="status-value">
|
||||
<span class="mode-badge %MODE_BADGE_CLASS%">
|
||||
%MODE_TEXT%
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="status-item">
|
||||
<span class="status-label">IP Address:</span>
|
||||
<span class="status-value">%CURRENT_IP%</span>
|
||||
</div>
|
||||
<div class="status-item">
|
||||
<span class="status-label">Device UID:</span>
|
||||
<span class="status-value">%DEVICE_UID%</span>
|
||||
</div>
|
||||
<div class="status-item">
|
||||
<span class="status-label">Firmware:</span>
|
||||
<span class="status-value">v%FW_VERSION%</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="section-title">Select Network Mode</div>
|
||||
|
||||
<div class="mode-selector">
|
||||
<div class="mode-option %AP_ACTIVE_CLASS%" onclick="selectMode('ap')">
|
||||
<h3>AP Mode</h3>
|
||||
<p>Direct Connection<br>192.168.4.1</p>
|
||||
</div>
|
||||
<div class="mode-option %STATION_ACTIVE_CLASS%" onclick="selectMode('station')">
|
||||
<h3>Router Mode</h3>
|
||||
<p>Connect via Router<br>WiFi/Ethernet</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button class="btn btn-primary" onclick="applyMode()">Apply & Reboot</button>
|
||||
<button class="btn btn-secondary" onclick="rebootDevice()">Reboot Device</button>
|
||||
|
||||
<div class="info-box">
|
||||
Device will reboot after applying changes. Make sure to reconnect to the correct network after reboot.
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
VESPER Bell Automation System<br>
|
||||
Advanced Bell Systems
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let selectedMode = '%SELECTED_MODE%';
|
||||
|
||||
function selectMode(mode) {
|
||||
selectedMode = mode;
|
||||
document.querySelectorAll('.mode-option').forEach(el => {
|
||||
el.classList.remove('active');
|
||||
});
|
||||
event.target.closest('.mode-option').classList.add('active');
|
||||
}
|
||||
|
||||
function applyMode() {
|
||||
if (confirm('Device will reboot and switch to ' + (selectedMode === 'ap' ? 'AP Mode' : 'Router Mode') + '. Continue?')) {
|
||||
fetch('/api/set-mode', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
|
||||
body: 'mode=' + selectedMode
|
||||
}).then(response => {
|
||||
alert('Rebooting... Please wait 10 seconds and reconnect.');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function rebootDevice() {
|
||||
if (confirm('Reboot device now?')) {
|
||||
fetch('/api/reboot', {method: 'POST'}).then(() => {
|
||||
alert('Rebooting... Please wait 10 seconds.');
|
||||
});
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
)rawliteral";
|
||||
@@ -0,0 +1,126 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* SETTINGSWEBSERVER.CPP - Network Mode Settings Web Interface Implementation
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#include "SettingsWebServer.hpp"
|
||||
|
||||
#define TAG "SettingsWebServer"
|
||||
#include "SettingsPage.h"
|
||||
#include "../ConfigManager/ConfigManager.hpp"
|
||||
#include "../Networking/Networking.hpp"
|
||||
#include "../Logging/Logging.hpp"
|
||||
|
||||
SettingsWebServer::SettingsWebServer(AsyncWebServer& server,
|
||||
ConfigManager& configManager,
|
||||
Networking& networking)
|
||||
: _server(server)
|
||||
, _configManager(configManager)
|
||||
, _networking(networking) {
|
||||
}
|
||||
|
||||
SettingsWebServer::~SettingsWebServer() {
|
||||
}
|
||||
|
||||
void SettingsWebServer::begin() {
|
||||
LOG_INFO(TAG, "SettingsWebServer - Initializing settings web interface");
|
||||
|
||||
// GET /settings - Main settings page
|
||||
_server.on("/settings", HTTP_GET,
|
||||
[this](AsyncWebServerRequest* request) {
|
||||
handleSettingsPage(request);
|
||||
}
|
||||
);
|
||||
|
||||
// POST /api/set-mode - Set network mode
|
||||
_server.on("/api/set-mode", HTTP_POST,
|
||||
[this](AsyncWebServerRequest* request) {
|
||||
handleSetMode(request);
|
||||
}
|
||||
);
|
||||
|
||||
// POST /api/reboot - Reboot device
|
||||
_server.on("/api/reboot", HTTP_POST,
|
||||
[this](AsyncWebServerRequest* request) {
|
||||
handleReboot(request);
|
||||
}
|
||||
);
|
||||
|
||||
LOG_INFO(TAG, "SettingsWebServer - Endpoints registered");
|
||||
LOG_INFO(TAG, " GET /settings - Settings page");
|
||||
LOG_INFO(TAG, " POST /api/set-mode - Set network mode");
|
||||
LOG_INFO(TAG, " POST /api/reboot - Reboot device");
|
||||
}
|
||||
|
||||
void SettingsWebServer::handleSettingsPage(AsyncWebServerRequest* request) {
|
||||
LOG_DEBUG(TAG, "SettingsWebServer - Settings page requested");
|
||||
String html = generateSettingsHTML();
|
||||
request->send(200, "text/html", html);
|
||||
}
|
||||
|
||||
void SettingsWebServer::handleSetMode(AsyncWebServerRequest* request) {
|
||||
if (!request->hasParam("mode", true)) {
|
||||
request->send(400, "text/plain", "Missing mode parameter");
|
||||
return;
|
||||
}
|
||||
|
||||
String mode = request->getParam("mode", true)->value();
|
||||
LOG_INFO(TAG, "SettingsWebServer - Mode change requested: %s", mode.c_str());
|
||||
|
||||
if (mode == "ap") {
|
||||
// Switch to permanent AP mode
|
||||
_configManager.setPermanentAPMode(true);
|
||||
_configManager.saveNetworkConfig();
|
||||
LOG_INFO(TAG, "✅ Permanent AP mode enabled - will activate on reboot");
|
||||
request->send(200, "text/plain", "AP mode enabled. Device will reboot in 3 seconds.");
|
||||
|
||||
// Reboot after 3 seconds
|
||||
delay(3000);
|
||||
ESP.restart();
|
||||
|
||||
} else if (mode == "station") {
|
||||
// Switch to station mode (router mode)
|
||||
_configManager.setPermanentAPMode(false);
|
||||
_configManager.saveNetworkConfig();
|
||||
LOG_INFO(TAG, "✅ Station mode enabled - will activate on reboot");
|
||||
request->send(200, "text/plain", "Station mode enabled. Device will reboot in 3 seconds.");
|
||||
|
||||
// Reboot after 3 seconds
|
||||
delay(3000);
|
||||
ESP.restart();
|
||||
|
||||
} else {
|
||||
request->send(400, "text/plain", "Invalid mode. Use 'ap' or 'station'");
|
||||
}
|
||||
}
|
||||
|
||||
void SettingsWebServer::handleReboot(AsyncWebServerRequest* request) {
|
||||
LOG_INFO(TAG, "SettingsWebServer - Reboot requested");
|
||||
request->send(200, "text/plain", "Rebooting device in 2 seconds...");
|
||||
|
||||
delay(2000);
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
String SettingsWebServer::generateSettingsHTML() {
|
||||
bool isAPMode = _networking.isInAPMode();
|
||||
String currentIP = _networking.getLocalIP();
|
||||
String deviceUID = _configManager.getDeviceUID();
|
||||
String fwVersion = _configManager.getFwVersion();
|
||||
|
||||
// Load HTML template from PROGMEM
|
||||
String html = String(FPSTR(SETTINGS_PAGE_HTML));
|
||||
|
||||
// Replace placeholders with dynamic values
|
||||
html.replace("%MODE_BADGE_CLASS%", isAPMode ? "ap" : "station");
|
||||
html.replace("%MODE_TEXT%", isAPMode ? "AP Mode" : "Station Mode");
|
||||
html.replace("%CURRENT_IP%", currentIP);
|
||||
html.replace("%DEVICE_UID%", deviceUID);
|
||||
html.replace("%FW_VERSION%", fwVersion);
|
||||
html.replace("%AP_ACTIVE_CLASS%", isAPMode ? "active" : "");
|
||||
html.replace("%STATION_ACTIVE_CLASS%", !isAPMode ? "active" : "");
|
||||
html.replace("%SELECTED_MODE%", isAPMode ? "ap" : "station");
|
||||
|
||||
return html;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* SETTINGSWEBSERVER.HPP - Network Mode Settings Web Interface
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 🌐 SETTINGS WEB INTERFACE FOR VESPER 🌐
|
||||
*
|
||||
* Provides web interface for switching between AP and Station modes:
|
||||
* • Accessible at http://192.168.4.1/settings (AP mode)
|
||||
* • Accessible at http://{device-ip}/settings (Station mode)
|
||||
* • Toggle between AP mode and Router mode
|
||||
* • Configure WiFi credentials for router connection
|
||||
* • Reboot device with new settings
|
||||
*
|
||||
* 🏗️ ARCHITECTURE:
|
||||
* • Uses AsyncWebServer for non-blocking operation
|
||||
* • HTML interface with toggle switch
|
||||
* • Updates ConfigManager and triggers reboot
|
||||
* • Works in both AP and Station modes
|
||||
*
|
||||
* 📡 ENDPOINTS:
|
||||
* GET /settings - Settings page with mode toggle
|
||||
* POST /api/set-mode - Set network mode (AP or STA)
|
||||
* POST /api/reboot - Reboot device
|
||||
*
|
||||
* 📋 VERSION: 1.0
|
||||
* 📅 DATE: 2025-12-28
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <ESPAsyncWebServer.h>
|
||||
|
||||
// Forward declarations
|
||||
class ConfigManager;
|
||||
class Networking;
|
||||
|
||||
class SettingsWebServer {
|
||||
public:
|
||||
explicit SettingsWebServer(AsyncWebServer& server,
|
||||
ConfigManager& configManager,
|
||||
Networking& networking);
|
||||
~SettingsWebServer();
|
||||
|
||||
/**
|
||||
* @brief Initialize settings web server and register endpoints
|
||||
*/
|
||||
void begin();
|
||||
|
||||
private:
|
||||
// Dependencies
|
||||
AsyncWebServer& _server;
|
||||
ConfigManager& _configManager;
|
||||
Networking& _networking;
|
||||
|
||||
// Endpoint handlers
|
||||
void handleSettingsPage(AsyncWebServerRequest* request);
|
||||
void handleSetMode(AsyncWebServerRequest* request);
|
||||
void handleReboot(AsyncWebServerRequest* request);
|
||||
|
||||
// HTML generation
|
||||
String generateSettingsHTML();
|
||||
};
|
||||
@@ -0,0 +1,287 @@
|
||||
#include "Telemetry.hpp"
|
||||
|
||||
#define TAG "Telemetry"
|
||||
#include <ArduinoJson.h>
|
||||
|
||||
void Telemetry::begin() {
|
||||
// Initialize arrays
|
||||
for (uint8_t i = 0; i < 16; i++) {
|
||||
strikeCounters[i] = 0;
|
||||
bellLoad[i] = 0;
|
||||
bellMaxLoad[i] = 200; // Default max load
|
||||
}
|
||||
|
||||
coolingActive = false;
|
||||
|
||||
// Load strike counters from SD if available
|
||||
loadStrikeCounters();
|
||||
|
||||
// Create the telemetry task
|
||||
xTaskCreatePinnedToCore(telemetryTask, "TelemetryTask", 4096, this, 2, &telemetryTaskHandle, 1);
|
||||
|
||||
LOG_INFO(TAG, "Telemetry initialized");
|
||||
}
|
||||
|
||||
void Telemetry::setPlayerReference(bool* isPlayingPtr) {
|
||||
playerIsPlayingPtr = isPlayingPtr;
|
||||
LOG_DEBUG(TAG, "Player reference set");
|
||||
}
|
||||
|
||||
void Telemetry::setFileManager(FileManager* fm) {
|
||||
fileManager = fm;
|
||||
LOG_DEBUG(TAG, "FileManager reference set");
|
||||
}
|
||||
|
||||
void Telemetry::setForceStopCallback(void (*callback)()) {
|
||||
forceStopCallback = callback;
|
||||
LOG_DEBUG(TAG, "Force stop callback set");
|
||||
}
|
||||
|
||||
void Telemetry::recordBellStrike(uint8_t bellIndex) {
|
||||
if (bellIndex >= 16) {
|
||||
LOG_ERROR(TAG, "Invalid bell index: %d", bellIndex);
|
||||
return;
|
||||
}
|
||||
|
||||
// Critical section - matches your original code
|
||||
portENTER_CRITICAL(&telemetrySpinlock);
|
||||
strikeCounters[bellIndex]++; // Count strikes per bell (warranty)
|
||||
bellLoad[bellIndex]++; // Load per bell (heat simulation)
|
||||
coolingActive = true; // System needs cooling
|
||||
portEXIT_CRITICAL(&telemetrySpinlock);
|
||||
|
||||
}
|
||||
|
||||
uint32_t Telemetry::getStrikeCount(uint8_t bellIndex) {
|
||||
if (bellIndex >= 16) {
|
||||
LOG_ERROR(TAG, "Invalid bell index: %d", bellIndex);
|
||||
return 0;
|
||||
}
|
||||
return strikeCounters[bellIndex];
|
||||
}
|
||||
|
||||
void Telemetry::resetStrikeCounters() {
|
||||
portENTER_CRITICAL(&telemetrySpinlock);
|
||||
for (uint8_t i = 0; i < 16; i++) {
|
||||
strikeCounters[i] = 0;
|
||||
}
|
||||
portEXIT_CRITICAL(&telemetrySpinlock);
|
||||
|
||||
LOG_WARNING(TAG, "Strike counters reset by user");
|
||||
}
|
||||
|
||||
uint16_t Telemetry::getBellLoad(uint8_t bellIndex) {
|
||||
if (bellIndex >= 16) {
|
||||
LOG_ERROR(TAG, "Invalid bell index: %d", bellIndex);
|
||||
return 0;
|
||||
}
|
||||
return bellLoad[bellIndex];
|
||||
}
|
||||
|
||||
void Telemetry::setBellMaxLoad(uint8_t bellIndex, uint16_t maxLoad) {
|
||||
if (bellIndex >= 16) {
|
||||
LOG_ERROR(TAG, "Invalid bell index: %d", bellIndex);
|
||||
return;
|
||||
}
|
||||
|
||||
bellMaxLoad[bellIndex] = maxLoad;
|
||||
LOG_INFO(TAG, "Bell %d max load set to %d", bellIndex, maxLoad);
|
||||
}
|
||||
|
||||
bool Telemetry::isOverloaded(uint8_t bellIndex) {
|
||||
if (bellIndex >= 16) {
|
||||
LOG_ERROR(TAG, "Invalid bell index: %d", bellIndex);
|
||||
return false;
|
||||
}
|
||||
return bellLoad[bellIndex] > bellMaxLoad[bellIndex];
|
||||
}
|
||||
|
||||
bool Telemetry::isCoolingActive() {
|
||||
return coolingActive;
|
||||
}
|
||||
|
||||
void Telemetry::logTemperature(float temperature) {
|
||||
// Future implementation for temperature logging
|
||||
LOG_INFO(TAG, "Temperature: %.2f°C", temperature);
|
||||
}
|
||||
|
||||
void Telemetry::logVibration(float vibration) {
|
||||
// Future implementation for vibration logging
|
||||
LOG_INFO(TAG, "Vibration: %.2f", vibration);
|
||||
}
|
||||
|
||||
void Telemetry::checkBellLoads() {
|
||||
coolingActive = false; // Reset cooling flag
|
||||
|
||||
// Collect overloaded bells for batch notification
|
||||
std::vector<uint8_t> criticalBells;
|
||||
std::vector<uint16_t> criticalLoads;
|
||||
std::vector<uint8_t> warningBells;
|
||||
std::vector<uint16_t> warningLoads;
|
||||
|
||||
bool anyOverload = false;
|
||||
|
||||
for (uint8_t i = 0; i < 16; i++) {
|
||||
if (bellLoad[i] > 0) {
|
||||
bellLoad[i]--;
|
||||
coolingActive = true; // Still has heat left
|
||||
}
|
||||
|
||||
// Check for critical overload (90% of max load)
|
||||
uint16_t criticalThreshold = (bellMaxLoad[i] * 90) / 100;
|
||||
// Check for warning overload (60% of max load)
|
||||
uint16_t warningThreshold = (bellMaxLoad[i] * 60) / 100;
|
||||
|
||||
// Critical overload - protection kicks in
|
||||
if (bellLoad[i] > bellMaxLoad[i]) {
|
||||
LOG_ERROR(TAG, "Bell %d OVERLOADED! load=%d max=%d",
|
||||
i, bellLoad[i], bellMaxLoad[i]);
|
||||
|
||||
criticalBells.push_back(i);
|
||||
criticalLoads.push_back(bellLoad[i]);
|
||||
anyOverload = true;
|
||||
|
||||
} else if (bellLoad[i] > criticalThreshold) {
|
||||
// Critical warning - approaching overload
|
||||
LOG_WARNING(TAG, "Bell %d approaching overload! load=%d (critical threshold=%d)",
|
||||
i, bellLoad[i], criticalThreshold);
|
||||
|
||||
criticalBells.push_back(i);
|
||||
criticalLoads.push_back(bellLoad[i]);
|
||||
|
||||
} else if (bellLoad[i] > warningThreshold) {
|
||||
// Warning - moderate load
|
||||
LOG_INFO(TAG, "Bell %d moderate load warning! load=%d (warning threshold=%d)",
|
||||
i, bellLoad[i], warningThreshold);
|
||||
|
||||
warningBells.push_back(i);
|
||||
warningLoads.push_back(bellLoad[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// Note: Notifications now handled by BellEngine which has Communication reference
|
||||
// BellEngine monitors telemetry and sends notifications when overloads detected
|
||||
|
||||
// Trigger force stop if any bell is actually overloaded
|
||||
if (anyOverload && forceStopCallback != nullptr) {
|
||||
forceStopCallback();
|
||||
}
|
||||
}
|
||||
|
||||
void Telemetry::telemetryTask(void* parameter) {
|
||||
Telemetry* telemetry = static_cast<Telemetry*>(parameter);
|
||||
|
||||
LOG_INFO(TAG, "Telemetry task started");
|
||||
|
||||
while(1) {
|
||||
// Skip processing if paused (OTA freeze mode)
|
||||
if (!telemetry->isPaused) {
|
||||
// Only run if player is playing OR we're still cooling
|
||||
bool isPlaying = (telemetry->playerIsPlayingPtr != nullptr) ?
|
||||
*(telemetry->playerIsPlayingPtr) : false;
|
||||
|
||||
if (isPlaying || telemetry->coolingActive) {
|
||||
telemetry->checkBellLoads();
|
||||
}
|
||||
}
|
||||
|
||||
vTaskDelay(pdMS_TO_TICKS(1000)); // Run every 1s
|
||||
}
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// STRIKE COUNTER PERSISTENCE
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void Telemetry::saveStrikeCounters() {
|
||||
if (!fileManager) {
|
||||
LOG_WARNING(TAG, "Cannot save strike counters: FileManager not set");
|
||||
return;
|
||||
}
|
||||
|
||||
StaticJsonDocument<512> doc;
|
||||
JsonArray counters = doc.createNestedArray("strikeCounters");
|
||||
|
||||
// Thread-safe read of strike counters
|
||||
portENTER_CRITICAL(&telemetrySpinlock);
|
||||
for (uint8_t i = 0; i < 16; i++) {
|
||||
counters.add(strikeCounters[i]);
|
||||
}
|
||||
portEXIT_CRITICAL(&telemetrySpinlock);
|
||||
|
||||
if (fileManager->writeJsonFile("/telemetry_data.json", doc)) {
|
||||
LOG_INFO(TAG, "Strike counters saved to SD card");
|
||||
} else {
|
||||
LOG_ERROR(TAG, "Failed to save strike counters to SD card");
|
||||
}
|
||||
}
|
||||
|
||||
void Telemetry::loadStrikeCounters() {
|
||||
if (!fileManager) {
|
||||
LOG_WARNING(TAG, "Cannot load strike counters: FileManager not set");
|
||||
return;
|
||||
}
|
||||
|
||||
StaticJsonDocument<512> doc;
|
||||
|
||||
if (!fileManager->readJsonFile("/telemetry_data.json", doc)) {
|
||||
LOG_INFO(TAG, "No previous strike counter data found, starting fresh");
|
||||
return;
|
||||
}
|
||||
|
||||
JsonArray counters = doc["strikeCounters"];
|
||||
if (counters.isNull()) {
|
||||
LOG_WARNING(TAG, "Invalid telemetry data format");
|
||||
return;
|
||||
}
|
||||
|
||||
// Thread-safe write of strike counters
|
||||
portENTER_CRITICAL(&telemetrySpinlock);
|
||||
for (uint8_t i = 0; i < 16 && i < counters.size(); i++) {
|
||||
strikeCounters[i] = counters[i].as<uint32_t>();
|
||||
}
|
||||
portEXIT_CRITICAL(&telemetrySpinlock);
|
||||
|
||||
LOG_INFO(TAG, "Strike counters loaded from SD card");
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// HEALTH CHECK IMPLEMENTATION
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
bool Telemetry::isHealthy() const {
|
||||
// Check if telemetry task is created and running
|
||||
if (telemetryTaskHandle == NULL) {
|
||||
LOG_DEBUG(TAG, "Telemetry: Unhealthy - Task not created");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if task is still alive
|
||||
eTaskState taskState = eTaskGetState(telemetryTaskHandle);
|
||||
if (taskState == eDeleted || taskState == eInvalid) {
|
||||
LOG_DEBUG(TAG, "Telemetry: Unhealthy - Task deleted or invalid");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if player reference is set
|
||||
if (playerIsPlayingPtr == nullptr) {
|
||||
LOG_DEBUG(TAG, "Telemetry: Unhealthy - Player reference not set");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check for any critical overloads that would indicate system stress
|
||||
bool hasCriticalOverload = false;
|
||||
for (uint8_t i = 0; i < 16; i++) {
|
||||
if (bellLoad[i] > bellMaxLoad[i]) {
|
||||
hasCriticalOverload = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (hasCriticalOverload) {
|
||||
LOG_DEBUG(TAG, "Telemetry: Unhealthy - Critical bell overload detected");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* 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"
|
||||
|
||||
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
|
||||
|
||||
// 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
|
||||
|
||||
// Persistence methods
|
||||
void saveStrikeCounters();
|
||||
void loadStrikeCounters();
|
||||
|
||||
// Bell load management
|
||||
uint16_t getBellLoad(uint8_t bellIndex);
|
||||
void setBellMaxLoad(uint8_t bellIndex, uint16_t maxLoad);
|
||||
bool isOverloaded(uint8_t bellIndex);
|
||||
bool isCoolingActive(); // Check if system needs cooling
|
||||
|
||||
// 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; }
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// HEALTH CHECK METHOD
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/** @brief Check if Telemetry is in healthy state */
|
||||
bool isHealthy() const;
|
||||
|
||||
// Static task function
|
||||
static void telemetryTask(void* parameter);
|
||||
|
||||
private:
|
||||
void (*forceStopCallback)() = nullptr;
|
||||
void checkBellLoads();
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,825 @@
|
||||
#include "TimeKeeper.hpp"
|
||||
|
||||
#define TAG "TimeKeeper"
|
||||
#include "../OutputManager/OutputManager.hpp"
|
||||
#include "../ConfigManager/ConfigManager.hpp"
|
||||
#include "../Networking/Networking.hpp"
|
||||
#include "../Player/Player.hpp" // 🔥 Include for Player class definition
|
||||
#include "SD.h"
|
||||
#include <time.h>
|
||||
|
||||
void Timekeeper::begin() {
|
||||
LOG_INFO(TAG, "Timekeeper initialized - clock outputs managed by ConfigManager");
|
||||
|
||||
// Initialize RTC
|
||||
if (!rtc.begin()) {
|
||||
LOG_ERROR(TAG, "Couldn't find RTC");
|
||||
// Continue anyway, but log the error
|
||||
} else {
|
||||
LOG_INFO(TAG, "RTC initialized successfully");
|
||||
|
||||
// Check if RTC lost power
|
||||
if (!rtc.isrunning()) {
|
||||
LOG_WARNING(TAG, "RTC is NOT running! Setting time...");
|
||||
// Set to compile time as fallback
|
||||
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
|
||||
}
|
||||
}
|
||||
|
||||
// Load today's events
|
||||
loadTodaysEvents();
|
||||
|
||||
// Create SINGLE consolidated task (saves 8KB RAM!)
|
||||
xTaskCreatePinnedToCore(mainTimekeeperTask, "TimeKeeper", 4096, this, 2, &mainTaskHandle, 1);
|
||||
|
||||
LOG_INFO(TAG, "TimeKeeper initialized with SIMPLE sync approach (like your Arduino code)");
|
||||
}
|
||||
|
||||
void Timekeeper::setOutputManager(OutputManager* outputManager) {
|
||||
_outputManager = outputManager;
|
||||
LOG_INFO(TAG, "Timekeeper connected to OutputManager - CLEAN ARCHITECTURE!");
|
||||
}
|
||||
|
||||
void Timekeeper::setConfigManager(ConfigManager* configManager) {
|
||||
_configManager = configManager;
|
||||
LOG_INFO(TAG, "Timekeeper connected to ConfigManager");
|
||||
}
|
||||
|
||||
void Timekeeper::setNetworking(Networking* networking) {
|
||||
_networking = networking;
|
||||
LOG_INFO(TAG, "Timekeeper connected to Networking");
|
||||
}
|
||||
|
||||
void Timekeeper::setPlayer(Player* player) {
|
||||
_player = player;
|
||||
LOG_INFO(TAG, "Timekeeper connected to Player for playback coordination");
|
||||
}
|
||||
|
||||
void Timekeeper::interruptActiveAlert() {
|
||||
if (alertInProgress.load()) {
|
||||
LOG_INFO(TAG, "⚡ ALERT INTERRUPTED by user playback - marking as complete");
|
||||
alertInProgress.store(false);
|
||||
// Alert will stop naturally on next check in fireAlertBell loop
|
||||
}
|
||||
}
|
||||
|
||||
void Timekeeper::setRelayWriteFunction(void (*func)(int, int)) {
|
||||
relayWriteFunc = func;
|
||||
LOG_WARNING(TAG, "Using LEGACY relay function - consider upgrading to OutputManager");
|
||||
}
|
||||
|
||||
void Timekeeper::setClockOutputs(int relay1, int relay2) {
|
||||
LOG_WARNING(TAG, "⚠️ setClockOutputs() is DEPRECATED! Use ConfigManager.setClockOutput1/2() instead");
|
||||
LOG_WARNING(TAG, "⚠️ Clock outputs should be configured via MQTT/WebSocket commands");
|
||||
|
||||
// For backward compatibility, still set the config if ConfigManager is available
|
||||
if (_configManager) {
|
||||
_configManager->setClockOutput1(relay1);
|
||||
_configManager->setClockOutput2(relay2);
|
||||
LOG_INFO(TAG, "Clock outputs updated via legacy method: C1=%d, C2=%d", relay1, relay2);
|
||||
} else {
|
||||
LOG_ERROR(TAG, "ConfigManager not available - cannot set clock outputs");
|
||||
}
|
||||
}
|
||||
|
||||
void Timekeeper::setTime(unsigned long timestamp) {
|
||||
if (!rtc.begin()) {
|
||||
LOG_ERROR(TAG, "RTC not available - cannot set time");
|
||||
return;
|
||||
}
|
||||
|
||||
// Get timezone configuration
|
||||
auto& timeConfig = _configManager->getTimeConfig();
|
||||
|
||||
// Apply timezone offset to UTC timestamp
|
||||
long totalOffset = timeConfig.gmtOffsetSec + timeConfig.daylightOffsetSec;
|
||||
unsigned long localTimestamp = timestamp + totalOffset;
|
||||
|
||||
// Convert local timestamp to DateTime object
|
||||
DateTime newTime(localTimestamp);
|
||||
|
||||
// Set the RTC with local time
|
||||
rtc.adjust(newTime);
|
||||
|
||||
LOG_INFO(TAG, "RTC time set to LOCAL: %04d-%02d-%02d %02d:%02d:%02d (UTC timestamp: %lu + %ld offset = %lu)",
|
||||
newTime.year(), newTime.month(), newTime.day(),
|
||||
newTime.hour(), newTime.minute(), newTime.second(),
|
||||
timestamp, totalOffset, localTimestamp);
|
||||
|
||||
// Reload today's events since the date might have changed
|
||||
loadTodaysEvents();
|
||||
}
|
||||
|
||||
void Timekeeper::setTimeWithLocalTimestamp(unsigned long localTimestamp) {
|
||||
if (!rtc.begin()) {
|
||||
LOG_ERROR(TAG, "RTC not available - cannot set time");
|
||||
return;
|
||||
}
|
||||
|
||||
// Convert local timestamp directly to DateTime object (no timezone conversion needed)
|
||||
DateTime newTime(localTimestamp);
|
||||
|
||||
// Set the RTC with local time
|
||||
rtc.adjust(newTime);
|
||||
|
||||
LOG_INFO(TAG, "RTC time set to LOCAL: %04d-%02d-%02d %02d:%02d:%02d (local timestamp: %lu)",
|
||||
newTime.year(), newTime.month(), newTime.day(),
|
||||
newTime.hour(), newTime.minute(), newTime.second(),
|
||||
localTimestamp);
|
||||
|
||||
// Reload today's events since the date might have changed
|
||||
loadTodaysEvents();
|
||||
}
|
||||
|
||||
unsigned long Timekeeper::getTime() {
|
||||
if (!rtc.isrunning()) {
|
||||
LOG_ERROR(TAG, "RTC not running - cannot get time");
|
||||
return 0;
|
||||
}
|
||||
|
||||
DateTime now = rtc.now();
|
||||
unsigned long timestamp = now.unixtime();
|
||||
|
||||
LOG_DEBUG(TAG, "Current RTC time: %04d-%02d-%02d %02d:%02d:%02d (timestamp: %lu)",
|
||||
now.year(), now.month(), now.day(),
|
||||
now.hour(), now.minute(), now.second(),
|
||||
timestamp);
|
||||
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
void Timekeeper::syncTimeWithNTP() {
|
||||
// Check if we have network connection and required dependencies
|
||||
if (!_networking || !_configManager) {
|
||||
LOG_WARNING(TAG, "Cannot sync time: Networking or ConfigManager not set - using RTC time");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_networking->isConnected()) {
|
||||
LOG_INFO(TAG, "No network connection - skipping NTP sync, using RTC time");
|
||||
return;
|
||||
}
|
||||
|
||||
LOG_INFO(TAG, "⏰ Starting non-blocking NTP sync...");
|
||||
|
||||
// Get config from ConfigManager
|
||||
auto& timeConfig = _configManager->getTimeConfig();
|
||||
|
||||
// Configure NTP with settings from config
|
||||
configTime(timeConfig.gmtOffsetSec, timeConfig.daylightOffsetSec, timeConfig.ntpServer.c_str());
|
||||
|
||||
// 🔥 NON-BLOCKING: Try to get time with reasonable timeout for network response
|
||||
struct tm timeInfo;
|
||||
if (getLocalTime(&timeInfo, 5000)) { // 5 second timeout for NTP response
|
||||
// Success! Update RTC with synchronized time
|
||||
rtc.adjust(DateTime(timeInfo.tm_year + 1900, timeInfo.tm_mon + 1, timeInfo.tm_mday,
|
||||
timeInfo.tm_hour, timeInfo.tm_min, timeInfo.tm_sec));
|
||||
|
||||
LOG_INFO(TAG, "✅ NTP sync successful: %04d-%02d-%02d %02d:%02d:%02d",
|
||||
timeInfo.tm_year + 1900, timeInfo.tm_mon + 1, timeInfo.tm_mday,
|
||||
timeInfo.tm_hour, timeInfo.tm_min, timeInfo.tm_sec);
|
||||
|
||||
// Reload today's events since the time might have changed significantly
|
||||
loadTodaysEvents();
|
||||
} else {
|
||||
// No internet or NTP server unreachable - this is NORMAL for local networks
|
||||
LOG_INFO(TAG, "⚠️ NTP sync skipped (no internet) - using RTC time. This is normal for local networks.");
|
||||
}
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// CONSOLIDATED TimeKeeper Task - SIMPLE approach like your Arduino code
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void Timekeeper::mainTimekeeperTask(void* parameter) {
|
||||
Timekeeper* keeper = static_cast<Timekeeper*>(parameter);
|
||||
LOG_INFO(TAG, "🕒 SIMPLE TimeKeeper task started - based on your Arduino code approach");
|
||||
|
||||
unsigned long lastRtcCheck = 0;
|
||||
unsigned long lastScheduleCheck = 0;
|
||||
|
||||
while (true) {
|
||||
unsigned long now = millis();
|
||||
|
||||
// 🕐 SIMPLE PHYSICAL CLOCK SYNC (check every loop, fire if needed - your Arduino approach)
|
||||
keeper->checkAndSyncPhysicalClock();
|
||||
|
||||
// 🔔 ALERT MANAGEMENT (every second for precise timing)
|
||||
keeper->checkClockAlerts();
|
||||
|
||||
// 💡 BACKLIGHT AUTOMATION (every 10 seconds)
|
||||
if (now - lastRtcCheck >= 10000) {
|
||||
keeper->checkBacklightAutomation();
|
||||
}
|
||||
|
||||
// 📅 SCHEDULE CHECK (every second)
|
||||
if (now - lastScheduleCheck >= 1000) {
|
||||
keeper->checkScheduledEvents();
|
||||
lastScheduleCheck = now;
|
||||
}
|
||||
|
||||
// 🔧 RTC MAINTENANCE (every 10 seconds)
|
||||
if (now - lastRtcCheck >= 10000) {
|
||||
// RTC health check
|
||||
DateTime rtcNow = keeper->rtc.now();
|
||||
if (keeper->rtc.isrunning()) {
|
||||
// Check for midnight - reload events for new day
|
||||
if (rtcNow.hour() == 0 && rtcNow.minute() == 0 && rtcNow.second() < 10) {
|
||||
LOG_INFO(TAG, "🌙 Midnight detected - reloading events");
|
||||
keeper->loadTodaysEvents();
|
||||
keeper->loadNextDayEvents();
|
||||
}
|
||||
|
||||
// Hourly maintenance
|
||||
if (rtcNow.minute() == 0 && rtcNow.second() < 10) {
|
||||
LOG_DEBUG(TAG, "🕐 Hourly check at %02d:00", rtcNow.hour());
|
||||
}
|
||||
} else {
|
||||
static uint8_t rtcWarningCounter = 0;
|
||||
if (rtcWarningCounter++ % 6 == 0) { // Log every minute
|
||||
LOG_WARNING(TAG, "⚠️ RTC not running!");
|
||||
}
|
||||
}
|
||||
lastRtcCheck = now;
|
||||
}
|
||||
|
||||
vTaskDelay(pdMS_TO_TICKS(1000));
|
||||
}
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// SIMPLE CLOCK SYNC IMPLEMENTATION - Based on your Arduino code
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void Timekeeper::checkAndSyncPhysicalClock() {
|
||||
// Check if clock is enabled in config
|
||||
if (!_configManager || !_configManager->getClockEnabled()) {
|
||||
return; // Clock is disabled - skip all clock functionality
|
||||
}
|
||||
|
||||
// Check if there is any Time Difference between the Physical Clock and the Actual Time and if yes, run the Motor
|
||||
|
||||
if (!_outputManager || !rtc.isrunning() || clockUpdatesPaused) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get current real time (your updateCurrentTime() equivalent)
|
||||
DateTime now = rtc.now();
|
||||
int8_t realHour = now.hour() % 12; // Convert to 12-hour format for clock face
|
||||
if (realHour == 0) realHour = 12; // 12 AM/PM shows as 12, not 0
|
||||
int8_t realMinute = now.minute();
|
||||
|
||||
// Get physical clock state (your clock.hour/clock.minute equivalent)
|
||||
int8_t physicalHour = _configManager->getPhysicalClockHour();
|
||||
int8_t physicalMinute = _configManager->getPhysicalClockMinute();
|
||||
|
||||
// Calculate time difference (your exact logic!)
|
||||
int16_t timeDifference = (realHour * 60 + realMinute) - (physicalHour * 60 + physicalMinute);
|
||||
|
||||
LOG_VERBOSE(TAG, "⏰ CHECK: Real time %02d:%02d vs Physical %02d:%02d - DIFF: %d mins",
|
||||
realHour, realMinute, physicalHour, physicalMinute, timeDifference);
|
||||
|
||||
// Handle 12-hour rollover (if negative, add 12 hours)
|
||||
if (timeDifference < 0) {
|
||||
timeDifference += 12 * 60; // Add 12 hours to handle rollover
|
||||
LOG_VERBOSE(TAG, "⏰ DIFF: Adjusted for rollover, new difference %d minutes", timeDifference);
|
||||
}
|
||||
|
||||
// If there's a difference, advance the clock by one minute (your runMotor equivalent)
|
||||
if (timeDifference >= 1) {
|
||||
advancePhysicalClockOneMinute();
|
||||
LOG_DEBUG(TAG, "⏰ SYNC: Advanced physical clock by 1 minute to %02d:%02d (real: %02d:%02d, diff: %lu mins)",
|
||||
_configManager->getPhysicalClockHour(), _configManager->getPhysicalClockMinute(),
|
||||
realHour, realMinute, timeDifference);
|
||||
}
|
||||
}
|
||||
|
||||
void Timekeeper::advancePhysicalClockOneMinute() {
|
||||
|
||||
const auto& clockConfig = _configManager->getClockConfig();
|
||||
if (clockConfig.c1output == 255 || clockConfig.c2output == 255) {
|
||||
return;
|
||||
}
|
||||
|
||||
bool useC1 = _configManager->getNextOutputIsC1();
|
||||
uint8_t outputToFire = useC1 ? (clockConfig.c1output - 1) : (clockConfig.c2output - 1);
|
||||
|
||||
LOG_DEBUG(TAG, "🔥 ADVANCE: Firing %s (output %d) for %dms",
|
||||
useC1 ? "C1" : "C2", outputToFire + 1, clockConfig.pulseDuration);
|
||||
|
||||
_outputManager->fireOutputForDuration(outputToFire, clockConfig.pulseDuration);
|
||||
vTaskDelay(pdMS_TO_TICKS(clockConfig.pulseDuration + clockConfig.pauseDuration)); // cool-off motor
|
||||
_configManager->setNextOutputIsC1(!useC1);
|
||||
updatePhysicalClockTime();
|
||||
}
|
||||
|
||||
void Timekeeper::updatePhysicalClockTime() {
|
||||
|
||||
uint8_t currentHour = _configManager->getPhysicalClockHour();
|
||||
uint8_t currentMinute = _configManager->getPhysicalClockMinute();
|
||||
|
||||
currentMinute++;
|
||||
if (currentMinute >= 60) {
|
||||
currentMinute = 0;
|
||||
currentHour++;
|
||||
if (currentHour > 12) { // 12-hour clock (your code used 24, but clock face is 12)
|
||||
currentHour = 1;
|
||||
}
|
||||
}
|
||||
|
||||
_configManager->setPhysicalClockHour(currentHour);
|
||||
_configManager->setPhysicalClockMinute(currentMinute);
|
||||
_configManager->setLastSyncTime(millis() / 1000);
|
||||
_configManager->saveClockState();
|
||||
|
||||
LOG_DEBUG(TAG, "📅 STATE: Physical clock advanced to %d:%02d", currentHour, currentMinute);
|
||||
}
|
||||
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// EVENT MANAGEMENT
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void Timekeeper::loadTodaysEvents() {
|
||||
// Clear existing events
|
||||
todaysEvents.clear();
|
||||
|
||||
// Get current date/time from RTC
|
||||
DateTime now = rtc.now();
|
||||
if (!rtc.isrunning()) {
|
||||
LOG_ERROR(TAG, "RTC not running - cannot load events");
|
||||
return;
|
||||
}
|
||||
|
||||
int currentYear = now.year();
|
||||
int currentMonth = now.month();
|
||||
int currentDay = now.day();
|
||||
int currentDayOfWeek = now.dayOfTheWeek(); // 0=Sunday, 1=Monday, etc.
|
||||
|
||||
LOG_INFO(TAG, "Loading events for: %04d-%02d-%02d (day %d)",
|
||||
currentYear, currentMonth, currentDay, currentDayOfWeek);
|
||||
|
||||
// Open and parse events file
|
||||
File file = SD.open("/events/events.json");
|
||||
if (!file) {
|
||||
LOG_ERROR(TAG, "Failed to open events.json");
|
||||
return;
|
||||
}
|
||||
|
||||
// Use static allocation instead of dynamic to avoid heap fragmentation
|
||||
static StaticJsonDocument<8192> doc;
|
||||
doc.clear();
|
||||
|
||||
DeserializationError error = deserializeJson(doc, file);
|
||||
file.close();
|
||||
|
||||
if (error) {
|
||||
LOG_ERROR(TAG, "JSON parsing failed: %s", error.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
JsonArray events = doc["events"];
|
||||
int eventsLoaded = 0;
|
||||
|
||||
for (JsonObject event : events) {
|
||||
if (!event["enabled"].as<bool>()) {
|
||||
continue; // Skip disabled events
|
||||
}
|
||||
|
||||
String type = event["type"].as<String>();
|
||||
bool shouldAdd = false;
|
||||
|
||||
if (type == "single") {
|
||||
// Check if event date matches today
|
||||
String eventDateTime = event["datetime"].as<String>();
|
||||
if (isSameDate(eventDateTime, currentYear, currentMonth, currentDay)) {
|
||||
shouldAdd = true;
|
||||
}
|
||||
}
|
||||
else if (type == "weekly") {
|
||||
// Check if today's day of week is in the event's days
|
||||
JsonArray daysOfWeek = event["days_of_week"];
|
||||
for (JsonVariant dayVar : daysOfWeek) {
|
||||
int day = dayVar.as<int>();
|
||||
if (day == currentDayOfWeek) {
|
||||
shouldAdd = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (type == "monthly") {
|
||||
// Check if today's date is in the event's days of month
|
||||
JsonArray daysOfMonth = event["days_of_month"];
|
||||
for (JsonVariant dayVar : daysOfMonth) {
|
||||
int day = dayVar.as<int>();
|
||||
if (day == currentDay) {
|
||||
shouldAdd = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldAdd) {
|
||||
addToTodaysSchedule(event);
|
||||
eventsLoaded++;
|
||||
}
|
||||
}
|
||||
|
||||
// Sort events by time
|
||||
sortEventsByTime();
|
||||
|
||||
LOG_INFO(TAG, "Loaded %d events for today", eventsLoaded);
|
||||
}
|
||||
|
||||
bool Timekeeper::isSameDate(String eventDateTime, int year, int month, int day) {
|
||||
// Parse "2025-12-25T09:00:00" format
|
||||
if (eventDateTime.length() < 10) return false;
|
||||
|
||||
int eventYear = eventDateTime.substring(0, 4).toInt();
|
||||
int eventMonth = eventDateTime.substring(5, 7).toInt();
|
||||
int eventDay = eventDateTime.substring(8, 10).toInt();
|
||||
|
||||
return (eventYear == year && eventMonth == month && eventDay == day);
|
||||
}
|
||||
|
||||
void Timekeeper::addToTodaysSchedule(JsonObject event) {
|
||||
ScheduledEvent schedEvent;
|
||||
|
||||
// Extract time based on event type
|
||||
if (event["type"] == "single") {
|
||||
// Extract time from datetime: "2025-12-25T09:00:00" -> "09:00:00"
|
||||
String datetime = event["datetime"].as<String>();
|
||||
if (datetime.length() >= 19) {
|
||||
schedEvent.timeStr = datetime.substring(11, 19);
|
||||
}
|
||||
} else {
|
||||
// Weekly/Monthly events have separate time field
|
||||
schedEvent.timeStr = event["time"].as<String>();
|
||||
}
|
||||
|
||||
// Store the entire event data (create a copy)
|
||||
schedEvent.eventData = event;
|
||||
|
||||
todaysEvents.push_back(schedEvent);
|
||||
|
||||
LOG_DEBUG(TAG, "Added event '%s' at %s",
|
||||
event["name"].as<String>().c_str(),
|
||||
schedEvent.timeStr.c_str());
|
||||
}
|
||||
|
||||
void Timekeeper::sortEventsByTime() {
|
||||
std::sort(todaysEvents.begin(), todaysEvents.end(),
|
||||
[](const ScheduledEvent& a, const ScheduledEvent& b) {
|
||||
return a.timeStr < b.timeStr;
|
||||
});
|
||||
}
|
||||
|
||||
String Timekeeper::getCurrentTimeString() {
|
||||
DateTime now = rtc.now();
|
||||
if (!rtc.isrunning()) {
|
||||
return "00:00:00";
|
||||
}
|
||||
|
||||
char timeStr[9];
|
||||
sprintf(timeStr, "%02d:%02d:%02d", now.hour(), now.minute(), now.second());
|
||||
return String(timeStr);
|
||||
}
|
||||
|
||||
void Timekeeper::checkScheduledEvents() {
|
||||
String currentTime = getCurrentTimeString();
|
||||
|
||||
// Only check the seconds part for exact matching
|
||||
String currentTimeMinute = currentTime.substring(0, 5); // "HH:MM"
|
||||
|
||||
for (auto& event : todaysEvents) {
|
||||
String eventTimeMinute = event.timeStr.substring(0, 5); // "HH:MM"
|
||||
|
||||
if (eventTimeMinute == currentTimeMinute) {
|
||||
// Check if we haven't already triggered this event
|
||||
if (!event.triggered) {
|
||||
triggerEvent(event);
|
||||
event.triggered = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Reset trigger flag when we're past the minute
|
||||
if (eventTimeMinute < currentTimeMinute) {
|
||||
event.triggered = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Timekeeper::triggerEvent(ScheduledEvent& event) {
|
||||
JsonObject eventData = event.eventData;
|
||||
|
||||
LOG_INFO(TAG, "TRIGGERING EVENT: %s at %s",
|
||||
eventData["name"].as<String>().c_str(),
|
||||
event.timeStr.c_str());
|
||||
|
||||
// Here you would trigger your melody playback
|
||||
// You might want to call a function from your main program
|
||||
// or send a message to another task
|
||||
|
||||
// Example of what you might do:
|
||||
JsonObject melody = eventData["melody"];
|
||||
String melodyUID = melody["uid"].as<String>();
|
||||
String melodyName = melody["name"].as<String>();
|
||||
|
||||
LOG_INFO(TAG, "Playing melody: %s (UID: %s)",
|
||||
melodyName.c_str(), melodyUID.c_str());
|
||||
|
||||
// TODO: Add your melody trigger code here
|
||||
// playMelody(melody);
|
||||
}
|
||||
|
||||
void Timekeeper::loadNextDayEvents() {
|
||||
// This function would load tomorrow's events for smooth midnight transition
|
||||
// Implementation similar to loadTodaysEvents() but for tomorrow's date
|
||||
LOG_DEBUG(TAG, "Pre-loading tomorrow's events...");
|
||||
// TODO: Implement if needed for smoother transitions
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// CLOCK ALERTS IMPLEMENTATION
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void Timekeeper::checkClockAlerts() {
|
||||
// Check if clock is enabled in config
|
||||
if (!_configManager || !_configManager->getClockEnabled()) {
|
||||
return; // Clock is disabled - skip all alert functionality
|
||||
}
|
||||
|
||||
// Check if we have required dependencies
|
||||
if (!_outputManager || !rtc.isrunning()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 🔥 CRITICAL: Check if Player is busy - if so, SKIP alert completely
|
||||
if (_player && _player->isPlaying) {
|
||||
// Player is active (playing, paused, stopping, etc.) - skip alert entirely
|
||||
// Mark this alert as processed to prevent it from firing when playback ends
|
||||
DateTime now = rtc.now();
|
||||
int currentMinute = now.minute();
|
||||
|
||||
if (currentMinute == 0) {
|
||||
lastHour = now.hour(); // Mark hour as processed
|
||||
} else if (currentMinute == 30) {
|
||||
lastMinute = 30; // Mark half-hour as processed
|
||||
} else if (currentMinute == 15 || currentMinute == 45) {
|
||||
lastMinute = currentMinute; // Mark quarter-hour as processed
|
||||
}
|
||||
|
||||
LOG_DEBUG(TAG, "⏭️ SKIPPING clock alert - Player is busy (playing/paused)");
|
||||
return;
|
||||
}
|
||||
|
||||
// Get current time
|
||||
DateTime now = rtc.now();
|
||||
int currentHour = now.hour();
|
||||
int currentMinute = now.minute();
|
||||
int currentSecond = now.second();
|
||||
|
||||
// Only trigger alerts in first 30 seconds of the minute
|
||||
// The lastHour/lastMinute tracking prevents duplicate triggers
|
||||
if (currentSecond > 30) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get clock configuration
|
||||
const auto& clockConfig = _configManager->getClockConfig();
|
||||
|
||||
// Check if alerts are disabled
|
||||
if (clockConfig.alertType == "OFF") {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if we're in a silence period
|
||||
if (isInSilencePeriod()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 🕐 HOURLY ALERTS (at xx:00)
|
||||
if (currentMinute == 0 && currentHour != lastHour) {
|
||||
triggerHourlyAlert(currentHour);
|
||||
lastHour = currentHour;
|
||||
}
|
||||
|
||||
// 🕕 HALF-HOUR ALERTS (at xx:30)
|
||||
if (currentMinute == 30 && lastMinute != 30) {
|
||||
if (clockConfig.halfBell != 255) { // 255 = disabled
|
||||
LOG_INFO(TAG, "🕕 Half-hour alert at %02d:30", currentHour);
|
||||
fireAlertBell(clockConfig.halfBell, 1);
|
||||
}
|
||||
lastMinute = 30;
|
||||
}
|
||||
|
||||
// 🕒 QUARTER-HOUR ALERTS (at xx:15 and xx:45)
|
||||
if ((currentMinute == 15 || currentMinute == 45) && lastMinute != currentMinute) {
|
||||
if (clockConfig.quarterBell != 255) { // 255 = disabled
|
||||
LOG_INFO(TAG, "🕒 Quarter-hour alert at %02d:%02d", currentHour, currentMinute);
|
||||
fireAlertBell(clockConfig.quarterBell, 1);
|
||||
}
|
||||
lastMinute = currentMinute;
|
||||
}
|
||||
|
||||
// Reset minute tracking for other minutes
|
||||
if (currentMinute != 0 && currentMinute != 15 && currentMinute != 30 && currentMinute != 45) {
|
||||
if (lastMinute != currentMinute) {
|
||||
lastMinute = currentMinute;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Timekeeper::triggerHourlyAlert(int hour) {
|
||||
const auto& clockConfig = _configManager->getClockConfig();
|
||||
|
||||
// Check if hourly bell is configured
|
||||
if (clockConfig.hourBell == 255) { // 255 = disabled
|
||||
return;
|
||||
}
|
||||
|
||||
if (clockConfig.alertType == "SINGLE") {
|
||||
// Single ding for any hour
|
||||
LOG_INFO(TAG, "🕐 Hourly alert (SINGLE) at %02d:00", hour);
|
||||
fireAlertBell(clockConfig.hourBell, 1);
|
||||
}
|
||||
else if (clockConfig.alertType == "HOURS") {
|
||||
// Ring the number of times equal to the hour (1-12)
|
||||
int bellCount = hour;
|
||||
if (bellCount == 0) bellCount = 12; // Midnight = 12 bells
|
||||
if (bellCount > 12) bellCount = bellCount - 12; // 24h to 12h conversion
|
||||
|
||||
LOG_INFO(TAG, "🕐 Hourly alert (HOURS) at %02d:00 - %d rings", hour, bellCount);
|
||||
fireAlertBell(clockConfig.hourBell, bellCount);
|
||||
}
|
||||
}
|
||||
|
||||
void Timekeeper::fireAlertBell(uint8_t bellNumber, int count) {
|
||||
if (!_outputManager || bellNumber == 255) {
|
||||
return;
|
||||
}
|
||||
|
||||
const auto& clockConfig = _configManager->getClockConfig();
|
||||
|
||||
// Mark alert as in progress
|
||||
alertInProgress.store(true);
|
||||
|
||||
for (int i = 0; i < count; i++) {
|
||||
// 🔥 Check for interruption by user playback
|
||||
if (!alertInProgress.load()) {
|
||||
LOG_INFO(TAG, "⚡ Alert interrupted at ring %d/%d - stopping immediately", i + 1, count);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get bell duration from bell configuration
|
||||
uint16_t bellDuration = _configManager->getBellDuration(bellNumber);
|
||||
|
||||
LOG_DEBUG(TAG, "🔔 Alert bell #%d ring %d/%d (duration: %dms)",
|
||||
bellNumber + 1, i + 1, count, bellDuration);
|
||||
|
||||
// Fire the bell using OutputManager
|
||||
_outputManager->fireOutputForDuration(bellNumber, bellDuration);
|
||||
|
||||
// Wait between rings (only if there's more than one ring)
|
||||
if (i < count - 1) {
|
||||
vTaskDelay(pdMS_TO_TICKS(clockConfig.alertRingInterval));
|
||||
}
|
||||
}
|
||||
|
||||
// Mark alert as complete
|
||||
alertInProgress.store(false);
|
||||
}
|
||||
|
||||
void Timekeeper::checkBacklightAutomation() {
|
||||
// Check if clock is enabled in config
|
||||
if (!_configManager || !_configManager->getClockEnabled()) {
|
||||
return; // Clock is disabled - skip all backlight functionality
|
||||
}
|
||||
|
||||
// Check if we have required dependencies
|
||||
if (!_outputManager || !rtc.isrunning()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const auto& clockConfig = _configManager->getClockConfig();
|
||||
|
||||
// Check if backlight automation is enabled
|
||||
if (!clockConfig.backlight || clockConfig.backlightOutput == 255) {
|
||||
return; // Backlight automation disabled
|
||||
}
|
||||
|
||||
// Get current time
|
||||
DateTime now = rtc.now();
|
||||
char currentTimeStr[6];
|
||||
sprintf(currentTimeStr, "%02d:%02d", now.hour(), now.minute());
|
||||
String currentTime = String(currentTimeStr);
|
||||
|
||||
// Check if it's time to turn backlight ON
|
||||
if (currentTime == clockConfig.backlightOnTime && !backlightState) {
|
||||
LOG_INFO(TAG, "💡 Turning backlight ON at %s (output #%d)",
|
||||
currentTime.c_str(), clockConfig.backlightOutput + 1);
|
||||
_outputManager->fireOutput(clockConfig.backlightOutput);
|
||||
backlightState = true;
|
||||
}
|
||||
// Check if it's time to turn backlight OFF
|
||||
else if (currentTime == clockConfig.backlightOffTime && backlightState) {
|
||||
LOG_INFO(TAG, "💡 Turning backlight OFF at %s (output #%d)",
|
||||
currentTime.c_str(), clockConfig.backlightOutput + 1);
|
||||
_outputManager->extinguishOutput(clockConfig.backlightOutput);
|
||||
backlightState = false;
|
||||
}
|
||||
}
|
||||
|
||||
bool Timekeeper::isInSilencePeriod() {
|
||||
if (!_configManager || !rtc.isrunning()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto& clockConfig = _configManager->getClockConfig();
|
||||
|
||||
// Get current time
|
||||
DateTime now = rtc.now();
|
||||
char currentTimeStr[6];
|
||||
sprintf(currentTimeStr, "%02d:%02d", now.hour(), now.minute());
|
||||
String currentTime = String(currentTimeStr);
|
||||
|
||||
// Check daytime silence period
|
||||
if (clockConfig.daytimeSilenceEnabled) {
|
||||
bool inDaytime = isTimeInRange(currentTime, clockConfig.daytimeSilenceOnTime, clockConfig.daytimeSilenceOffTime);
|
||||
LOG_DEBUG(TAG, "🔇 Daytime silence check: current=%s, range=%s-%s, inRange=%s",
|
||||
currentTime.c_str(), clockConfig.daytimeSilenceOnTime.c_str(),
|
||||
clockConfig.daytimeSilenceOffTime.c_str(), inDaytime ? "YES" : "NO");
|
||||
if (inDaytime) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Check nighttime silence period
|
||||
if (clockConfig.nighttimeSilenceEnabled) {
|
||||
bool inNighttime = isTimeInRange(currentTime, clockConfig.nighttimeSilenceOnTime, clockConfig.nighttimeSilenceOffTime);
|
||||
LOG_DEBUG(TAG, "🌙 Nighttime silence check: current=%s, range=%s-%s, inRange=%s",
|
||||
currentTime.c_str(), clockConfig.nighttimeSilenceOnTime.c_str(),
|
||||
clockConfig.nighttimeSilenceOffTime.c_str(), inNighttime ? "YES" : "NO");
|
||||
if (inNighttime) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool Timekeeper::isTimeInRange(const String& currentTime, const String& startTime, const String& endTime) const {
|
||||
// Handle the case where the time range crosses midnight (e.g., 22:00 to 07:00)
|
||||
if (startTime > endTime) {
|
||||
// Range crosses midnight - current time is in range if it's after start OR before end
|
||||
return (currentTime >= startTime || currentTime <= endTime);
|
||||
} else {
|
||||
// Normal range - current time is in range if it's between start and end
|
||||
return (currentTime >= startTime && currentTime <= endTime);
|
||||
}
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// HEALTH CHECK IMPLEMENTATION
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
bool Timekeeper::isHealthy() {
|
||||
// Check if RTC is running
|
||||
if (!rtc.isrunning()) {
|
||||
LOG_DEBUG(TAG, "TimeKeeper: Unhealthy - RTC not running");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if main task is created and running
|
||||
if (mainTaskHandle == NULL) {
|
||||
LOG_DEBUG(TAG, "TimeKeeper: Unhealthy - Main task not created");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if task is still alive
|
||||
eTaskState taskState = eTaskGetState(mainTaskHandle);
|
||||
if (taskState == eDeleted || taskState == eInvalid) {
|
||||
LOG_DEBUG(TAG, "TimeKeeper: Unhealthy - Main task deleted or invalid");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if required dependencies are set
|
||||
if (!_configManager) {
|
||||
LOG_DEBUG(TAG, "TimeKeeper: Unhealthy - ConfigManager not set");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!_outputManager) {
|
||||
LOG_DEBUG(TAG, "TimeKeeper: Unhealthy - OutputManager not set");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if time is reasonable (not stuck at epoch or way in the future)
|
||||
DateTime now = rtc.now();
|
||||
if (now.year() < 2020 || now.year() > 2100) {
|
||||
LOG_DEBUG(TAG, "TimeKeeper: Unhealthy - RTC time unreasonable: %d", now.year());
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* TIMEKEEPER.HPP - NTP Synchronization and Clock Management
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* ⏰ THE TIME MASTER OF VESPER ⏰
|
||||
*
|
||||
* This class manages all time-related functionality including NTP synchronization,
|
||||
* timezone handling, and hardware clock signal generation. It ensures accurate
|
||||
* timekeeping across the entire system.
|
||||
*
|
||||
* 🏗️ TIME MANAGEMENT:
|
||||
* • NTP synchronization with automatic retry
|
||||
* • Timezone and daylight saving time support
|
||||
* • Hardware clock signal generation
|
||||
* • Network-dependent time sync
|
||||
* • Clean dependency injection architecture
|
||||
*
|
||||
* 📋 VERSION: 2.0 (Modular time management)
|
||||
* 📅 DATE: 2025
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#ifndef TIMEKEEPER_HPP
|
||||
#define TIMEKEEPER_HPP
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <ArduinoJson.h>
|
||||
#include <RTClib.h>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "../Logging/Logging.hpp"
|
||||
|
||||
// Forward declarations
|
||||
class OutputManager;
|
||||
class ConfigManager;
|
||||
class Networking;
|
||||
|
||||
// Structure to hold scheduled events
|
||||
struct ScheduledEvent {
|
||||
String timeStr; // Time in "HH:MM:SS" format
|
||||
JsonObject eventData; // Complete event data from JSON
|
||||
bool triggered = false; // Flag to prevent multiple triggers
|
||||
};
|
||||
|
||||
class Timekeeper {
|
||||
private:
|
||||
// RTC object
|
||||
RTC_DS1307 rtc;
|
||||
|
||||
// Event storage
|
||||
std::vector<ScheduledEvent> todaysEvents;
|
||||
std::vector<ScheduledEvent> tomorrowsEvents;
|
||||
|
||||
// Clocktower Updating Pause
|
||||
bool clockUpdatesPaused = false;
|
||||
|
||||
// Alert management - new functionality
|
||||
int lastHour = -1; // Track last processed hour to avoid duplicate alerts
|
||||
int lastMinute = -1; // Track last processed minute for quarter/half alerts
|
||||
std::atomic<bool> alertInProgress{false}; // Flag to track if alert is currently playing
|
||||
|
||||
// Backlight management - new functionality
|
||||
bool backlightState = false; // Track current backlight state
|
||||
|
||||
// Clean dependencies
|
||||
OutputManager* _outputManager = nullptr;
|
||||
ConfigManager* _configManager = nullptr;
|
||||
Networking* _networking = nullptr;
|
||||
class Player* _player = nullptr; // Reference to Player for playback status checks
|
||||
|
||||
// Legacy function pointer (DEPRECATED - will be removed)
|
||||
void (*relayWriteFunc)(int relay, int state) = nullptr;
|
||||
|
||||
// Task handles - CONSOLIDATED!
|
||||
TaskHandle_t mainTaskHandle = NULL; // Single task handles everything
|
||||
|
||||
public:
|
||||
// Main initialization (no clock outputs initially)
|
||||
void begin();
|
||||
|
||||
// Modern clean interface
|
||||
void setOutputManager(OutputManager* outputManager);
|
||||
void setConfigManager(ConfigManager* configManager);
|
||||
void setNetworking(Networking* networking);
|
||||
void setPlayer(class Player* player); // Set Player reference for playback coordination
|
||||
|
||||
// Clock Updates Pause Functions
|
||||
void pauseClockUpdates() { clockUpdatesPaused = true; }
|
||||
void resumeClockUpdates() { clockUpdatesPaused = false; }
|
||||
bool areClockUpdatesPaused() const { return clockUpdatesPaused; }
|
||||
|
||||
// Alert interruption - called by Player when starting playback
|
||||
void interruptActiveAlert();
|
||||
|
||||
// Legacy interface (DEPRECATED - will be removed)
|
||||
void setRelayWriteFunction(void (*func)(int, int));
|
||||
|
||||
// DEPRECATED: Clock outputs now configured via ConfigManager
|
||||
void setClockOutputs(int relay1, int relay2) __attribute__((deprecated("Use ConfigManager to set clock outputs")));
|
||||
|
||||
// Time management functions
|
||||
void setTime(unsigned long timestamp);
|
||||
|
||||
/**
|
||||
* @brief Set RTC time with local timestamp (timezone already applied)
|
||||
* @param localTimestamp Unix timestamp with timezone offset already applied
|
||||
*/
|
||||
void setTimeWithLocalTimestamp(unsigned long localTimestamp); // Set RTC time from Unix timestamp
|
||||
unsigned long getTime(); // Get current time as Unix timestamp
|
||||
void syncTimeWithNTP(); // Sync RTC time with NTP server
|
||||
|
||||
// Event management
|
||||
void loadTodaysEvents();
|
||||
void loadNextDayEvents();
|
||||
|
||||
// Static task functions (CONSOLIDATED)
|
||||
static void mainTimekeeperTask(void* parameter);
|
||||
|
||||
bool isHealthy();
|
||||
|
||||
private:
|
||||
// Helper functions
|
||||
bool isSameDate(String eventDateTime, int year, int month, int day);
|
||||
void addToTodaysSchedule(JsonObject event);
|
||||
void sortEventsByTime();
|
||||
String getCurrentTimeString();
|
||||
|
||||
// Core functionality
|
||||
void checkScheduledEvents();
|
||||
void triggerEvent(ScheduledEvent& event);
|
||||
|
||||
// New clock features - comprehensive alert and automation system
|
||||
void checkClockAlerts();
|
||||
void triggerHourlyAlert(int hour);
|
||||
void checkBacklightAutomation();
|
||||
bool isInSilencePeriod();
|
||||
bool isTimeInRange(const String& currentTime, const String& startTime, const String& endTime) const;
|
||||
void fireAlertBell(uint8_t bellNumber, int count = 1);
|
||||
|
||||
// Physical clock synchronization - SIMPLE approach based on your Arduino code
|
||||
void checkAndSyncPhysicalClock();
|
||||
void advancePhysicalClockOneMinute();
|
||||
void updatePhysicalClockTime();
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// HEALTH CHECK METHOD
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
public:
|
||||
/** @brief Check if TimeKeeper is in healthy state */
|
||||
bool isHealthy() const;
|
||||
};
|
||||
|
||||
#endif
|
||||
+542
@@ -0,0 +1,542 @@
|
||||
/*
|
||||
|
||||
█████ █████ ██████████ █████████ ███████████ ██████████ ███████████
|
||||
▒▒███ ▒▒███ ▒▒███▒▒▒▒▒█ ███▒▒▒▒▒███▒▒███▒▒▒▒▒███▒▒███▒▒▒▒▒█▒▒███▒▒▒▒▒███
|
||||
▒███ ▒███ ▒███ █ ▒ ▒███ ▒▒▒ ▒███ ▒███ ▒███ █ ▒ ▒███ ▒███
|
||||
▒███ ▒███ ▒██████ ▒▒█████████ ▒██████████ ▒██████ ▒██████████
|
||||
▒▒███ ███ ▒███▒▒█ ▒▒▒▒▒▒▒▒███ ▒███▒▒▒▒▒▒ ▒███▒▒█ ▒███▒▒▒▒▒███
|
||||
▒▒▒█████▒ ▒███ ▒ █ ███ ▒███ ▒███ ▒███ ▒ █ ▒███ ▒███
|
||||
▒▒███ ██████████▒▒█████████ █████ ██████████ █████ █████
|
||||
▒▒▒ ▒▒▒▒▒▒▒▒▒▒ ▒▒▒▒▒▒▒▒▒ ▒▒▒▒▒ ▒▒▒▒▒▒▒▒▒▒ ▒▒▒▒▒ ▒▒▒▒▒
|
||||
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* Project VESPER - BELL AUTOMATION SYSTEM - Main Firmware Entry Point
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 🔔 DESCRIPTION:
|
||||
* High-precision automated bell control system with multi-protocol communication,
|
||||
* real-time telemetry, OTA updates, and modular hardware abstraction.
|
||||
*
|
||||
* 🏗️ ARCHITECTURE:
|
||||
* Clean modular design with dependency injection and proper separation of concerns.
|
||||
* Each major system is encapsulated in its own class with well-defined interfaces.
|
||||
*
|
||||
* 🎯 KEY FEATURES:
|
||||
* ✅ Microsecond-precision bell timing (BellEngine)
|
||||
* ✅ Multi-hardware support (PCF8574, GPIO, Mock)
|
||||
* ✅ Dual network connectivity (Ethernet + WiFi + Permanent AP Mode)
|
||||
* ✅ Multi-protocol communication (MQTT + WebSocket + HTTP REST API)
|
||||
* ✅ Web settings interface for network mode switching
|
||||
* ✅ Real-time telemetry and load monitoring
|
||||
* ✅ Over-the-air firmware updates
|
||||
* ✅ SD card configuration and file management
|
||||
* ✅ NTP time synchronization
|
||||
* ✅ Comprehensive logging system
|
||||
*
|
||||
* 📡 COMMUNICATION PROTOCOLS:
|
||||
* • MQTT (SSL/TLS via AsyncMqttClient on Core 0)
|
||||
* • WebSocket (Real-time web interface)
|
||||
* • HTTP REST API (Command execution via HTTP)
|
||||
* • UDP Discovery (Auto-discovery service)
|
||||
* • HTTP/HTTPS (OTA updates)
|
||||
*
|
||||
* 🔧 HARDWARE ABSTRACTION:
|
||||
* OutputManager provides clean interface for different relay systems:
|
||||
* - PCF8574OutputManager: I2C GPIO expander (8 outputs, 6 on Kincony A6 Board)
|
||||
* - GPIOOutputManager: Direct ESP32 pins (for DIY projects)
|
||||
* - MockOutputManager: Testing without hardware
|
||||
*
|
||||
* ⚡ PERFORMANCE:
|
||||
* High-priority FreeRTOS tasks ensure microsecond timing precision.
|
||||
* Core 1 dedicated to BellEngine for maximum performance.
|
||||
*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════
|
||||
* 📋 VERSION CONFIGURATION
|
||||
* ═══════════════════════════════════════════════════════════════════════════════
|
||||
* 📅 DATE: 2025-10-10
|
||||
* 👨💻 AUTHOR: BellSystems bonamin
|
||||
*/
|
||||
|
||||
#define FW_VERSION "154"
|
||||
|
||||
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════
|
||||
* 📅 VERSION HISTORY:
|
||||
* NOTE: Versions are now stored as integers (v1.3 = 130)
|
||||
* ═══════════════════════════════════════════════════════════════════════════════
|
||||
* v0.1 (100) - Vesper Launch Beta
|
||||
* v1.2 (120) - Added Log Level Configuration via App/MQTT
|
||||
* v1.3 (130) - Added Telemetry Reports to App, Various Playback Fixes
|
||||
* v137 - Made OTA and MQTT delays Async
|
||||
* v138 - Removed Ethernet, added default WiFi creds (Mikrotik AP) and fixed various Clock issues
|
||||
* v140 - Changed FW Updates to Direct-to-Flash and added manual update functionality with version check
|
||||
* v151 - Fixed Clock Alerts not running properly
|
||||
* v152 - Fix RTC Time Reports, added sync_time_to_LCD functionality
|
||||
* v153 - Fix Infinite Loop Bug and Melody Download crashes.
|
||||
* ═══════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// SYSTEM LIBRARIES - Core ESP32 and Arduino functionality
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
#include <SD.h> // SD card file system operations
|
||||
#include <FS.h> // File system base class
|
||||
#include <ETH.h> // Ethernet connectivity (W5500 support)
|
||||
#include <SPI.h> // SPI communication protocol
|
||||
#include <Arduino.h> // Arduino core framework
|
||||
#include <WiFi.h> // WiFi connectivity management
|
||||
#include <HTTPClient.h> // HTTP client for OTA updates
|
||||
#include <Update.h> // Firmware update utilities
|
||||
#include <Wire.h> // I2C communication protocol
|
||||
#include <esp_task_wdt.h> // Task watchdog timer
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// NETWORKING LIBRARIES - Advanced networking and communication
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
#include <WiFiManager.h> // WiFi configuration portal
|
||||
#include <ESPAsyncWebServer.h> // Async web server for WebSocket support
|
||||
#include <AsyncUDP.h> // UDP for discovery service
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// DATA PROCESSING LIBRARIES - JSON parsing and data structures
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
#include <ArduinoJson.h> // Efficient JSON processing
|
||||
#include <string> // STL string support
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// HARDWARE LIBRARIES - Peripheral device control
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
#include <Adafruit_PCF8574.h> // I2C GPIO expander for relay control
|
||||
#include <RTClib.h> // Real-time clock functionality
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// CUSTOM CLASSES - Include Custom Classes and Functions
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
#include "SDCardMutex/SDCardMutex.hpp" // ⚠️ MUST be included before any SD-using classes
|
||||
#include "ConfigManager/ConfigManager.hpp"
|
||||
#include "FileManager/FileManager.hpp"
|
||||
#include "TimeKeeper/TimeKeeper.hpp"
|
||||
#include "Logging/Logging.hpp"
|
||||
#include "Telemetry/Telemetry.hpp"
|
||||
#include "OTAManager/OTAManager.hpp"
|
||||
#include "Networking/Networking.hpp"
|
||||
#include "Communication/CommunicationRouter/CommunicationRouter.hpp"
|
||||
#include "ClientManager/ClientManager.hpp"
|
||||
#include "Communication/ResponseBuilder/ResponseBuilder.hpp"
|
||||
#include "Player/Player.hpp"
|
||||
#include "BellEngine/BellEngine.hpp"
|
||||
#include "OutputManager/OutputManager.hpp"
|
||||
#include "HealthMonitor/HealthMonitor.hpp"
|
||||
#include "FirmwareValidator/FirmwareValidator.hpp"
|
||||
#include "InputManager/InputManager.hpp"
|
||||
|
||||
#define TAG "Main"
|
||||
|
||||
// Class Constructors
|
||||
ConfigManager configManager;
|
||||
FileManager fileManager(&configManager);
|
||||
Timekeeper timekeeper;
|
||||
Telemetry telemetry;
|
||||
OTAManager otaManager(configManager);
|
||||
Player player;
|
||||
AsyncWebServer server(80);
|
||||
AsyncWebSocket ws("/ws");
|
||||
AsyncUDP udp;
|
||||
Networking networking(configManager);
|
||||
CommunicationRouter communication(configManager, otaManager, networking, server, ws, udp);
|
||||
HealthMonitor healthMonitor;
|
||||
FirmwareValidator firmwareValidator;
|
||||
InputManager inputManager;
|
||||
|
||||
|
||||
// 🔥 OUTPUT SYSTEM - PCF8574/PCF8575 I2C Expanders Configuration
|
||||
// Choose one of the following configurations (with active output counts):
|
||||
|
||||
// Option 1: Single PCF8574 (6 active outputs out of 8 max)
|
||||
PCF8574OutputManager outputManager(0x24, ChipType::PCF8574, 6);
|
||||
|
||||
// Option 2: Single PCF8575 (8 active outputs out of 16 max)
|
||||
//PCF8574OutputManager outputManager(0x24, ChipType::PCF8575, 8);
|
||||
|
||||
// Option 3: PCF8574 + PCF8575 (6 + 8 = 14 total virtual outputs)
|
||||
//PCF8574OutputManager outputManager(0x24, ChipType::PCF8574, 6, 0x21, ChipType::PCF8575, 8);
|
||||
|
||||
// Option 4: Dual PCF8575 (8 + 8 = 16 total virtual outputs)
|
||||
//PCF8574OutputManager outputManager(0x24, ChipType::PCF8575, 8, 0x21, ChipType::PCF8575, 8);
|
||||
|
||||
// Virtual Output Mapping Examples:
|
||||
// Option 1: Virtual outputs 0-5 → PCF8574[0x20] pins 0-5
|
||||
// Option 3: Virtual outputs 0-5 → PCF8574[0x20] pins 0-5, Virtual outputs 6-13 → PCF8575[0x21] pins 0-7
|
||||
// Option 4: Virtual outputs 0-7 → PCF8575[0x20] pins 0-7, Virtual outputs 8-15 → PCF8575[0x21] pins 0-7
|
||||
|
||||
// Legacy backward-compatible (defaults to 8 active outputs):
|
||||
//PCF8574OutputManager outputManager(0x20, ChipType::PCF8574); // 8/8 active outputs
|
||||
|
||||
BellEngine bellEngine(player, configManager, telemetry, outputManager); // 🔥 THE ULTIMATE BEAST!
|
||||
|
||||
TaskHandle_t bellEngineHandle = NULL; // Legacy - will be removed
|
||||
TimerHandle_t schedulerTimer;
|
||||
TimerHandle_t ntpSyncTimer; // Non-blocking delayed NTP sync timer
|
||||
|
||||
|
||||
|
||||
void handleFactoryReset() {
|
||||
if (configManager.resetAllToDefaults()) {
|
||||
delay(3000);
|
||||
ESP.restart();
|
||||
}
|
||||
}
|
||||
|
||||
// One-shot task to perform NTP sync outside the Tmr Svc context
|
||||
static void ntpSyncTask(void* param) {
|
||||
LOG_DEBUG(TAG, "Network stabilization complete - starting NTP sync");
|
||||
if (!networking.isInAPMode()) {
|
||||
timekeeper.syncTimeWithNTP();
|
||||
}
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
// Non-blocking NTP sync timer callback — defers work to a task (Tmr Svc stack is only 2KB)
|
||||
void ntpSyncTimerCallback(TimerHandle_t xTimer) {
|
||||
xTaskCreate(ntpSyncTask, "ntpSync", 3072, NULL, 5, NULL);
|
||||
}
|
||||
|
||||
|
||||
|
||||
void setup()
|
||||
{
|
||||
// Initialize Serial Communications (for debugging) & I2C Bus (for Hardware Control)
|
||||
Serial.begin(115200);
|
||||
Serial.print("VESPER System Booting UP! - Version ");
|
||||
Serial.println(FW_VERSION);
|
||||
Wire.begin(4,15);
|
||||
auto& hwConfig = configManager.getHardwareConfig();
|
||||
SPI.begin(hwConfig.ethSpiSck, hwConfig.ethSpiMiso, hwConfig.ethSpiMosi);
|
||||
delay(50);
|
||||
|
||||
// 🔒 CRITICAL: Initialize SD Card Mutex BEFORE any SD operations
|
||||
// This prevents concurrent SD access from multiple FreeRTOS tasks
|
||||
if (!SDCardMutex::getInstance().begin()) {
|
||||
Serial.println("❌ FATAL: Failed to initialize SD card mutex!");
|
||||
Serial.println(" System cannot continue safely - entering infinite loop");
|
||||
while(1) { delay(1000); } // Halt system - unsafe to proceed
|
||||
}
|
||||
Serial.println("✅ SD card mutex initialized");
|
||||
|
||||
// Initialize Configuration (loads factory identity from NVS + user settings from SD)
|
||||
configManager.begin();
|
||||
|
||||
// Apply log level from config (loaded from SD)
|
||||
uint8_t logLevel = configManager.getGeneralConfig().serialLogLevel;
|
||||
Logging::setLevel((Logging::LogLevel)logLevel);
|
||||
LOG_INFO(TAG, "Log level set to %d from configuration", logLevel);
|
||||
|
||||
inputManager.begin();
|
||||
inputManager.setFactoryResetLongPressCallback(handleFactoryReset);
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// REMOVED: Manual device identity setters
|
||||
// Device identity (UID, hwType, hwVersion) is now READ-ONLY in production firmware
|
||||
// These values are set by factory firmware and stored permanently in NVS
|
||||
// Production firmware loads them once at boot and keeps them in RAM
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
// Update firmware version (this is the ONLY identity field that can be set)
|
||||
|
||||
// 🔥 MIGRATION: Convert old float-style version to integer format
|
||||
String currentVersion = configManager.getFwVersion();
|
||||
if (currentVersion.indexOf('.') != -1) {
|
||||
// Old format detected (e.g., "1.3"), convert to integer ("130")
|
||||
float versionFloat = currentVersion.toFloat();
|
||||
uint16_t versionInt = (uint16_t)(versionFloat * 100.0f);
|
||||
configManager.setFwVersion(String(versionInt));
|
||||
configManager.saveDeviceConfig();
|
||||
LOG_INFO(TAG, "⚠️ Migrated version format: %s -> %u", currentVersion.c_str(), versionInt);
|
||||
}
|
||||
|
||||
configManager.setFwVersion(FW_VERSION);
|
||||
LOG_INFO(TAG, "Firmware version: %s", FW_VERSION);
|
||||
|
||||
|
||||
// Display device information after configuration is loaded
|
||||
Serial.println("\n=== DEVICE IDENTITY ===");
|
||||
Serial.printf("Device UID: %s\n", configManager.getDeviceUID().c_str());
|
||||
Serial.printf("Hardware Type: %s\n", configManager.getHwType().c_str());
|
||||
Serial.printf("Hardware Version: %s\n", configManager.getHwVersion().c_str());
|
||||
Serial.printf("Firmware Version: %s\n", configManager.getFwVersion().c_str());
|
||||
Serial.printf("AP SSID: %s\n", configManager.getAPSSID().c_str());
|
||||
Serial.println("=====================\n");
|
||||
|
||||
// 🔥 CRITICAL: Initialize Health Monitor FIRST (required for firmware validation)
|
||||
healthMonitor.begin();
|
||||
// Register all subsystems with health monitor for continuous monitoring
|
||||
healthMonitor.setConfigManager(&configManager);
|
||||
healthMonitor.setFileManager(&fileManager);
|
||||
|
||||
// Initialize Output Manager - 🔥 THE NEW WAY!
|
||||
outputManager.setConfigManager(&configManager);
|
||||
if (!outputManager.initialize()) {
|
||||
LOG_ERROR(TAG, "Failed to initialize OutputManager!");
|
||||
// Continue anyway for now
|
||||
}
|
||||
// Register OutputManager with health monitor
|
||||
healthMonitor.setOutputManager(&outputManager);
|
||||
|
||||
// Initialize BellEngine early for health validation
|
||||
bellEngine.begin();
|
||||
healthMonitor.setBellEngine(&bellEngine);
|
||||
|
||||
delay(100);
|
||||
|
||||
// 🔥 BULLETPROOF: Initialize Firmware Validator and perform startup validation
|
||||
firmwareValidator.begin(&healthMonitor, &configManager);
|
||||
delay(100);
|
||||
|
||||
// 💀 CRITICAL SAFETY CHECK: Perform startup validation
|
||||
// This MUST happen early before initializing other subsystems
|
||||
if (!firmwareValidator.performStartupValidation()) {
|
||||
// If we reach here, startup validation failed and rollback was triggered
|
||||
// The system should reboot automatically to the previous firmware
|
||||
LOG_ERROR(TAG, "💀 STARTUP VALIDATION FAILED - SYSTEM HALTED");
|
||||
while(1) { delay(1000); } // Should not reach here
|
||||
}
|
||||
|
||||
LOG_INFO(TAG, "✅ Firmware startup validation PASSED - proceeding with initialization");
|
||||
|
||||
// Initialize remaining subsystems...
|
||||
|
||||
// SD Card initialization is now handled by ConfigManager
|
||||
|
||||
// Initialize timekeeper with NO clock outputs
|
||||
timekeeper.begin(); // No parameters needed
|
||||
// Connect the timekeeper to dependencies (CLEAN!)
|
||||
timekeeper.setOutputManager(&outputManager);
|
||||
timekeeper.setConfigManager(&configManager);
|
||||
timekeeper.setNetworking(&networking);
|
||||
timekeeper.setPlayer(&player); // 🔥 Connect for playback coordination
|
||||
// Clock outputs now configured via ConfigManager/Communication commands
|
||||
|
||||
// Register TimeKeeper with health monitor
|
||||
healthMonitor.setTimeKeeper(&timekeeper);
|
||||
|
||||
// Initialize Telemetry
|
||||
telemetry.setPlayerReference(&player.isPlaying);
|
||||
// 🚑 CRITICAL: Connect force stop callback for overload protection!
|
||||
telemetry.setForceStopCallback([]() { player.forceStop(); });
|
||||
telemetry.setFileManager(&fileManager);
|
||||
telemetry.begin();
|
||||
|
||||
// Register Telemetry with health monitor
|
||||
healthMonitor.setTelemetry(&telemetry);
|
||||
|
||||
|
||||
// Initialize Networking (handles everything automatically)
|
||||
networking.begin();
|
||||
|
||||
// Register Networking with health monitor
|
||||
healthMonitor.setNetworking(&networking);
|
||||
|
||||
// Initialize Player
|
||||
player.begin();
|
||||
|
||||
// Register Player with health monitor
|
||||
healthMonitor.setPlayer(&player);
|
||||
|
||||
// BellEngine already initialized and registered earlier for health validation
|
||||
|
||||
// Initialize Communication Manager (now with PubSubClient MQTT)
|
||||
communication.begin();
|
||||
communication.setPlayerReference(&player);
|
||||
communication.setFileManagerReference(&fileManager);
|
||||
communication.setTimeKeeperReference(&timekeeper);
|
||||
communication.setFirmwareValidatorReference(&firmwareValidator);
|
||||
communication.setTelemetryReference(&telemetry);
|
||||
|
||||
player.setDependencies(&communication, &fileManager);
|
||||
player.setBellEngine(&bellEngine); // Connect the beast!
|
||||
player.setTelemetry(&telemetry);
|
||||
player.setTimekeeper(&timekeeper); // 🔥 Connect for alert coordination
|
||||
|
||||
// Register Communication with health monitor
|
||||
healthMonitor.setCommunication(&communication);
|
||||
|
||||
// 🔔 CONNECT BELLENGINE TO COMMUNICATION FOR DING NOTIFICATIONS!
|
||||
bellEngine.setCommunicationManager(&communication);
|
||||
|
||||
// Track if AsyncWebServer has been started to prevent duplicates
|
||||
static bool webServerStarted = false;
|
||||
|
||||
// Create NTP sync timer (one-shot, 3 second delay for network stabilization)
|
||||
ntpSyncTimer = xTimerCreate(
|
||||
"NTPSync", // Timer name
|
||||
pdMS_TO_TICKS(3000), // 3 second delay (network stabilization)
|
||||
pdFALSE, // One-shot timer (not auto-reload)
|
||||
NULL, // Timer ID (not used)
|
||||
ntpSyncTimerCallback // Callback function
|
||||
);
|
||||
|
||||
// Set up network callbacks
|
||||
networking.setNetworkCallbacks(
|
||||
[&webServerStarted]() {
|
||||
communication.onNetworkConnected();
|
||||
|
||||
// Schedule non-blocking NTP sync after 3s network stabilization (like MQTT)
|
||||
// Skip NTP sync in AP mode (no internet connection)
|
||||
if (!networking.isInAPMode() && ntpSyncTimer) {
|
||||
LOG_DEBUG(TAG, "Network connected - scheduling NTP sync after 3s stabilization (non-blocking)");
|
||||
xTimerStart(ntpSyncTimer, 0);
|
||||
}
|
||||
|
||||
// Start AsyncWebServer when network becomes available (only once!)
|
||||
if (!webServerStarted && networking.getState() != NetworkState::WIFI_PORTAL_MODE) {
|
||||
LOG_INFO(TAG, "🚀 Starting AsyncWebServer on port 80...");
|
||||
server.begin();
|
||||
LOG_INFO(TAG, "✅ AsyncWebServer started on http://%s", networking.getLocalIP().c_str());
|
||||
webServerStarted = true;
|
||||
}
|
||||
}, // onConnected
|
||||
[]() { communication.onNetworkDisconnected(); } // onDisconnected
|
||||
);
|
||||
|
||||
// If already connected, trigger MQTT connection and setup manually
|
||||
if (networking.isConnected()) {
|
||||
LOG_INFO(TAG, "Network already connected - initializing services");
|
||||
communication.onNetworkConnected();
|
||||
|
||||
// Schedule non-blocking NTP sync after 3s network stabilization (like MQTT)
|
||||
// Skip NTP sync in AP mode (no internet connection)
|
||||
if (!networking.isInAPMode() && ntpSyncTimer) {
|
||||
LOG_DEBUG(TAG, "Network already connected - scheduling NTP sync after 3s stabilization (non-blocking)");
|
||||
xTimerStart(ntpSyncTimer, 0);
|
||||
}
|
||||
|
||||
// 🔥 CRITICAL: Start AsyncWebServer ONLY when network is ready
|
||||
// Do NOT start if WiFiManager portal is active (port 80 conflict!)
|
||||
if (!webServerStarted && networking.getState() != NetworkState::WIFI_PORTAL_MODE) {
|
||||
LOG_INFO(TAG, "🚀 Starting AsyncWebServer on port 80...");
|
||||
server.begin();
|
||||
LOG_INFO(TAG, "✅ AsyncWebServer started on http://%s", networking.getLocalIP().c_str());
|
||||
webServerStarted = true;
|
||||
}
|
||||
} else {
|
||||
LOG_WARNING(TAG, "⚠️ Network not ready - services will start after connection");
|
||||
}
|
||||
|
||||
// Initialize OTA Manager
|
||||
otaManager.begin();
|
||||
otaManager.setFileManager(&fileManager);
|
||||
otaManager.setPlayer(&player); // Set player reference for idle check
|
||||
otaManager.setTimeKeeper(&timekeeper); // Set timekeeper reference for freeze mode
|
||||
otaManager.setTelemetry(&telemetry); // Set telemetry reference for freeze mode
|
||||
|
||||
// 🔥 FIX: OTA check will happen asynchronously via scheduled timer (no blocking delay)
|
||||
// UDP discovery setup can happen immediately without conflicts
|
||||
communication.setupUdpDiscovery();
|
||||
|
||||
// Register OTA Manager with health monitor
|
||||
healthMonitor.setOTAManager(&otaManager);
|
||||
|
||||
// Note: AsyncWebServer will be started by network callbacks when connection is ready
|
||||
// This avoids port 80 conflicts with WiFiManager's captive portal
|
||||
|
||||
|
||||
// 🔥 START RUNTIME VALIDATION: All subsystems are now initialized
|
||||
// Begin extended runtime validation if we're in testing mode
|
||||
if (firmwareValidator.isInTestingMode()) {
|
||||
LOG_INFO(TAG, "🏃 Starting runtime validation - firmware will be tested for %lu seconds",
|
||||
firmwareValidator.getValidationConfig().runtimeTimeoutMs / 1000);
|
||||
firmwareValidator.startRuntimeValidation();
|
||||
} else {
|
||||
LOG_INFO(TAG, "✅ Firmware already validated - normal operation mode");
|
||||
}
|
||||
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// INITIALIZATION COMPLETE
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// ✅ All automatic task creation handled by individual components:
|
||||
// • BellEngine creates high-priority timing task on Core 1
|
||||
// • Telemetry creates monitoring task for load tracking
|
||||
// • Player creates duration timer for playback control
|
||||
// • Communication creates MQTT task on Core 0 with PubSubClient
|
||||
// • Networking creates connection management timers
|
||||
// ✅ Bell configuration automatically loaded by ConfigManager
|
||||
// ✅ System ready for MQTT commands, WebSocket connections, and UDP discovery
|
||||
}
|
||||
|
||||
// ███████████████████████████████████████████████████████████████████████████████████
|
||||
// █ MAIN LOOP █
|
||||
// ███████████████████████████████████████████████████████████████████████████████████
|
||||
// The main loop is intentionally kept minimal in this architecture. All critical
|
||||
// functionality runs in dedicated FreeRTOS tasks for optimal performance and timing.
|
||||
// This ensures the main loop doesn't interfere with precision bell timing.
|
||||
|
||||
/**
|
||||
* @brief Main execution loop - Minimal by design
|
||||
*
|
||||
* In the new modular architecture, all heavy lifting is done by dedicated tasks:
|
||||
* • BellEngine: High-priority task on Core 1 for microsecond timing
|
||||
* • Telemetry: Background monitoring task for system health
|
||||
* • Player: Timer-based duration control for melody playback
|
||||
* • Communication: MQTT task on Core 0 + Event-driven WebSocket
|
||||
* • Networking: Automatic connection management
|
||||
*
|
||||
* The main loop only handles lightweight operations that don't require
|
||||
* precise timing or could benefit from running on Core 0.
|
||||
*
|
||||
* @note This loop runs on Core 0 and should remain lightweight to avoid
|
||||
* interfering with the precision timing on Core 1.
|
||||
*/
|
||||
void loop()
|
||||
{
|
||||
// Feed watchdog only during firmware validation
|
||||
if (firmwareValidator.isInTestingMode()) {
|
||||
esp_task_wdt_reset();
|
||||
} else {
|
||||
// Remove task from watchdog if validation completed
|
||||
static bool taskRemoved = false;
|
||||
if (!taskRemoved) {
|
||||
esp_task_wdt_delete(NULL); // Remove current task
|
||||
taskRemoved = true;
|
||||
}
|
||||
}
|
||||
|
||||
// 🔥 CRITICAL: Clean up dead WebSocket connections every 2 seconds
|
||||
// This prevents ghost connections from blocking new clients
|
||||
static unsigned long lastWsCleanup = 0;
|
||||
if (millis() - lastWsCleanup > 2000) {
|
||||
ws.cleanupClients();
|
||||
lastWsCleanup = millis();
|
||||
}
|
||||
|
||||
// Process UART command input from external devices (LCD panel, buttons)
|
||||
communication.loop();
|
||||
|
||||
// 🔥 DEBUG: Log every 10 seconds to verify we're still running
|
||||
static unsigned long lastLog = 0;
|
||||
if (millis() - lastLog > 10000) {
|
||||
LOG_DEBUG(TAG, "❤️ Loop alive | Free heap: %d bytes (%.1f KB) | Min free: %d | Largest block: %d",
|
||||
ESP.getFreeHeap(),
|
||||
ESP.getFreeHeap() / 1024.0,
|
||||
ESP.getMinFreeHeap(),
|
||||
ESP.getMaxAllocHeap());
|
||||
lastLog = millis();
|
||||
}
|
||||
|
||||
// Keep the loop responsive but not busy
|
||||
delay(100); // ⏱️ 100ms delay to prevent busy waiting
|
||||
}
|
||||
Reference in New Issue
Block a user