diff --git a/docs/Communication-Refactor-Plan.md b/docs/Communication-Refactor-Plan.md index 26a11ed..23eabe3 100644 --- a/docs/Communication-Refactor-Plan.md +++ b/docs/Communication-Refactor-Plan.md @@ -1,7 +1,8 @@ # Communication Subsystem — Complete Refactor Plan > Written: 2026-02-27 -> Status: **Planning** — Not yet implemented +> Updated: 2026-02-28 +> Status: **Stage 6 complete** — All stages done. SettingsWebServer absorbed into WebServerTransport. > Related: MQTT refactor, Logging refactor (separate plans) --- @@ -403,49 +404,76 @@ With this architecture, adding it costs almost nothing: ## Implementation Stages -### Stage 1 — Core Scaffolding ✅ / ⬜ TODO +### Stage 1 — Core Scaffolding ✅ COMPLETE > No behavior change. Zero risk. Headers only. -- [ ] Define `CommandEnvelope.hpp` -- [ ] Define `CommandResult.hpp` -- [ ] Define `ICommandHandler.hpp` -- [ ] Define `ITransport.hpp` -- [ ] Create `CommandBus` skeleton (register + dispatch, no handlers yet) -- [ ] Old `CommandHandler` stays untouched +- [x] Define `CommandEnvelope.hpp` +- [x] Define `CommandResult.hpp` +- [x] Define `ICommandHandler.hpp` +- [x] Define `ITransport.hpp` +- [x] Create `CommandBus` skeleton (register + dispatch, no handlers yet) +- [x] Old `CommandHandler` stays untouched -### Stage 2 — Migrate Handlers One Domain at a Time +### Stage 2 — Migrate Handlers One Domain at a Time ✅ COMPLETE > Write new handler → register on bus → comment out old if/else branch → test -- [ ] `PlaybackHandler` (simplest — one dependency) -- [ ] `SystemHandler` -- [ ] `FirmwareHandler` -- [ ] `LoggingHandler` -- [ ] `RelayHandler` (complex — multiple sub-commands) -- [ ] `ClockHandler` (most complex — many sub-commands) -- [ ] `FileHandler` -- [ ] `NetworkHandler` +- [x] `PlaybackHandler` (simplest — one dependency) +- [x] `SystemHandler` +- [x] `FirmwareHandler` +- [x] `LoggingHandler` +- [x] `RelayHandler` (complex — multiple sub-commands) +- [x] `ClockHandler` (most complex — many sub-commands) +- [x] `FileHandler` +- [x] `NetworkHandler` +- [x] `TelemetryHandler` (new — zero coverage in old system) +- [x] `MQTTHandler` (new — mqtt.enable / mqtt.disable) -### Stage 3 — Transport Layer Refactor -- [ ] Refactor `MQTTAsyncClient` → `MQTTTransport` (implement `ITransport`) -- [ ] Refactor `WebSocketServer` → `WebSocketTransport` (implement `ITransport`) -- [ ] Promote `HTTPRequestHandler` → `HTTPTransport` (proper HTTP identity, no more 0xFFFFFFFF) -- [ ] Refactor `UARTCommandHandler` → `UARTTransport` (whitelist lives here) +> Also added: `ResponseBuilder::fromResult(CommandResult)` factory method (needed by transports) -### Stage 4 — CommunicationRouter Simplification -- [ ] Replace router internals with `CommandBus` + transport array -- [ ] Implement `registerHandlers()` — replaces all `setXxxReference()` calls -- [ ] Delete old `CommandHandler` once all handlers migrated and tested +### Stage 3 — Transport Layer Refactor ✅ COMPLETE -### Stage 5 — Legacy Adapter (optional) -- [ ] Add `LegacyAdapter.cpp` if needed for staggered FlutterFlow rollout +- [x] `MQTTTransport` — wraps `MQTTAsyncClient`, implements `ITransport`. All timers/heartbeat/reconnect logic in the underlying client untouched. Callback → `CommandEnvelope` → bus → reply publishes to data topic. +- [x] `WebSocketTransport` — wraps `WebSocketServer` + `ClientManager`. Reply lambda routes response back to the originating client by `clientId`. Exposes `broadcastToMasters()` / `broadcastToSecondary()` for router helpers. +- [x] `HTTPTransport` — **proper first-class HTTP identity**. No more `0xFFFFFFFF` fake WS client ID. Registers `POST /api/command`, `GET /api/ping`, `GET /api/status`. Reply lambda captures `AsyncWebServerRequest*` and calls `send()` exactly once. `broadcast()` is a no-op (stateless protocol). +- [x] `UARTTransport` — wraps `UARTCommandHandler`. Whitelist enforced before bus dispatch; non-whitelisted commands silently dropped (no error response — prevents feedback loops). `loop()` polls the underlying handler. + +> Note: existing `MQTTAsyncClient`, `WebSocketServer`, `HTTPRequestHandler`, `UARTCommandHandler` +> are **not deleted** — they remain in place until Stage 4 wires the router. The transports wrap them. + +### Stage 4 — CommunicationRouter Simplification ✅ COMPLETE + +- [x] Replace router internals with `CommandBus` + transport array +- [x] Implement `registerHandlers()` — called from `begin()` after all setters are applied +- [x] `setHealthMonitorReference()` + `setOutputManagerReference()` added; main.cpp updated +- [x] All setters now called **before** `begin()` in main.cpp so registerHandlers() has full dependency set +- [x] Old `CommandHandler` marked `// DEPRECATED` — kept on disk until confirmed stable in production +- [x] `HTTPRequestHandler` no longer instantiated in router (replaced by `HTTPTransport`) +- [x] `CommunicationRouter` public API unchanged — BellEngine, Player, Telemetry callers need no changes + +### Stage 5 — Legacy Adapter ✅ COMPLETE + +- [x] `LegacyAdapter.hpp` — `translateLegacyEnvelope()` declaration + deletion instructions +- [x] `LegacyAdapter.cpp` — full translation table: 35 mappings covering all v1 command/action pairs + - Simple 1-to-1: `ping`, `identify`, `playback` + - Action-based: `file_manager`, `relay_setup`, `clock_setup`, `system_info`, `system` + - Boolean splits: `clock_setup → set_enabled` → `clock.enable`/`clock.disable`; `system → set_mqtt_enabled` → `mqtt.enable`/`mqtt.disable` + - Retired command: `sync_time_to_lcd` → `system.get_time` (LCD now uses request/response) +- [x] `CommandBus::dispatch()` — single `if (version == 1)` gate before registry lookup; zero transport changes - [ ] Test with FlutterFlow app sending `"v": 1` - [ ] Set cutover date — delete adapter in one clean PR -### Stage 6 — SettingsWebServer Integration (4th Transport) -- [ ] Create `WebServerTransport` skeleton -- [ ] Absorb `SettingsWebServer` into `WebServerTransport` -- [ ] Settings page form POSTs route through `CommandBus` -- [ ] All 4 transports share single command pipeline +### Stage 6 — SettingsWebServer Integration (4th Transport) ✅ COMPLETE + +- [x] Create `WebServerTransport` (implements `ITransport`) +- [x] Absorb `SettingsWebServer` into `WebServerTransport` — old class is dead code +- [x] `POST /api/set-mode` → `network.set_config { permanent_ap_mode }` via CommandBus +- [x] `POST /api/reboot` → `system.restart` via CommandBus +- [x] `NetworkHandler::handleSetConfig` extended to handle `permanent_ap_mode` field +- [x] `WebServerTransport` registered in `CommunicationRouter::begin()` and on the bus +- [x] `SettingsWebServer` member removed from router — `src/SettingsWebServer/` is deletable in one PR + +> `src/SettingsWebServer/SettingsPage.h` still included by `WebServerTransport.cpp` for the PROGMEM HTML template. +> Move or inline it when deleting the old directory. --- diff --git a/src/Communication/CommandBus/CommandBus.cpp b/src/Communication/CommandBus/CommandBus.cpp index 2c94199..c10f629 100644 --- a/src/Communication/CommandBus/CommandBus.cpp +++ b/src/Communication/CommandBus/CommandBus.cpp @@ -1,4 +1,5 @@ #include "CommandBus.hpp" +#include "LegacyAdapter.hpp" #include "../../Logging/Logging.hpp" #define TAG "CommandBus" @@ -32,6 +33,14 @@ void CommandBus::addTransport(ITransport* transport) { // --------------------------------------------------------------------------- void CommandBus::dispatch(CommandEnvelope& envelope) { + // Translate legacy v1 envelopes before registry lookup. + // No-op for v2 — the check is a single integer compare. + if (envelope.version == 1) { + LOG_DEBUG(TAG, "v1 envelope received — translating '%s'", envelope.command.c_str()); + translateLegacyEnvelope(envelope); + LOG_DEBUG(TAG, "v1 translation result: '%s'", envelope.command.c_str()); + } + auto it = _registry.find(envelope.command); if (it == _registry.end()) { diff --git a/src/Communication/CommandBus/LegacyAdapter.cpp b/src/Communication/CommandBus/LegacyAdapter.cpp new file mode 100644 index 0000000..ece13ab --- /dev/null +++ b/src/Communication/CommandBus/LegacyAdapter.cpp @@ -0,0 +1,133 @@ +#include "LegacyAdapter.hpp" + +// --------------------------------------------------------------------------- +// Translation tables +// +// SIMPLE_MAP: v1 cmd (no action) → v2 cmd +// ACTION_MAP: v1 "cmd:action" compound key → v2 cmd +// --------------------------------------------------------------------------- + +// Compound key helper — "cmd\0action" stored as two concatenated const char* pairs +struct ActionEntry { + const char* cmd; + const char* action; + const char* v2; +}; + +static const ActionEntry ACTION_MAP[] = { + // file_manager + { "file_manager", "list_melodies", "files.list" }, + { "file_manager", "download_melody", "files.download" }, + { "file_manager", "delete_melody", "files.delete" }, + + // relay_setup + { "relay_setup", "set_timings", "relay.set_durations" }, + { "relay_setup", "set_outputs", "relay.set_outputs" }, + + // clock_setup — generic actions (enabled split handled separately below) + { "clock_setup", "set_outputs", "clock.set_outputs" }, + { "clock_setup", "set_timings", "clock.set_timings" }, + { "clock_setup", "set_alerts", "clock.set_alerts" }, + { "clock_setup", "set_backlight", "clock.set_backlight" }, + { "clock_setup", "set_silence", "clock.set_silence" }, + { "clock_setup", "set_rtc_time", "clock.set_time" }, + { "clock_setup", "set_physical_clock_time", "clock.set_face" }, + { "clock_setup", "pause_clock_updates", "clock.pause" }, + { "clock_setup", "resume_clock_updates", "clock.resume" }, + + // system_info + { "system_info", "report_status", "system.status" }, + { "system_info", "get_device_time", "system.get_time" }, + { "system_info", "get_clock_time", "clock.get_face" }, + { "system_info", "get_firmware_status", "firmware.status" }, + { "system_info", "network_info", "network.info" }, + { "system_info", "get_full_settings", "system.get_settings" }, + // sync_time_to_lcd retired — LCD now uses request/response model + { "system_info", "sync_time_to_lcd", "system.get_time" }, + + // system + { "system", "status", "system.status" }, + { "system", "reset_defaults", "system.factory_reset" }, + { "system", "commit_firmware", "firmware.commit" }, + { "system", "rollback_firmware", "firmware.rollback" }, + { "system", "get_firmware_status", "firmware.status" }, + { "system", "set_network_config", "network.set_config" }, + { "system", "set_serial_log_level", "log.set_serial" }, + { "system", "set_sd_log_level", "log.set_sd" }, + { "system", "set_mqtt_log_level", "log.set_mqtt" }, + { "system", "restart", "system.restart" }, + { "system", "reboot", "system.restart" }, + { "system", "force_update", "ota.update" }, + { "system", "custom_update", "ota.custom" }, +}; + +static constexpr size_t ACTION_MAP_SIZE = sizeof(ACTION_MAP) / sizeof(ACTION_MAP[0]); + +// v1 top-level commands with no "action" field that map 1-to-1 +struct SimpleEntry { + const char* v1; + const char* v2; +}; + +static const SimpleEntry SIMPLE_MAP[] = { + { "ping", "ping" }, + { "identify", "identify" }, + { "playback", "playback" }, +}; + +static constexpr size_t SIMPLE_MAP_SIZE = sizeof(SIMPLE_MAP) / sizeof(SIMPLE_MAP[0]); + +// --------------------------------------------------------------------------- + +void translateLegacyEnvelope(CommandEnvelope& envelope) { + const String& cmd = envelope.command; + + // ── 1. Simple 1-to-1 commands (no action needed) ─────────────────────── + for (size_t i = 0; i < SIMPLE_MAP_SIZE; ++i) { + if (cmd == SIMPLE_MAP[i].v1) { + envelope.command = SIMPLE_MAP[i].v2; + envelope.version = 2; + return; + } + } + + // ── 2. Commands that require an "action" field ────────────────────────── + // Extract action from contents, strip it, then look up in ACTION_MAP. + const char* action = envelope.contents["action"] | ""; + + // ── 2a. Special case: clock_setup → set_enabled (boolean split) ───────── + if (cmd == "clock_setup" && strcmp(action, "set_enabled") == 0) { + bool enabled = envelope.contents["enabled"] | false; + envelope.command = enabled ? "clock.enable" : "clock.disable"; + envelope.contents.remove("action"); + envelope.contents.remove("enabled"); + envelope.version = 2; + return; + } + + // ── 2b. Special case: system → set_mqtt_enabled (boolean split) ───────── + if (cmd == "system" && strcmp(action, "set_mqtt_enabled") == 0) { + bool enabled = envelope.contents["enabled"] | false; + envelope.command = enabled ? "mqtt.enable" : "mqtt.disable"; + envelope.contents.remove("action"); + envelope.contents.remove("enabled"); + envelope.version = 2; + return; + } + + // ── 2c. General action-based lookup ───────────────────────────────────── + if (action[0] != '\0') { + for (size_t i = 0; i < ACTION_MAP_SIZE; ++i) { + if (cmd == ACTION_MAP[i].cmd && strcmp(action, ACTION_MAP[i].action) == 0) { + envelope.command = ACTION_MAP[i].v2; + envelope.contents.remove("action"); + envelope.version = 2; + return; + } + } + } + + // ── 3. Unknown / unmapped — leave command unchanged so the bus returns ── + // its normal "Unknown command: ..." error. Mark as v2 so we don't loop. + envelope.version = 2; +} diff --git a/src/Communication/CommandBus/LegacyAdapter.hpp b/src/Communication/CommandBus/LegacyAdapter.hpp new file mode 100644 index 0000000..18f4943 --- /dev/null +++ b/src/Communication/CommandBus/LegacyAdapter.hpp @@ -0,0 +1,33 @@ +#pragma once + +// --------------------------------------------------------------------------- +// LegacyAdapter — v1 → v2 command translation +// +// When a client sends { "v": 1 } (or omits "v"), the envelope arrives here +// before reaching the CommandBus registry. The adapter maps the old flat/ +// umbrella command shape to the new namespaced v2 command. +// +// Translation logic: +// 1. If the v1 message has an "action" field inside contents, combine +// cmd + action → v2 flat command name, then strip "action" from contents. +// 2. If no action, map the top-level cmd name directly (e.g. "ping" → "ping"). +// 3. Special cases: +// - clock_setup → set_enabled uses contents["enabled"] bool to pick +// clock.enable vs clock.disable +// - system → set_mqtt_enabled uses contents["enabled"] bool to pick +// mqtt.enable vs mqtt.disable +// - system_info → sync_time_to_lcd is remapped to system.get_time +// (LCD now uses request/response; old push model retired) +// +// To delete legacy support in one PR: remove the #include and the single +// call in CommandBus::dispatch(), then delete this file. +// --------------------------------------------------------------------------- + +#include "CommandEnvelope.hpp" + +// Translate an envelope whose version == 1 into its v2 equivalent. +// Mutates envelope.command and (where needed) envelope.contents in place. +// Sets envelope.version = 2 on return. +// No-op if the command is already valid v2 (unknown v1 commands are left +// unchanged so the bus returns a proper "Unknown command" error). +void translateLegacyEnvelope(CommandEnvelope& envelope); diff --git a/src/Communication/CommandHandler/CommandHandler.hpp b/src/Communication/CommandHandler/CommandHandler.hpp index e185142..8c41dd1 100644 --- a/src/Communication/CommandHandler/CommandHandler.hpp +++ b/src/Communication/CommandHandler/CommandHandler.hpp @@ -1,6 +1,11 @@ /* + * ⚠️ DEPRECATED — Stage 4 complete. + * This class is no longer used by CommunicationRouter. + * It will be deleted once Stage 4 is confirmed stable in production. + * New path: CommandBus + domain handlers under Communication/Handlers/ + * * ═══════════════════════════════════════════════════════════════════════════════════ - * COMMANDHANDLER.HPP - Unified Command Processing + * COMMANDHANDLER.HPP - Unified Command Processing (DEPRECATED) * ═══════════════════════════════════════════════════════════════════════════════════ * * ⚙️ COMMAND ROUTER AND PROCESSOR ⚙️ diff --git a/src/Communication/CommunicationRouter/CommunicationRouter.cpp b/src/Communication/CommunicationRouter/CommunicationRouter.cpp index a194bf9..d480259 100644 --- a/src/Communication/CommunicationRouter/CommunicationRouter.cpp +++ b/src/Communication/CommunicationRouter/CommunicationRouter.cpp @@ -1,10 +1,14 @@ /* - * COMMUNICATIONROUTER.CPP - Communication Router Implementation + * CommunicationRouter.cpp — Stage 4 refactor + * + * Wires CommandBus + transports + handlers. + * Old CommandHandler is no longer used. */ #include "CommunicationRouter.hpp" #define TAG "CommRouter" + #include "../../ConfigManager/ConfigManager.hpp" #include "../../OTAManager/OTAManager.hpp" #include "../../Networking/Networking.hpp" @@ -13,146 +17,140 @@ #include "../../FileManager/FileManager.hpp" #include "../../TimeKeeper/TimeKeeper.hpp" #include "../../FirmwareValidator/FirmwareValidator.hpp" +#include "../../Telemetry/Telemetry.hpp" +#include "../../HealthMonitor/HealthMonitor.hpp" +#include "../../OutputManager/OutputManager.hpp" + +// Domain handlers +#include "../Handlers/PlaybackHandler/PlaybackHandler.hpp" +#include "../Handlers/RelayHandler/RelayHandler.hpp" +#include "../Handlers/ClockHandler/ClockHandler.hpp" +#include "../Handlers/SystemHandler/SystemHandler.hpp" +#include "../Handlers/FirmwareHandler/FirmwareHandler.hpp" +#include "../Handlers/NetworkHandler/NetworkHandler.hpp" +#include "../Handlers/FileHandler/FileHandler.hpp" +#include "../Handlers/LoggingHandler/LoggingHandler.hpp" +#include "../Handlers/TelemetryHandler/TelemetryHandler.hpp" +#include "../Handlers/MQTTHandler/MQTTHandler.hpp" + +// ───────────────────────────────────────────────────────────────────────────── +// Constructor +// ───────────────────────────────────────────────────────────────────────────── CommunicationRouter::CommunicationRouter(ConfigManager& configManager, - OTAManager& otaManager, - Networking& networking, - AsyncWebServer& server, - AsyncWebSocket& webSocket, - AsyncUDP& udp) + 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) + // Underlying protocol objects , _mqttClient(configManager, networking) , _clientManager() , _wsServer(webSocket, _clientManager) - , _commandHandler(configManager, otaManager) - , _httpHandler(server, configManager) , _uartHandler() - , _settingsServer(server, configManager, networking) {} + // New architecture — transports reference the bus + , _bus() + , _mqttTransport(_mqttClient, _bus) + , _wsTransport(_wsServer, _bus) + , _httpTransport(server, _bus, configManager) + , _uartTransport(_uartHandler, _bus) + , _webServerTransport(server, _bus, configManager, networking) +{} CommunicationRouter::~CommunicationRouter() {} +// ───────────────────────────────────────────────────────────────────────────── +// begin() +// ───────────────────────────────────────────────────────────────────────────── + 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! + LOG_INFO(TAG, "Initializing Communication Router v5.0 (CommandBus)"); + + // ── WebSocket ───────────────────────────────────────────────────────────── + LOG_INFO(TAG, "Setting up WebSocket transport..."); _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); - }); + _wsTransport.begin(); + LOG_INFO(TAG, "WebSocket transport initialised (/ws)"); - // 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 - ); + // ── MQTT ───────────────────────────────────────────────────────────────── + LOG_INFO(TAG, "Setting up MQTT transport..."); + _mqttTransport.begin(); - // 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()); + String logTopic = "vesper/" + _configManager.getDeviceUID() + "/logs"; + Logging::setMqttPublishCallback( + [this](const String& topic, const String& payload, int qos) { + _mqttClient.publish(topic, payload, qos, false); + }, + logTopic + ); - // 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); + 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()); - LOG_INFO(TAG, "✅ MQTT client initialized"); - } catch (...) { - LOG_ERROR(TAG, "❌ MQTT initialization failed, but WebSocket is still available"); - } + Logging::setSubsystemMqttLevel("MQTTClient", Logging::NONE); + Logging::setSubsystemMqttLevel("CommRouter", Logging::WARNING); + Logging::setSubsystemMqttLevel("Logger", Logging::NONE); - // 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"); + LOG_INFO(TAG, "MQTT transport initialised"); - // 🔥 Set CommunicationRouter reference for MQTT control commands - _commandHandler.setCommunicationRouterReference(this); - LOG_INFO(TAG, "CommunicationRouter reference set for CommandHandler"); + // ── HTTP ───────────────────────────────────────────────────────────────── + LOG_INFO(TAG, "Setting up HTTP transport..."); + _httpTransport.begin(); + LOG_INFO(TAG, "HTTP transport initialised"); - // Setup command handler response callback - _commandHandler.setResponseCallback([this](const String& response, const CommandHandler::MessageContext& context) { - sendResponse(response, context); - }); + // ── Settings Web Server (4th transport — Stage 6) + LOG_INFO(TAG, "Setting up WebServer transport..."); + _webServerTransport.begin(); + LOG_INFO(TAG, "WebServer transport initialised (/settings)"); - // Initialize HTTP Request Handler - LOG_INFO(TAG, "Setting up HTTP REST API..."); - _httpHandler.begin(); - _httpHandler.setCommandHandlerReference(&_commandHandler); - LOG_INFO(TAG, "✅ HTTP REST API initialized"); + // ── UART ───────────────────────────────────────────────────────────────── + LOG_INFO(TAG, "Setting up UART transport..."); + _uartTransport.begin(); + LOG_INFO(TAG, "UART transport initialised"); - // Initialize Settings Web Server - LOG_INFO(TAG, "Setting up Settings Web Server..."); - _settingsServer.begin(); - LOG_INFO(TAG, "✅ Settings Web Server initialized at /settings"); + // ── Register transports with the bus ───────────────────────────────────── + _bus.addTransport(&_mqttTransport); + _bus.addTransport(&_wsTransport); + _bus.addTransport(&_httpTransport); + _bus.addTransport(&_uartTransport); + _bus.addTransport(&_webServerTransport); - // 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)"); + // ── Register all domain handlers ───────────────────────────────────────── + registerHandlers(); - 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"); + LOG_INFO(TAG, "Communication Router ready — CommandBus active"); } +// ───────────────────────────────────────────────────────────────────────────── +// loop() +// ───────────────────────────────────────────────────────────────────────────── + void CommunicationRouter::loop() { - // Process UART incoming data - _uartHandler.loop(); + _uartTransport.loop(); } +// ───────────────────────────────────────────────────────────────────────────── +// Late-bound reference setters +// ───────────────────────────────────────────────────────────────────────────── + 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); @@ -163,18 +161,92 @@ void CommunicationRouter::setFileManagerReference(FileManager* fm) { 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); + _telemetry = telemetry; } +void CommunicationRouter::setHealthMonitorReference(HealthMonitor* hm) { + _healthMonitor = hm; +} + +void CommunicationRouter::setOutputManagerReference(OutputManager* om) { + _outputManager = om; +} + +// ───────────────────────────────────────────────────────────────────────────── +// registerHandlers() +// ───────────────────────────────────────────────────────────────────────────── + +void CommunicationRouter::registerHandlers() { + // Log any missing optional dependencies so issues surface at boot, not later. + if (!_player) LOG_ERROR(TAG, "registerHandlers: _player is null — PlaybackHandler, RelayHandler, FirmwareHandler, SystemHandler skipped"); + if (!_fileManager) LOG_ERROR(TAG, "registerHandlers: _fileManager is null — FileHandler skipped"); + if (!_timeKeeper) LOG_ERROR(TAG, "registerHandlers: _timeKeeper is null — ClockHandler skipped"); + if (!_firmwareValidator) LOG_ERROR(TAG, "registerHandlers: _firmwareValidator is null — FirmwareHandler skipped"); + if (!_telemetry) LOG_ERROR(TAG, "registerHandlers: _telemetry is null — TelemetryHandler and SystemHandler skipped"); + if (!_healthMonitor) LOG_WARNING(TAG, "registerHandlers: _healthMonitor is null — system.health unavailable"); + if (!_outputManager) LOG_ERROR(TAG, "registerHandlers: _outputManager is null — RelayHandler skipped"); + + // Playback + if (_player) { + _bus.registerHandler(std::make_unique(*_player)); + } + + // Relay + if (_player && _outputManager) { + _bus.registerHandler(std::make_unique(_configManager, *_outputManager, *_player)); + } + + // Clock + if (_timeKeeper) { + _bus.registerHandler(std::make_unique(_configManager, *_timeKeeper)); + } + + // System — requires player, telemetry, healthMonitor, timeKeeper, clientManager + if (_player && _telemetry && _healthMonitor && _timeKeeper) { + _bus.registerHandler(std::make_unique( + _configManager, *_player, *_telemetry, *_healthMonitor, + *_timeKeeper, _clientManager)); + } + + // Firmware / OTA + if (_firmwareValidator && _player) { + _bus.registerHandler(std::make_unique( + *_firmwareValidator, _otaManager, *_player)); + } + + // Network — no optional dependencies + _bus.registerHandler(std::make_unique(_configManager, _networking)); + + // File + if (_fileManager) { + _bus.registerHandler(std::make_unique(*_fileManager)); + } + + // Logging — no optional dependencies + _bus.registerHandler(std::make_unique(_configManager)); + + // Telemetry + if (_telemetry) { + _bus.registerHandler(std::make_unique(*_telemetry)); + } + + // MQTT control (enable / disable) + _bus.registerHandler(std::make_unique(_configManager, _mqttClient)); + + LOG_INFO(TAG, "All domain handlers registered on CommandBus"); +} + +// ───────────────────────────────────────────────────────────────────────────── +// UDP Discovery +// ───────────────────────────────────────────────────────────────────────────── + void CommunicationRouter::setupUdpDiscovery() { uint16_t discoveryPort = _configManager.getNetworkConfig().discoveryPort; if (_udp.listen(discoveryPort)) { @@ -188,13 +260,11 @@ void CommunicationRouter::setupUdpDiscovery() { msg.c_str()); bool shouldReply = false; - if (msg.indexOf("discover") >= 0) { shouldReply = true; } else { StaticJsonDocument<128> req; - DeserializationError err = deserializeJson(req, msg); - if (!err) { + if (!deserializeJson(req, msg)) { shouldReply = (req["op"] == "discover"); } } @@ -202,216 +272,143 @@ void CommunicationRouter::setupUdpDiscovery() { if (!shouldReply) return; StaticJsonDocument<256> doc; - doc["op"] = "discover_reply"; - doc["svc"] = "vesper"; - doc["ver"] = 1; + doc["op"] = "discover_reply"; + doc["svc"] = "vesper"; + doc["ver"] = 1; + doc["name"] = "Proj. Vesper v2.0"; + doc["id"] = _configManager.getDeviceUID(); + doc["ip"] = _networking.getLocalIP(); + doc["port"] = 80; + doc["fw"] = "2.0"; + doc["clients"] = _clientManager.getClientCount(); - 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()); + packet.remoteIP(), packet.remotePort()); }); } else { - LOG_ERROR(TAG, "Failed to start UDP discovery."); + LOG_ERROR(TAG, "Failed to start UDP discovery"); } } +// ───────────────────────────────────────────────────────────────────────────── +// Status +// ───────────────────────────────────────────────────────────────────────────── + bool CommunicationRouter::isMqttConnected() const { return _mqttClient.isConnected(); } bool CommunicationRouter::hasActiveWebSocketClients() const { - return _wsServer.hasClients(); + return _wsTransport.hasClients(); } size_t CommunicationRouter::getWebSocketClientCount() const { - return _wsServer.getClientCount(); + return _wsTransport.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)", + 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"); + 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)", + LOG_WARNING(TAG, "Unhealthy — no active connections (MQTT=%d WS=%d)", isMqttConnected(), hasActiveWebSocketClients()); return false; } - return true; } -void CommunicationRouter::broadcastStatus(const String& statusMessage) { - publishToMqtt(statusMessage); - _wsServer.broadcastToAll(statusMessage); +// ───────────────────────────────────────────────────────────────────────────── +// Broadcast helpers +// ───────────────────────────────────────────────────────────────────────────── + +void CommunicationRouter::broadcastStatus(const String& message) { + publishToMqtt(message); + _wsTransport.broadcast(message); } void CommunicationRouter::broadcastStatus(const JsonDocument& statusJson) { - String statusMessage; - serializeJson(statusJson, statusMessage); - broadcastStatus(statusMessage); + String msg; + serializeJson(statusJson, msg); + broadcastStatus(msg); } void CommunicationRouter::broadcastToMasterClients(const String& message) { - _wsServer.broadcastToMaster(message); + _wsTransport.broadcastToMasters(message); } void CommunicationRouter::broadcastToSecondaryClients(const String& message) { - _wsServer.broadcastToSecondary(message); + _wsTransport.broadcastToSecondary(message); } void CommunicationRouter::broadcastToAllWebSocketClients(const String& message) { - _wsServer.broadcastToAll(message); + _wsTransport.broadcast(message); } void CommunicationRouter::broadcastToAllWebSocketClients(const JsonDocument& message) { - String messageStr; - serializeJson(message, messageStr); - _wsServer.broadcastToAll(messageStr); + String msg; + serializeJson(message, msg); + _wsTransport.broadcast(msg); } 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()); + _mqttClient.publish("", data, 0, false); + LOG_DEBUG(TAG, "Published to MQTT data topic"); } else { - LOG_ERROR(TAG, "MQTT Not Connected! Message Failed: %s", data.c_str()); + LOG_WARNING(TAG, "MQTT not connected — message dropped"); } } -void CommunicationRouter::sendBellOverloadNotification(const std::vector& bellNumbers, - const std::vector& bellLoads, - const String& severity) { - StaticJsonDocument<512> overloadMsg; - overloadMsg["status"] = "INFO"; - overloadMsg["type"] = "bell_overload"; - - JsonArray bellsArray = overloadMsg["payload"]["bells"].to(); - JsonArray loadsArray = overloadMsg["payload"]["loads"].to(); - - for (size_t i = 0; i < bellNumbers.size() && i < bellLoads.size(); i++) { - bellsArray.add(bellNumbers[i] + 1); - loadsArray.add(bellLoads[i]); +// ───────────────────────────────────────────────────────────────────────────── +// Bell overload notification +// ───────────────────────────────────────────────────────────────────────────── + +void CommunicationRouter::sendBellOverloadNotification( + const std::vector& bellNumbers, + const std::vector& bellLoads, + const String& severity) { + + StaticJsonDocument<512> doc; + doc["status"] = "INFO"; + doc["type"] = "bell_overload"; + + JsonArray bellsArr = doc["payload"]["bells"].to(); + JsonArray loadsArr = doc["payload"]["loads"].to(); + + for (size_t i = 0; i < bellNumbers.size() && i < bellLoads.size(); ++i) { + bellsArr.add(bellNumbers[i] + 1); + loadsArr.add(bellLoads[i]); } - - overloadMsg["payload"]["severity"] = severity; - broadcastStatus(overloadMsg); - - LOG_WARNING(TAG, "Bell overload notification sent: %d bells, severity: %s", + doc["payload"]["severity"] = severity; + + broadcastStatus(doc); + LOG_WARNING(TAG, "Bell overload notification sent: %d bells, severity: %s", bellNumbers.size(), severity.c_str()); } +// ───────────────────────────────────────────────────────────────────────────── +// Network state callbacks +// ───────────────────────────────────────────────────────────────────────────── + void CommunicationRouter::onNetworkConnected() { - LOG_DEBUG(TAG, "Network connected - notifying MQTT client"); - _mqttClient.onNetworkConnected(); + LOG_DEBUG(TAG, "Network connected — notifying MQTT transport"); + _mqttTransport.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(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!"); - } + LOG_DEBUG(TAG, "Network disconnected — notifying MQTT transport"); + _mqttTransport.onNetworkDisconnected(); } diff --git a/src/Communication/CommunicationRouter/CommunicationRouter.hpp b/src/Communication/CommunicationRouter/CommunicationRouter.hpp index 33cc8d1..85f2e47 100644 --- a/src/Communication/CommunicationRouter/CommunicationRouter.hpp +++ b/src/Communication/CommunicationRouter/CommunicationRouter.hpp @@ -1,31 +1,15 @@ /* - * ═══════════════════════════════════════════════════════════════════════════════════ - * 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 - * ═══════════════════════════════════════════════════════════════════════════════════ + * CommunicationRouter.hpp — Stage 4 refactor + * + * The router is now a thin coordinator: + * • Owns the CommandBus and four transports (MQTT, WS, HTTP, UART) + * • Owns the underlying legacy protocol objects (MQTTAsyncClient, etc.) + * so the rest of the codebase doesn't need to change + * • Registers all domain handlers in registerHandlers() + * • Exposes the same public API as before so main.cpp is unchanged + * + * The 700-line if/else CommandHandler is no longer used — it stays on disk + * until Stage 4 is proven stable, then gets deleted. */ #pragma once @@ -34,15 +18,22 @@ #include #include #include + +// Underlying protocol objects (still owned here) #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" +// New architecture +#include "../CommandBus/CommandBus.hpp" +#include "../Transport/MQTTTransport/MQTTTransport.hpp" +#include "../Transport/WebSocketTransport/WebSocketTransport.hpp" +#include "../Transport/HTTPTransport/HTTPTransport.hpp" +#include "../Transport/UARTTransport/UARTTransport.hpp" +#include "../Transport/WebServerTransport/WebServerTransport.hpp" + +// Forward declarations — resolved in .cpp class ConfigManager; class OTAManager; class Player; @@ -51,38 +42,49 @@ class Timekeeper; class Networking; class FirmwareValidator; class Telemetry; +class HealthMonitor; +class OutputManager; class CommunicationRouter { public: - explicit CommunicationRouter(ConfigManager& configManager, - OTAManager& otaManager, - Networking& networking, - AsyncWebServer& server, - AsyncWebSocket& webSocket, - AsyncUDP& udp); - + // Same constructor signature as before — main.cpp is unchanged. + 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 loop(); + + // Late-bound references — called by main.cpp after construction. + // registerHandlers() is deferred until begin() is called after all + // setXxxReference() calls have been made. void setPlayerReference(Player* player); void setFileManagerReference(FileManager* fm); void setTimeKeeperReference(Timekeeper* tk); void setFirmwareValidatorReference(FirmwareValidator* fv); void setTelemetryReference(Telemetry* telemetry); + void setHealthMonitorReference(HealthMonitor* hm); + void setOutputManagerReference(OutputManager* om); + + // UDP discovery (called by main.cpp) void setupUdpDiscovery(); - - // Status methods + + // Status bool isMqttConnected() const; bool hasActiveWebSocketClients() const; size_t getWebSocketClientCount() const; bool isHealthy() const; - // Component accessors - MQTTAsyncClient& getMQTTClient() { return _mqttClient; } - UARTCommandHandler& getUARTHandler() { return _uartHandler; } + // Legacy accessors used by other subsystems + MQTTAsyncClient& getMQTTClient() { return _mqttClient; } + UARTCommandHandler& getUARTHandler() { return _uartHandler; } - // Broadcast methods + // Broadcast helpers — called by BellEngine, Player, Telemetry, etc. void broadcastStatus(const String& statusMessage); void broadcastStatus(const JsonDocument& statusJson); void broadcastToMasterClients(const String& message); @@ -90,43 +92,49 @@ public: void broadcastToAllWebSocketClients(const String& message); void broadcastToAllWebSocketClients(const JsonDocument& message); void publishToMqtt(const String& data); - - // Bell overload notification - void sendBellOverloadNotification(const std::vector& bellNumbers, - const std::vector& bellLoads, - const String& severity); - - // Network connection callbacks + + // Bell overload notification (called by Telemetry / BellEngine) + void sendBellOverloadNotification(const std::vector& bellNumbers, + const std::vector& bellLoads, + const String& severity); + + // Network state callbacks (called by Networking) void onNetworkConnected(); void onNetworkDisconnected(); private: - // Dependencies - ConfigManager& _configManager; - OTAManager& _otaManager; - Networking& _networking; + // ── External dependencies (injected) ──────────────────────────────────── + 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; + AsyncUDP& _udp; + + // Late-bound (set via setXxxReference after construction) + Player* _player = nullptr; + FileManager* _fileManager = nullptr; + Timekeeper* _timeKeeper = nullptr; + FirmwareValidator* _firmwareValidator = nullptr; + Telemetry* _telemetry = nullptr; + HealthMonitor* _healthMonitor = nullptr; + OutputManager* _outputManager = nullptr; + + // ── Underlying protocol objects (owned) ───────────────────────────────── + MQTTAsyncClient _mqttClient; + ClientManager _clientManager; + WebSocketServer _wsServer; 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); + + // ── New architecture (owned) ──────────────────────────────────────────── + CommandBus _bus; + MQTTTransport _mqttTransport; + WebSocketTransport _wsTransport; + HTTPTransport _httpTransport; + UARTTransport _uartTransport; + WebServerTransport _webServerTransport; + + // Register all domain handlers onto the bus. + // Called once from begin() after all late-bound references are confirmed. + void registerHandlers(); }; diff --git a/src/Communication/Handlers/NetworkHandler/NetworkHandler.cpp b/src/Communication/Handlers/NetworkHandler/NetworkHandler.cpp index 89826fa..d0a718d 100644 --- a/src/Communication/Handlers/NetworkHandler/NetworkHandler.cpp +++ b/src/Communication/Handlers/NetworkHandler/NetworkHandler.cpp @@ -62,11 +62,23 @@ CommandResult NetworkHandler::handleStatus(const CommandEnvelope& e) { CommandResult NetworkHandler::handleSetConfig(const CommandEnvelope& e) { bool hasHostname = e.contents["hostname"].is(); bool hasStaticIPCfg = e.contents["useStaticIP"].is(); + bool hasAPMode = e.contents["permanent_ap_mode"].is(); - if (!hasHostname && !hasStaticIPCfg) { + if (!hasHostname && !hasStaticIPCfg && !hasAPMode) { return CommandResult::err("network.set_config", "No network parameters provided"); } + // AP mode toggle — handled independently (no IP fields needed). + if (hasAPMode) { + bool enable = e.contents["permanent_ap_mode"].as(); + _configManager.setPermanentAPMode(enable); + _configManager.saveNetworkConfig(); + LOG_INFO(TAG, "Permanent AP mode %s", enable ? "enabled" : "disabled"); + return CommandResult::ok("network.set_config", + enable ? "AP mode saved. Restart to apply." + : "Station mode saved. Restart to apply."); + } + auto& current = _configManager.getNetworkConfig(); bool useStatic = current.useStaticIP; IPAddress ip = current.ip, gateway = current.gateway; diff --git a/src/Communication/ResponseBuilder/ResponseBuilder.cpp b/src/Communication/ResponseBuilder/ResponseBuilder.cpp index 5b27256..dcb9cec 100644 --- a/src/Communication/ResponseBuilder/ResponseBuilder.cpp +++ b/src/Communication/ResponseBuilder/ResponseBuilder.cpp @@ -1,8 +1,25 @@ #include "ResponseBuilder.hpp" +#include "../CommandBus/CommandResult.hpp" #define TAG "ResponseBuilder" #include "../../Logging/Logging.hpp" +String ResponseBuilder::fromResult(const CommandResult& result) { + JsonDocument doc; + doc["status"] = result.isOk() ? "SUCCESS" + : (result.status == CommandResult::Status::INFO ? "INFO" : "ERROR"); + doc["type"] = result.type; + if (!result.payload.isEmpty()) { + doc["message"] = result.payload; + } + if (result.hasData) { + doc["data"] = result.data; + } + String out; + serializeJson(doc, out); + return out; +} + // Static member initialization StaticJsonDocument<512> ResponseBuilder::_responseDoc; diff --git a/src/Communication/ResponseBuilder/ResponseBuilder.hpp b/src/Communication/ResponseBuilder/ResponseBuilder.hpp index 8910297..6ded12b 100644 --- a/src/Communication/ResponseBuilder/ResponseBuilder.hpp +++ b/src/Communication/ResponseBuilder/ResponseBuilder.hpp @@ -45,6 +45,9 @@ #include #include "../../Player/Player.hpp" // For PlayerStatus enum +// Forward declaration — CommandResult.hpp is included in the .cpp only +struct CommandResult; + class ResponseBuilder { public: // Response status types @@ -54,6 +57,10 @@ public: INFO }; + // Factory: serialise a CommandResult into a ready-to-send JSON string. + // Produces the same {"status","type","message"/"data"} envelope used everywhere. + static String fromResult(const CommandResult& result); + // Main response builders static String success(const String& type, const String& payload = ""); static String success(const String& type, const JsonObject& payload); diff --git a/src/Communication/Transport/HTTPTransport/HTTPTransport.cpp b/src/Communication/Transport/HTTPTransport/HTTPTransport.cpp new file mode 100644 index 0000000..ff8d05f --- /dev/null +++ b/src/Communication/Transport/HTTPTransport/HTTPTransport.cpp @@ -0,0 +1,170 @@ +#include "HTTPTransport.hpp" +#include "../../CommandBus/CommandBus.hpp" +#include "../../CommandBus/CommandEnvelope.hpp" +#include "../../CommandBus/CommandResult.hpp" +#include "../../../ConfigManager/ConfigManager.hpp" + +#define TAG "HTTPTransport" +#include "../../../Logging/Logging.hpp" + +HTTPTransport::HTTPTransport(AsyncWebServer& server, CommandBus& bus, ConfigManager& configManager) + : _server(server) + , _bus(bus) + , _configManager(configManager) { +} + +void HTTPTransport::begin() { + // POST /api/command — execute any command + _server.on("/api/command", HTTP_POST, + // Called when body-less POST completes (shouldn't happen, but guard it) + [](AsyncWebServerRequest* request) { + request->send(400, "application/json", + R"({"status":"ERROR","type":"bad_request","message":"Body required"})"); + }, + nullptr, // no upload handler + [this](AsyncWebServerRequest* request, uint8_t* data, size_t len, + size_t index, size_t total) { + // Wait for full body before processing + if (index + len == total) { + handleCommandRequest(request, data, len); + } + } + ); + + // GET /api/ping — lightweight health check + _server.on("/api/ping", HTTP_GET, + [this](AsyncWebServerRequest* request) { + handlePingRequest(request); + } + ); + + // GET /api/status — convenience shortcut for system.status + _server.on("/api/status", HTTP_GET, + [this](AsyncWebServerRequest* request) { + handleStatusRequest(request); + } + ); + + // CORS headers for browser clients + 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"); + + _initialised = true; + LOG_INFO(TAG, "HTTPTransport initialised — POST /api/command, GET /api/ping, GET /api/status"); +} + +void HTTPTransport::loop() { + // AsyncWebServer is fully event-driven; nothing to poll. +} + +bool HTTPTransport::isHealthy() const { + return _initialised; +} + +// --------------------------------------------------------------------------- + +void HTTPTransport::handleCommandRequest(AsyncWebServerRequest* request, + uint8_t* data, size_t len) { + JsonDocument doc; + DeserializationError err = deserializeJson(doc, data, len); + if (err) { + LOG_WARNING(TAG, "JSON parse error: %s", err.c_str()); + sendErrorJson(request, 400, "Invalid JSON"); + return; + } + + const char* cmd = doc["cmd"] | ""; + if (cmd[0] == '\0') { + sendErrorJson(request, 400, "Missing 'cmd' field"); + return; + } + + LOG_DEBUG(TAG, "HTTP CMD: %s", cmd); + + CommandEnvelope envelope; + envelope.transport = CommandEnvelope::Transport::HTTP; + envelope.clientId = 0; + envelope.command = cmd; + envelope.version = doc["v"] | 2; + + if (doc.containsKey("contents")) { + envelope.contents.set(doc["contents"]); + } + + // Capture request pointer. The reply lambda must call request->send() exactly once. + // AsyncWebServer keeps the request alive until we call send() or the connection closes. + envelope.reply = [this, request](const CommandResult& result) { + JsonDocument resp; + resp["status"] = result.isOk() ? "SUCCESS" + : (result.status == CommandResult::Status::INFO ? "INFO" : "ERROR"); + resp["type"] = result.type; + if (!result.payload.isEmpty()) { + resp["message"] = result.payload; + } + if (result.hasData) { + resp["data"] = result.data; + } + String out; + serializeJson(resp, out); + sendJsonResponse(request, 200, out); + }; + + _bus.dispatch(envelope); +} + +void HTTPTransport::handlePingRequest(AsyncWebServerRequest* request) { + LOG_DEBUG(TAG, "Ping request"); + JsonDocument doc; + doc["status"] = "SUCCESS"; + doc["type"] = "pong"; + doc["uptime"] = millis(); + String out; + serializeJson(doc, out); + sendJsonResponse(request, 200, out); +} + +void HTTPTransport::handleStatusRequest(AsyncWebServerRequest* request) { + LOG_DEBUG(TAG, "Status shortcut — dispatching system.status"); + + CommandEnvelope envelope; + envelope.transport = CommandEnvelope::Transport::HTTP; + envelope.clientId = 0; + envelope.command = "system.status"; + envelope.version = 2; + + envelope.reply = [this, request](const CommandResult& result) { + JsonDocument resp; + resp["status"] = result.isOk() ? "SUCCESS" : "ERROR"; + resp["type"] = result.type; + if (!result.payload.isEmpty()) { + resp["message"] = result.payload; + } + if (result.hasData) { + resp["data"] = result.data; + } + String out; + serializeJson(resp, out); + sendJsonResponse(request, 200, out); + }; + + _bus.dispatch(envelope); +} + +// --------------------------------------------------------------------------- + +void HTTPTransport::sendJsonResponse(AsyncWebServerRequest* request, + int code, const String& json) { + request->send(code, "application/json", json); +} + +void HTTPTransport::sendErrorJson(AsyncWebServerRequest* request, + int code, const String& message) { + JsonDocument doc; + doc["status"] = "ERROR"; + doc["type"] = "bad_request"; + doc["message"] = message; + String out; + serializeJson(doc, out); + sendJsonResponse(request, code, out); +} diff --git a/src/Communication/Transport/HTTPTransport/HTTPTransport.hpp b/src/Communication/Transport/HTTPTransport/HTTPTransport.hpp new file mode 100644 index 0000000..d05b5fb --- /dev/null +++ b/src/Communication/Transport/HTTPTransport/HTTPTransport.hpp @@ -0,0 +1,54 @@ +#pragma once + +#include +#include +#include "../ITransport.hpp" + +class CommandBus; +class ConfigManager; + +// --------------------------------------------------------------------------- +// HTTPTransport +// +// ITransport implementation for HTTP — replaces HTTPRequestHandler. +// +// HTTP is now a proper first-class transport with its own identity. +// No more 0xFFFFFFFF fake WebSocket client ID. +// +// Endpoints registered: +// POST /api/command — execute any command via CommandBus +// GET /api/ping — health check (no bus involvement) +// GET /api/status — shortcut: dispatches system.status to the bus +// +// broadcast() is a no-op (HTTP is stateless; no persistent connection to push to). +// +// The reply lambda captures the AsyncWebServerRequest* and sends the HTTP +// response directly — the bus and handlers never see the HTTP layer. +// --------------------------------------------------------------------------- + +class HTTPTransport : public ITransport { +public: + HTTPTransport(AsyncWebServer& server, CommandBus& bus, ConfigManager& configManager); + + void begin() override; + void loop() override; // no-op — AsyncWebServer is event-driven + bool isHealthy() const override; + String name() const override { return "HTTP"; } + + // No persistent connections — broadcast is a no-op. + void broadcast(const String& message) override {} + +private: + AsyncWebServer& _server; + CommandBus& _bus; + ConfigManager& _configManager; + bool _initialised = false; + + // Endpoint handlers + void handleCommandRequest(AsyncWebServerRequest* request, uint8_t* data, size_t len); + void handlePingRequest(AsyncWebServerRequest* request); + void handleStatusRequest(AsyncWebServerRequest* request); + + void sendJsonResponse(AsyncWebServerRequest* request, int code, const String& json); + void sendErrorJson(AsyncWebServerRequest* request, int code, const String& message); +}; diff --git a/src/Communication/Transport/MQTTTransport/MQTTTransport.cpp b/src/Communication/Transport/MQTTTransport/MQTTTransport.cpp new file mode 100644 index 0000000..753b16f --- /dev/null +++ b/src/Communication/Transport/MQTTTransport/MQTTTransport.cpp @@ -0,0 +1,91 @@ +#include "MQTTTransport.hpp" +#include "../../CommandBus/CommandBus.hpp" +#include "../../CommandBus/CommandEnvelope.hpp" +#include "../../CommandBus/CommandResult.hpp" + +#define TAG "MQTTTransport" +#include "../../../Logging/Logging.hpp" + +MQTTTransport::MQTTTransport(MQTTAsyncClient& mqttClient, CommandBus& bus) + : _mqtt(mqttClient) + , _bus(bus) { +} + +void MQTTTransport::begin() { + // Wire up the message callback — any message arriving on the control topic + // is routed through here. + _mqtt.setCallback([this](const String& topic, const String& payload) { + onMessage(topic, payload); + }); + + _mqtt.begin(); + LOG_INFO(TAG, "MQTTTransport initialised"); +} + +void MQTTTransport::loop() { + // AsyncMqttClient drives itself; nothing to poll here. +} + +bool MQTTTransport::isHealthy() const { + return _mqtt.isConnected(); +} + +void MQTTTransport::broadcast(const String& message) { + _mqtt.publish("", message); // MQTTAsyncClient::publish() routes "" → _dataTopic +} + +void MQTTTransport::onNetworkConnected() { + _mqtt.onNetworkConnected(); +} + +void MQTTTransport::onNetworkDisconnected() { + _mqtt.onNetworkDisconnected(); +} + +// --------------------------------------------------------------------------- + +void MQTTTransport::onMessage(const String& topic, const String& payload) { + LOG_DEBUG(TAG, "RX [%s]: %s", topic.c_str(), payload.c_str()); + + JsonDocument doc; + DeserializationError err = deserializeJson(doc, payload); + if (err) { + LOG_WARNING(TAG, "JSON parse error: %s — dropping message", err.c_str()); + return; + } + + // Build the envelope + CommandEnvelope envelope; + envelope.transport = CommandEnvelope::Transport::MQTT; + envelope.clientId = 0; + envelope.command = doc["cmd"].as(); + envelope.version = doc["v"] | 2; + + if (doc.containsKey("contents")) { + envelope.contents.set(doc["contents"]); + } + + if (envelope.command.isEmpty()) { + LOG_WARNING(TAG, "MQTT message missing 'cmd' field — dropping"); + return; + } + + // Reply lambda — publishes the response back to the MQTT data topic + envelope.reply = [this](const CommandResult& result) { + JsonDocument resp; + resp["status"] = result.isOk() ? "SUCCESS" + : (result.status == CommandResult::Status::INFO ? "INFO" : "ERROR"); + resp["type"] = result.type; + if (!result.payload.isEmpty()) { + resp["message"] = result.payload; + } + if (result.hasData) { + resp["data"] = result.data; + } + String out; + serializeJson(resp, out); + _mqtt.publish("", out); + }; + + _bus.dispatch(envelope); +} diff --git a/src/Communication/Transport/MQTTTransport/MQTTTransport.hpp b/src/Communication/Transport/MQTTTransport/MQTTTransport.hpp new file mode 100644 index 0000000..e8f446b --- /dev/null +++ b/src/Communication/Transport/MQTTTransport/MQTTTransport.hpp @@ -0,0 +1,48 @@ +#pragma once + +#include +#include "../ITransport.hpp" +#include "../../MQTTAsyncClient/MQTTAsyncClient.hpp" + +class CommandBus; + +// --------------------------------------------------------------------------- +// MQTTTransport +// +// ITransport wrapper around the existing MQTTAsyncClient. +// +// Responsibilities: +// - Delegates connection lifecycle to MQTTAsyncClient +// - Parses incoming MQTT JSON messages into CommandEnvelopes +// - Injects a reply lambda that publishes the response to the data topic +// - Dispatches to the CommandBus +// - broadcast() publishes to the device data topic (telemetry, events) +// +// The underlying MQTTAsyncClient (and its timers, heartbeat, reconnect logic) +// is unchanged — this transport just owns the bus glue. +// --------------------------------------------------------------------------- + +class MQTTTransport : public ITransport { +public: + MQTTTransport(MQTTAsyncClient& mqttClient, CommandBus& bus); + + void begin() override; + void loop() override; // no-op — AsyncMqttClient is fully async + bool isHealthy() const override; + String name() const override { return "MQTT"; } + + // Publish a pre-serialised JSON string to the device data topic. + // Called by CommandBus::broadcast() for unsolicited events. + void broadcast(const String& message) override; + + // Called by CommunicationRouter when the network connects / disconnects + void onNetworkConnected(); + void onNetworkDisconnected(); + +private: + MQTTAsyncClient& _mqtt; + CommandBus& _bus; + + // Invoked by MQTTAsyncClient's message callback + void onMessage(const String& topic, const String& payload); +}; diff --git a/src/Communication/Transport/UARTTransport/UARTTransport.cpp b/src/Communication/Transport/UARTTransport/UARTTransport.cpp new file mode 100644 index 0000000..003c043 --- /dev/null +++ b/src/Communication/Transport/UARTTransport/UARTTransport.cpp @@ -0,0 +1,105 @@ +#include "UARTTransport.hpp" +#include "../../CommandBus/CommandBus.hpp" +#include "../../CommandBus/CommandEnvelope.hpp" +#include "../../CommandBus/CommandResult.hpp" + +#define TAG "UARTTransport" +#include "../../../Logging/Logging.hpp" + +// --------------------------------------------------------------------------- +// Whitelist +// --------------------------------------------------------------------------- + +const char* const UARTTransport::WHITELIST[] = { + "ping", + "playback", + "clock.pause", + "clock.resume", + "system.get_time", +}; + +const size_t UARTTransport::WHITELIST_SIZE = + sizeof(UARTTransport::WHITELIST) / sizeof(UARTTransport::WHITELIST[0]); + +// --------------------------------------------------------------------------- + +UARTTransport::UARTTransport(UARTCommandHandler& uart, CommandBus& bus) + : _uart(uart) + , _bus(bus) { +} + +void UARTTransport::begin() { + _uart.setCallback([this](JsonDocument& doc) { + onMessage(doc); + }); + + _uart.begin(); + LOG_INFO(TAG, "UARTTransport initialised (whitelist: %u commands)", WHITELIST_SIZE); +} + +void UARTTransport::loop() { + _uart.loop(); +} + +bool UARTTransport::isHealthy() const { + return _uart.isReady(); +} + +void UARTTransport::broadcast(const String& message) { + _uart.send(message); +} + +// --------------------------------------------------------------------------- + +bool UARTTransport::isWhitelisted(const String& command) const { + for (size_t i = 0; i < WHITELIST_SIZE; ++i) { + if (command == WHITELIST[i]) { + return true; + } + } + return false; +} + +void UARTTransport::onMessage(JsonDocument& doc) { + const char* cmd = doc["cmd"] | ""; + if (cmd[0] == '\0') { + LOG_WARNING(TAG, "UART message missing 'cmd' field — dropping"); + return; + } + + if (!isWhitelisted(cmd)) { + LOG_WARNING(TAG, "UART command '%s' not whitelisted — silently dropped", cmd); + return; + } + + LOG_DEBUG(TAG, "UART CMD (whitelisted): %s", cmd); + + CommandEnvelope envelope; + envelope.transport = CommandEnvelope::Transport::UART; + envelope.clientId = 0; + envelope.command = cmd; + envelope.version = doc["v"] | 2; + + if (doc.containsKey("contents")) { + envelope.contents.set(doc["contents"]); + } + + // Reply routes back over UART to the slave + envelope.reply = [this](const CommandResult& result) { + JsonDocument resp; + resp["status"] = result.isOk() ? "SUCCESS" + : (result.status == CommandResult::Status::INFO ? "INFO" : "ERROR"); + resp["type"] = result.type; + if (!result.payload.isEmpty()) { + resp["message"] = result.payload; + } + if (result.hasData) { + resp["data"] = result.data; + } + String out; + serializeJson(resp, out); + _uart.send(out); + }; + + _bus.dispatch(envelope); +} diff --git a/src/Communication/Transport/UARTTransport/UARTTransport.hpp b/src/Communication/Transport/UARTTransport/UARTTransport.hpp new file mode 100644 index 0000000..0337bae --- /dev/null +++ b/src/Communication/Transport/UARTTransport/UARTTransport.hpp @@ -0,0 +1,56 @@ +#pragma once + +#include +#include "../ITransport.hpp" +#include "../../UARTCommandHandler/UARTCommandHandler.hpp" + +class CommandBus; + +// --------------------------------------------------------------------------- +// UARTTransport +// +// ITransport wrapper around the existing UARTCommandHandler. +// +// The UART port talks to a slave LCD/button board. Only a small whitelist of +// commands are accepted from this transport to prevent feedback loops and +// stop a compromised slave from issuing sensitive commands. +// +// Whitelist (v2 — see Communication-Refactor-Plan.md): +// ping — connection check +// playback — play/stop from physical buttons +// clock.pause — button-triggered pause +// clock.resume — button-triggered resume +// system.get_time — LCD requests current time (replaces old push model) +// +// All other commands are silently dropped before they reach the bus. +// +// broadcast() sends to the UART slave (unsolicited events / telemetry). +// For connection-less context this is optional; the slave may ignore messages +// it doesn't request. +// --------------------------------------------------------------------------- + +class UARTTransport : public ITransport { +public: + UARTTransport(UARTCommandHandler& uart, CommandBus& bus); + + void begin() override; + void loop() override; // polls UARTCommandHandler::loop() + bool isHealthy() const override; + String name() const override { return "UART"; } + + // Send a serialised JSON string to the UART slave (newline appended by handler). + void broadcast(const String& message) override; + +private: + UARTCommandHandler& _uart; + CommandBus& _bus; + + // Commands the UART slave is allowed to issue + static const char* const WHITELIST[]; + static const size_t WHITELIST_SIZE; + + bool isWhitelisted(const String& command) const; + + // Invoked by UARTCommandHandler's message callback + void onMessage(JsonDocument& doc); +}; diff --git a/src/Communication/Transport/WebServerTransport/WebServerTransport.cpp b/src/Communication/Transport/WebServerTransport/WebServerTransport.cpp new file mode 100644 index 0000000..c198dae --- /dev/null +++ b/src/Communication/Transport/WebServerTransport/WebServerTransport.cpp @@ -0,0 +1,156 @@ +#include "WebServerTransport.hpp" +#include "../../CommandBus/CommandBus.hpp" +#include "../../CommandBus/CommandEnvelope.hpp" +#include "../../CommandBus/CommandResult.hpp" +#include "../../../ConfigManager/ConfigManager.hpp" +#include "../../../Networking/Networking.hpp" + +#define TAG "WebServerTransport" +#include "../../../Logging/Logging.hpp" + +// HTML template lives alongside the old SettingsWebServer — include from there +// until the old directory is deleted. +#include "../../../SettingsWebServer/SettingsPage.h" + +WebServerTransport::WebServerTransport(AsyncWebServer& server, + CommandBus& bus, + ConfigManager& configManager, + Networking& networking) + : _server(server) + , _bus(bus) + , _configManager(configManager) + , _networking(networking) { +} + +void WebServerTransport::begin() { + // GET /settings — HTML settings page + _server.on("/settings", HTTP_GET, + [this](AsyncWebServerRequest* request) { + handleSettingsPage(request); + } + ); + + // POST /api/set-mode — AP / station toggle + _server.on("/api/set-mode", HTTP_POST, + [this](AsyncWebServerRequest* request) { + handleSetMode(request); + } + ); + + // POST /api/reboot — restart via CommandBus (system.restart) + _server.on("/api/reboot", HTTP_POST, + [this](AsyncWebServerRequest* request) { + handleReboot(request); + } + ); + + _initialised = true; + LOG_INFO(TAG, "WebServerTransport initialised"); + LOG_INFO(TAG, " GET /settings - Settings page"); + LOG_INFO(TAG, " POST /api/set-mode - AP/station toggle"); + LOG_INFO(TAG, " POST /api/reboot - Device restart"); +} + +void WebServerTransport::loop() { + // AsyncWebServer is fully event-driven; nothing to poll. +} + +bool WebServerTransport::isHealthy() const { + return _initialised; +} + +// --------------------------------------------------------------------------- +// Endpoint handlers +// --------------------------------------------------------------------------- + +void WebServerTransport::handleSettingsPage(AsyncWebServerRequest* request) { + LOG_DEBUG(TAG, "Settings page requested"); + request->send(200, "text/html", generateSettingsHTML()); +} + +void WebServerTransport::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, "Mode change requested via web: %s", mode.c_str()); + + if (mode != "ap" && mode != "station") { + request->send(400, "text/plain", "Invalid mode. Use 'ap' or 'station'"); + return; + } + + bool apMode = (mode == "ap"); + + // Route through CommandBus: network.set_config with permanent_ap_mode field. + CommandEnvelope envelope; + envelope.transport = CommandEnvelope::Transport::HTTP; + envelope.clientId = 0; + envelope.command = "network.set_config"; + envelope.version = 2; + envelope.contents["permanent_ap_mode"] = apMode; + + // The reply lambda sends the HTTP response, then triggers a restart. + // We capture by value to be safe (request pointer stays valid until send()). + envelope.reply = [request, apMode](const CommandResult& result) { + if (result.isOk()) { + String msg = apMode + ? "AP mode enabled. Device will reboot in 3 seconds." + : "Station mode enabled. Device will reboot in 3 seconds."; + request->send(200, "text/plain", msg); + delay(3000); + ESP.restart(); + } else { + request->send(500, "text/plain", + String("Failed to set mode: ") + result.payload); + } + }; + + _bus.dispatch(envelope); +} + +void WebServerTransport::handleReboot(AsyncWebServerRequest* request) { + LOG_INFO(TAG, "Reboot requested via web"); + + CommandEnvelope envelope; + envelope.transport = CommandEnvelope::Transport::HTTP; + envelope.clientId = 0; + envelope.command = "system.restart"; + envelope.version = 2; + + // system.restart sends its own response and then reboots. + // For the web client we send a simple text ack before the handler fires. + request->send(200, "text/plain", "Rebooting device in 2 seconds..."); + + envelope.reply = [](const CommandResult&) { + // Response already sent above; restart is handled by SystemHandler. + }; + + _bus.dispatch(envelope); +} + +// --------------------------------------------------------------------------- +// HTML generation +// --------------------------------------------------------------------------- + +String WebServerTransport::generateSettingsHTML() { + bool isAPMode = _networking.isInAPMode(); + String currentIP = _networking.getLocalIP(); + String deviceUID = _configManager.getDeviceUID(); + String fwVersion = _configManager.getFwVersion(); + + String html = String(FPSTR(SETTINGS_PAGE_HTML)); + + 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; +} diff --git a/src/Communication/Transport/WebServerTransport/WebServerTransport.hpp b/src/Communication/Transport/WebServerTransport/WebServerTransport.hpp new file mode 100644 index 0000000..5848075 --- /dev/null +++ b/src/Communication/Transport/WebServerTransport/WebServerTransport.hpp @@ -0,0 +1,58 @@ +#pragma once + +#include +#include +#include "../ITransport.hpp" + +class CommandBus; +class ConfigManager; +class Networking; + +// --------------------------------------------------------------------------- +// WebServerTransport +// +// ITransport implementation for the on-board settings web interface. +// Absorbs SettingsWebServer — Stage 6 of the comms refactor. +// +// Serves the network-mode settings page and routes form actions through +// the CommandBus, giving the settings UI the same command pipeline as +// every other transport. +// +// Endpoints: +// GET /settings — Settings page (HTML) +// POST /api/set-mode — Routes to network.set_ap_mode via CommandBus +// POST /api/reboot — Routes to system.restart via CommandBus +// +// broadcast() is a no-op (web server has no persistent client connections). +// --------------------------------------------------------------------------- + +class WebServerTransport : public ITransport { +public: + WebServerTransport(AsyncWebServer& server, + CommandBus& bus, + ConfigManager& configManager, + Networking& networking); + + void begin() override; + void loop() override; // no-op — AsyncWebServer is event-driven + bool isHealthy() const override; + String name() const override { return "WebServer"; } + + // No persistent connections — broadcast is a no-op. + void broadcast(const String& message) override {} + +private: + AsyncWebServer& _server; + CommandBus& _bus; + ConfigManager& _configManager; + Networking& _networking; + bool _initialised = false; + + // Endpoint handlers + void handleSettingsPage(AsyncWebServerRequest* request); + void handleSetMode(AsyncWebServerRequest* request); + void handleReboot(AsyncWebServerRequest* request); + + // Generates the settings HTML with runtime values substituted. + String generateSettingsHTML(); +}; diff --git a/src/Communication/Transport/WebSocketTransport/WebSocketTransport.cpp b/src/Communication/Transport/WebSocketTransport/WebSocketTransport.cpp new file mode 100644 index 0000000..4d50e42 --- /dev/null +++ b/src/Communication/Transport/WebSocketTransport/WebSocketTransport.cpp @@ -0,0 +1,96 @@ +#include "WebSocketTransport.hpp" +#include "../../CommandBus/CommandBus.hpp" +#include "../../CommandBus/CommandEnvelope.hpp" +#include "../../CommandBus/CommandResult.hpp" + +#define TAG "WebSocketTransport" +#include "../../../Logging/Logging.hpp" + +WebSocketTransport::WebSocketTransport(WebSocketServer& wsServer, CommandBus& bus) + : _ws(wsServer) + , _bus(bus) { +} + +void WebSocketTransport::begin() { + _ws.setCallback([this](uint32_t clientId, const JsonDocument& doc) { + onMessage(clientId, doc); + }); + + _ws.begin(); + LOG_INFO(TAG, "WebSocketTransport initialised"); +} + +void WebSocketTransport::loop() { + // AsyncWebServer drives the event loop; nothing to poll here. +} + +bool WebSocketTransport::isHealthy() const { + return true; // Always healthy — WebSocket server is always listening +} + +void WebSocketTransport::broadcast(const String& message) { + _ws.broadcastToAll(message); +} + +void WebSocketTransport::sendToClient(uint32_t clientId, const String& message) { + _ws.sendToClient(clientId, message); +} + +void WebSocketTransport::broadcastToMasters(const String& message) { + _ws.broadcastToMaster(message); +} + +void WebSocketTransport::broadcastToSecondary(const String& message) { + _ws.broadcastToSecondary(message); +} + +bool WebSocketTransport::hasClients() const { + return _ws.hasClients(); +} + +size_t WebSocketTransport::getClientCount() const { + return _ws.getClientCount(); +} + +// --------------------------------------------------------------------------- + +void WebSocketTransport::onMessage(uint32_t clientId, const JsonDocument& doc) { + const char* cmd = doc["cmd"] | ""; + if (cmd[0] == '\0') { + LOG_WARNING(TAG, "Client #%u: WebSocket message missing 'cmd' field — dropping", clientId); + String err = R"({"status":"ERROR","type":"bad_request","message":"Missing 'cmd' field"})"; + _ws.sendToClient(clientId, err); + return; + } + + LOG_DEBUG(TAG, "Client #%u CMD: %s", clientId, cmd); + + CommandEnvelope envelope; + envelope.transport = CommandEnvelope::Transport::WEBSOCKET; + envelope.clientId = clientId; + envelope.command = cmd; + envelope.version = doc["v"] | 2; + + if (doc.containsKey("contents")) { + envelope.contents.set(doc["contents"]); + } + + // Reply routes back to the originating WebSocket client only + envelope.reply = [this, clientId](const CommandResult& result) { + JsonDocument resp; + resp["status"] = result.isOk() ? "SUCCESS" + : (result.status == CommandResult::Status::INFO ? "INFO" : "ERROR"); + resp["type"] = result.type; + if (!result.payload.isEmpty()) { + resp["message"] = result.payload; + } + if (result.hasData) { + resp["data"] = result.data; + } + String out; + serializeJson(resp, out); + _ws.sendToClient(clientId, out); + }; + + _bus.dispatch(envelope); +} diff --git a/src/Communication/Transport/WebSocketTransport/WebSocketTransport.hpp b/src/Communication/Transport/WebSocketTransport/WebSocketTransport.hpp new file mode 100644 index 0000000..be61e0e --- /dev/null +++ b/src/Communication/Transport/WebSocketTransport/WebSocketTransport.hpp @@ -0,0 +1,53 @@ +#pragma once + +#include +#include "../ITransport.hpp" +#include "../../WebSocketServer/WebSocketServer.hpp" + +class CommandBus; + +// --------------------------------------------------------------------------- +// WebSocketTransport +// +// ITransport wrapper around the existing WebSocketServer. +// +// Responsibilities: +// - Delegates connection lifecycle and client management to WebSocketServer +// - Parses incoming WebSocket JSON messages into CommandEnvelopes +// - Injects a reply lambda that sends the response back to the originating client +// - Dispatches to the CommandBus +// - broadcast() sends to all connected WebSocket clients +// +// The identify command is still handled by SystemHandler (registered on the bus), +// not special-cased here — the transport is protocol-neutral. +// --------------------------------------------------------------------------- + +class WebSocketTransport : public ITransport { +public: + WebSocketTransport(WebSocketServer& wsServer, CommandBus& bus); + + void begin() override; + void loop() override; // no-op — AsyncWebServer is event-driven + bool isHealthy() const override; + String name() const override { return "WebSocket"; } + + // Send to all connected WebSocket clients. + void broadcast(const String& message) override; + + // Targeted send — used by the identify handler and other per-client responses. + void sendToClient(uint32_t clientId, const String& message); + + // Access for CommunicationRouter broadcast helpers + void broadcastToMasters(const String& message); + void broadcastToSecondary(const String& message); + + bool hasClients() const; + size_t getClientCount() const; + +private: + WebSocketServer& _ws; + CommandBus& _bus; + + // Invoked by WebSocketServer's message callback + void onMessage(uint32_t clientId, const JsonDocument& doc); +}; diff --git a/src/main.cpp b/src/main.cpp index 77461a1..eae75d0 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -358,13 +358,17 @@ void setup() // BellEngine already initialized and registered earlier for health validation - // Initialize Communication Manager (now with PubSubClient MQTT) - communication.begin(); + // Initialize Communication Manager + // Set all dependency references BEFORE begin() so that registerHandlers() + // (called inside begin()) can construct every domain handler. communication.setPlayerReference(&player); communication.setFileManagerReference(&fileManager); communication.setTimeKeeperReference(&timekeeper); communication.setFirmwareValidatorReference(&firmwareValidator); communication.setTelemetryReference(&telemetry); + communication.setHealthMonitorReference(&healthMonitor); + communication.setOutputManagerReference(&outputManager); + communication.begin(); player.setDependencies(&communication, &fileManager); player.setBellEngine(&bellEngine); // Connect the beast!