# BellEngine ## Summary BellEngine is the real-time bell activation core of the Vesper firmware. It receives compiled melody data from `Player` and fires physical relay outputs through `OutputManager` with microsecond-precision inter-note timing. The engine runs permanently on a dedicated FreeRTOS task (priority 6, Core 1, 12 KB stack) that spins idle between plays; when `start()` is called, it executes the full melody step-by-step without interruption, applying a hybrid vTaskDelay + busy-wait strategy to hit sub-millisecond timing accuracy. BellEngine exists as a separate subsystem so that all hardware-agnostic timing logic is isolated from both the higher-level playback policy (owned by `Player`) and the hardware abstraction (owned by `OutputManager`). --- ## Public API | Method | Description | |--------|-------------| | `BellEngine(Player&, ConfigManager&, Telemetry&, OutputManager&)` | Constructor. All four references must remain valid for the object lifetime. `CommunicationRouter` is injected separately via `setCommunicationManager()`. | | `void begin()` | Creates the FreeRTOS engine task. Must be called once before `start()`. Does **not** start playback. | | `void setCommunicationManager(CommunicationRouter*)` | Wires the optional communication reference used for overload notifications. May be called at any time before or after `begin()`. Pass `nullptr` to disconnect. | | `void setMelodyData(const std::vector&)` | Copies melody step data into the engine under a critical section. Each `uint16_t` is a bitmask: bit N set means note-slot N fires on this step. Must be called before `start()`. | | `void clearMelodyData()` | Clears melody data and marks the engine as not ready. Thread-safe. | | `void start()` | Signals the engine task to begin playback. No-op (with error log) if no melody data is loaded. | | `void stop()` | Graceful stop — sets the `_engineRunning` flag; the engine halts after the current inter-note delay. Does not cut mid-note relay pulses. | | `void emergencyStop()` | Immediate stop. Sets both `_emergencyStop` and `_engineRunning` flags and calls `emergencyShutdown()` to de-energize all relays via `OutputManager`. | | `bool isRunning() const` | Returns `true` if the engine is actively executing a melody. Atomic read. | | `bool isEmergencyStopped() const` | Returns `true` if an emergency stop is in effect. Atomic read. | | `uint32_t getMaxLoopTime() const` | Returns the worst-case engine loop execution time in microseconds, for performance diagnostics. | | `bool isHealthy() const` | Returns `true` if the engine task handle is valid, the task state is neither deleted nor invalid, and `OutputManager::isInitialized()` is true. Used by `HealthMonitor`. | --- ## Initialization BellEngine depends on `OutputManager` being initialized before `begin()` is called. In `main.cpp`, the sequence is: ``` outputManager.initialize() // OutputManager must be ready first bellEngine.begin() // Creates engine task; task waits idle healthMonitor.setBellEngine(&bellEngine) // ... other subsystems ... player.setBellEngine(&bellEngine) bellEngine.setCommunicationManager(&communication) ``` `begin()` is called early (before networking and communication) so that `HealthMonitor` and `FirmwareValidator` can include BellEngine in startup validation. The engine task itself remains idle at this stage — it does nothing until `Player` loads melody data and calls `start()`. Typical playback sequence (driven by `Player`): 1. `Player::loadMelodyInRAM()` — loads melody steps from SD into RAM. 2. `bellEngine.setMelodyData(steps)` — copies steps into BellEngine. 3. `bellEngine.start()` — sets `_engineRunning = true`. 4. Engine task calls `playbackLoop()`, iterates steps, fires relays via `OutputManager::fireOutputsBatchForDuration()`, applies `preciseDelay()` between steps. 5. On final step: `player.onMelodyLoopCompleted()` is called so Player can handle looping, pausing, or stopping. 6. `Player` calls `bellEngine.stop()` or `bellEngine.emergencyStop()` when done. --- ## Dependencies | Dependency | Role | |------------|------| | `Player` | Provides `isPlaying`, `isPaused`, `hardStop`, `speed`, `noteAssignments`, and the `onMelodyLoopCompleted()` callback. BellEngine reads these public fields directly — no locking around them. | | `ConfigManager` | Supplies per-bell relay duration (`getBellDuration(bellIndex)`) used when firing a note. | | `OutputManager` | Hardware abstraction. `fireOutputsBatchForDuration()` fires one or more relays simultaneously; `getPhysicalOutput()` maps logical bell index to physical pin; `emergencyShutdown()` de-energizes everything. | | `Telemetry` | `recordBellStrike(bellIndex)` is called on every activation. `getBellLoad()` and `isOverloaded()` are queried after each full melody loop to detect overload conditions. | | `CommunicationRouter` (optional) | `sendBellOverloadNotification()` is called when load thresholds are exceeded. | | FreeRTOS | Task, critical section (`portMUX_TYPE`), and `vTaskDelay` APIs. | | `esp_timer` | `esp_timer_get_time()` provides the microsecond timestamp used by `preciseDelay()` and performance tracking. | --- ## Gotchas / Notes **Thread safety model.** Engine state (`_engineRunning`, `_emergencyStop`, `_melodyDataReady`) uses `std::atomic` — safe to read/write from any task. Melody step data (`_melodySteps`) is guarded by a `portMUX_TYPE` spinlock via `portENTER_CRITICAL` / `portEXIT_CRITICAL`. The engine makes a local copy of `_melodySteps` at the start of each playback pass, so late calls to `setMelodyData()` do not affect an in-progress play. **Player state is read without locks.** `playbackLoop()` reads `_player.isPlaying`, `_player.hardStop`, `_player.isPaused`, and `_player.speed` directly as plain public members. These are written only from Core 0 tasks; the implicit memory ordering from `atomic` flag checks provides adequate coordination in practice, but this is a weak coupling point. **Timing strategy.** `preciseDelay(us)` uses `vTaskDelay` for the bulk of a delay (leaving a 500 µs margin) and then busy-waits for the remainder. This means Core 1 will spin-wait for up to 500 µs per note step. At typical bell speeds (≥ 100 ms per beat) the busy-wait fraction is negligible, but it will starve any other Core 1 work during that window. **Core 1 is dedicated.** The engine task is pinned to Core 1 at priority 6. No other application task should be pinned to Core 1 at equal or higher priority, or timing jitter will increase. **Stack size.** The engine task allocates 12 KB. The `activateNote()` path allocates two `std::vector` objects and a fixed 16-element `bool` array on the stack per note step; this is the dominant stack consumer. **`notifyBellsFired()` has been removed.** The per-bell ding notification (previously sent to WebSocket clients only) was unstable under load and had no consumers. The function and its call site have been deleted. Bell activity is visible to external systems via telemetry strike counts and health monitor alerts only. **`_precisionTimer` is unused.** The `esp_timer_handle_t _precisionTimer` field is allocated but never started. It is vestigial from an earlier design iteration. **Overload thresholds are hardcoded.** `checkAndNotifyOverloads()` uses fixed values of 54 (critical, ~90% of 60 strikes/min) and 36 (warning, ~60%) rather than reading per-bell maximums from config. This should be parameterized if bell load limits become configurable. **Emergency stop in destructor.** `~BellEngine()` calls `emergencyShutdown()`, which in turn calls `OutputManager::emergencyShutdown()`. If `OutputManager` has already been destroyed before `BellEngine`, this will be a use-after-free. Ensure destruction order in `main.cpp` is consistent with construction order (BellEngine before OutputManager).