/* * 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" #include "../../Logging/Logging.hpp" #include "../../Player/Player.hpp" #include "../../FileManager/FileManager.hpp" #if HAS_RTC #include "../../TimeKeeper/TimeKeeper.hpp" #endif #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" #if HAS_RTC #include "../Handlers/ClockHandler/ClockHandler.hpp" #include "../Handlers/SystemHandler/SystemHandler.hpp" #endif #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" #if HAS_RF #include "../../RFRemote/RFRemoteHandler.hpp" #endif // ───────────────────────────────────────────────────────────────────────────── // Constructor // ───────────────────────────────────────────────────────────────────────────── CommunicationRouter::CommunicationRouter(ConfigManager& configManager, OTAManager& otaManager, Networking& networking, AsyncWebServer& server, AsyncWebSocket& webSocket, AsyncUDP& udp) : _configManager(configManager) , _otaManager(otaManager) , _networking(networking) , _server(server) , _webSocket(webSocket) , _udp(udp) // Underlying protocol objects , _mqttClient(configManager, networking) , _clientManager() , _wsServer(webSocket, _clientManager) #if HAS_UART , _uartHandler() #endif // New architecture — transports reference the bus , _bus() , _mqttTransport(_mqttClient, _bus) , _wsTransport(_wsServer, _bus) , _httpTransport(server, _bus, configManager) #if HAS_UART , _uartTransport(_uartHandler, _bus) #endif , _webServerTransport(server, _bus, configManager, networking) {} CommunicationRouter::~CommunicationRouter() {} // ───────────────────────────────────────────────────────────────────────────── // begin() // ───────────────────────────────────────────────────────────────────────────── void CommunicationRouter::begin() { LOG_INFO(TAG, "Initializing Communication Router v5.0 (CommandBus)"); // ── WebSocket ───────────────────────────────────────────────────────────── LOG_INFO(TAG, "Setting up WebSocket transport..."); _server.addHandler(&_webSocket); _wsTransport.begin(); LOG_INFO(TAG, "WebSocket transport initialised (/ws)"); // ── MQTT ───────────────────────────────────────────────────────────────── LOG_INFO(TAG, "Setting up MQTT transport..."); _mqttTransport.begin(); String logTopic = "vesper/" + _configManager.getDeviceUID() + "/logs"; Logging::setMqttPublishCallback( [this](const String& topic, const String& payload, int qos) { _mqttClient.publish(topic, payload, qos, false); }, logTopic ); 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()); Logging::setSubsystemMqttLevel("MQTTClient", Logging::NONE); Logging::setSubsystemMqttLevel("CommRouter", Logging::WARNING); Logging::setSubsystemMqttLevel("Logger", Logging::NONE); LOG_INFO(TAG, "MQTT transport initialised"); // ── HTTP ───────────────────────────────────────────────────────────────── LOG_INFO(TAG, "Setting up HTTP transport..."); _httpTransport.begin(); LOG_INFO(TAG, "HTTP transport initialised"); // ── Settings Web Server (4th transport — Stage 6) LOG_INFO(TAG, "Setting up WebServer transport..."); _webServerTransport.begin(); LOG_INFO(TAG, "WebServer transport initialised (/settings)"); // ── UART ───────────────────────────────────────────────────────────────── #if HAS_UART LOG_INFO(TAG, "Setting up UART transport..."); _uartTransport.begin(); LOG_INFO(TAG, "UART transport initialised"); #endif // ── Register transports with the bus ───────────────────────────────────── _bus.addTransport(&_mqttTransport); _bus.addTransport(&_wsTransport); _bus.addTransport(&_httpTransport); #if HAS_UART _bus.addTransport(&_uartTransport); #endif _bus.addTransport(&_webServerTransport); // ── Register all domain handlers ───────────────────────────────────────── registerHandlers(); // ── Wire HealthMonitor alert callback ──────────────────────────────────── if (_healthMonitor) { _healthMonitor->setAlertCallback( [this](const String& subsystem, const String& newState, const String& message) { publishAlert(subsystem, newState, message); } ); LOG_INFO(TAG, "HealthMonitor alert callback registered"); } LOG_INFO(TAG, "Communication Router ready — CommandBus active"); } // ───────────────────────────────────────────────────────────────────────────── // loop() // ───────────────────────────────────────────────────────────────────────────── void CommunicationRouter::loop() { #if HAS_UART _uartTransport.loop(); #endif } // ───────────────────────────────────────────────────────────────────────────── // Late-bound reference setters // ───────────────────────────────────────────────────────────────────────────── void CommunicationRouter::setPlayerReference(Player* player) { _player = player; } void CommunicationRouter::setFileManagerReference(FileManager* fm) { _fileManager = fm; if (fm != nullptr) { Logging::setSdWriteCallback([fm](const String& line) { fm->appendLine("/logs/vesper.log", line); }); LOG_INFO(TAG, "SD log channel registered -> /logs/vesper.log"); } } #if HAS_RTC void CommunicationRouter::setTimeKeeperReference(Timekeeper* tk) { _timeKeeper = tk; } #endif void CommunicationRouter::setFirmwareValidatorReference(FirmwareValidator* fv) { _firmwareValidator = fv; } void CommunicationRouter::setTelemetryReference(Telemetry* telemetry) { _telemetry = telemetry; } void CommunicationRouter::setHealthMonitorReference(HealthMonitor* hm) { _healthMonitor = hm; } void CommunicationRouter::setOutputManagerReference(OutputManager* om) { _outputManager = om; } #if HAS_RF void CommunicationRouter::setRFRemoteReference(RFRemote* rf) { _rfRemote = rf; } #endif // ───────────────────────────────────────────────────────────────────────────── // 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 HAS_RTC if (!_timeKeeper) LOG_ERROR(TAG, "registerHandlers: _timeKeeper is null — ClockHandler skipped"); #endif 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)); } #if HAS_RTC // Clock if (_timeKeeper) { _bus.registerHandler(std::make_unique(_configManager, *_timeKeeper)); } #endif // System — requires player, telemetry, healthMonitor, timeKeeper, clientManager #if HAS_RTC if (_player && _telemetry && _healthMonitor && _timeKeeper) { _bus.registerHandler(std::make_unique( _configManager, *_player, *_telemetry, *_healthMonitor, *_timeKeeper, _clientManager)); } #endif // Firmware / OTA if (_firmwareValidator && _player) { _bus.registerHandler(std::make_unique( *_firmwareValidator, _otaManager, *_player, _configManager)); } // 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)); #if HAS_RF // RF remote control if (_rfRemote) { _bus.registerHandler(std::make_unique(*_rfRemote)); } #endif LOG_INFO(TAG, "All domain handlers registered on CommandBus"); } // ───────────────────────────────────────────────────────────────────────────── // UDP Discovery // ───────────────────────────────────────────────────────────────────────────── void CommunicationRouter::setupUdpDiscovery() { uint16_t discoveryPort = _configManager.getNetworkConfig().discoveryPort; if (_udp.listen(discoveryPort)) { LOG_INFO(TAG, "UDP discovery listening on port %u", discoveryPort); _udp.onPacket([this](AsyncUDPPacket packet) { String msg = String((const char*)packet.data(), packet.length()); LOG_DEBUG(TAG, "UDP from %s:%u -> %s", packet.remoteIP().toString().c_str(), packet.remotePort(), msg.c_str()); bool shouldReply = false; if (msg.indexOf("discover") >= 0) { shouldReply = true; } else { JsonDocument req; if (!deserializeJson(req, msg)) { shouldReply = (req["op"] == "discover"); } } if (!shouldReply) return; JsonDocument doc; doc["op"] = "discover_reply"; doc["svc"] = "vesper"; doc["ver"] = 1; doc["name"] = "Proj. Vesper v2.0"; doc["id"] = _configManager.getDeviceUID(); doc["ip"] = _networking.getLocalIP(); doc["port"] = 80; doc["fw"] = "2.0"; doc["clients"] = _clientManager.getClientCount(); char wsUrl[64]; snprintf(wsUrl, sizeof(wsUrl), "ws://%s:80/ws", _networking.getLocalIP().c_str()); doc["ws"] = wsUrl; String out; serializeJson(doc, out); _udp.writeTo((const uint8_t*)out.c_str(), out.length(), packet.remoteIP(), packet.remotePort()); }); } else { LOG_ERROR(TAG, "Failed to start UDP discovery"); } } // ───────────────────────────────────────────────────────────────────────────── // Status // ───────────────────────────────────────────────────────────────────────────── bool CommunicationRouter::isMqttConnected() const { return _mqttClient.isConnected(); } bool CommunicationRouter::hasActiveWebSocketClients() const { return _wsTransport.hasClients(); } size_t CommunicationRouter::getWebSocketClientCount() const { return _wsTransport.getClientCount(); } bool CommunicationRouter::isHealthy() const { #if HAS_RTC if (!_player || !_timeKeeper) { LOG_WARNING(TAG, "Unhealthy — missing subsystem references (player=%d timeKeeper=%d)", _player != nullptr, _timeKeeper != nullptr); return false; } #else if (!_player) { LOG_WARNING(TAG, "Unhealthy — missing subsystem references (player=%d)", _player != nullptr); return false; } #endif if (!_networking.isConnected()) { LOG_WARNING(TAG, "Unhealthy — no network connection"); return false; } if (!isMqttConnected() && !hasActiveWebSocketClients()) { LOG_WARNING(TAG, "Unhealthy — no active connections (MQTT=%d WS=%d)", isMqttConnected(), hasActiveWebSocketClients()); return false; } return true; } // ───────────────────────────────────────────────────────────────────────────── // Broadcast helpers // ───────────────────────────────────────────────────────────────────────────── void CommunicationRouter::broadcastStatus(const String& message) { publishToMqtt(message); _wsTransport.broadcast(message); } void CommunicationRouter::broadcastStatus(const JsonDocument& statusJson) { String msg; serializeJson(statusJson, msg); broadcastStatus(msg); } void CommunicationRouter::broadcastToMasterClients(const String& message) { _wsTransport.broadcastToMasters(message); } void CommunicationRouter::broadcastToSecondaryClients(const String& message) { _wsTransport.broadcastToSecondary(message); } void CommunicationRouter::broadcastToAllWebSocketClients(const String& message) { _wsTransport.broadcast(message); } void CommunicationRouter::broadcastToAllWebSocketClients(const JsonDocument& message) { String msg; serializeJson(message, msg); _wsTransport.broadcast(msg); } void CommunicationRouter::publishToMqtt(const String& data) { if (_mqttClient.isConnected()) { _mqttClient.publish("", data, 0, false); LOG_DEBUG(TAG, "Published to MQTT data topic"); } else { LOG_WARNING(TAG, "MQTT not connected — message dropped"); } } // ───────────────────────────────────────────────────────────────────────────── // Bell overload notification // ───────────────────────────────────────────────────────────────────────────── void CommunicationRouter::sendBellOverloadNotification( const std::vector& bellNumbers, const std::vector& bellLoads, const String& severity) { JsonDocument 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]); } doc["payload"]["severity"] = severity; broadcastStatus(doc); LOG_WARNING(TAG, "Bell overload notification sent: %d bells, severity: %s", bellNumbers.size(), severity.c_str()); } // ───────────────────────────────────────────────────────────────────────────── // Alert / Info publishing // ───────────────────────────────────────────────────────────────────────────── void CommunicationRouter::publishAlert(const String& subsystem, const String& newState, const String& message) { if (!_mqttClient.isConnected()) return; JsonDocument doc; doc["subsystem"] = subsystem; doc["state"] = newState; if (!message.isEmpty()) { doc["msg"] = message; } String out; serializeJson(doc, out); _mqttClient.publishDirect(_mqttClient.getAlertsTopic(), out, 1, false); LOG_DEBUG(TAG, "Alert published: %s → %s", subsystem.c_str(), newState.c_str()); } void CommunicationRouter::publishInfo(const String& type, const JsonDocument& payload) { if (!_mqttClient.isConnected()) return; JsonDocument doc; doc["type"] = type; if (!payload.isNull()) { doc["payload"] = payload; } String out; serializeJson(doc, out); _mqttClient.publishDirect(_mqttClient.getInfoTopic(), out, 0, false); LOG_DEBUG(TAG, "Info published: %s", type.c_str()); } // ───────────────────────────────────────────────────────────────────────────── // Network state callbacks // ───────────────────────────────────────────────────────────────────────────── void CommunicationRouter::onNetworkConnected() { LOG_DEBUG(TAG, "Network connected — notifying MQTT transport"); _mqttTransport.onNetworkConnected(); } void CommunicationRouter::onNetworkDisconnected() { LOG_DEBUG(TAG, "Network disconnected — notifying MQTT transport"); _mqttTransport.onNetworkDisconnected(); }