refactor: Fixed the file hierarchy and switched to platform.io
This commit is contained in:
@@ -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
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
Reference in New Issue
Block a user