# CommunicationRouter ## Summary `CommunicationRouter` is the top-level coordinator for all inbound and outbound communication. It owns the `CommandBus`, all five transport objects (`MQTTTransport`, `WebSocketTransport`, `HTTPTransport`, `UARTTransport`, `WebServerTransport`), and the three underlying protocol driver objects (`MQTTDriver`, `WebSocketDriver`, `UARTDriver`). It also owns `ClientManager`. On `begin()`, it initialises all transports, registers them with the bus, and calls `registerHandlers()` to bind all ten domain handlers to the bus. After that, the router largely gets out of the way: incoming messages are routed internally by the bus, and outbound unsolicited events (status, telemetry, bell strikes) are pushed through the broadcast helpers exposed on this class. All other subsystems that need to send data call into the router rather than touching transports directly. --- ## Public API ### Lifecycle | Method | Description | |--------|-------------| | `CommunicationRouter(ConfigManager&, OTAManager&, Networking&, AsyncWebServer&, AsyncWebSocket&, AsyncUDP&)` | Constructor. Builds all owned objects; does not start any communication. | | `void begin()` | Initialises all transports, registers them with the bus, calls `registerHandlers()`. Must be called after all `setXxxReference()` calls. | | `void loop()` | Forwards to `UARTTransport::loop()` to poll UART input. Call from `main.cpp` loop. | ### Late-bound references (call before `begin()`) | Method | Description | |--------|-------------| | `void setPlayerReference(Player*)` | Required for PlaybackHandler, RelayHandler, FirmwareHandler, SystemHandler. | | `void setFileManagerReference(FileManager*)` | Required for FileHandler and for `logs.list`/`logs.download` on LoggingHandler; also wires the day-rotated SD log channel into `Logging` (`/logs/YYYY-MM-DD.log`, capped at `SD_LOG_MAX_TOTAL_BYTES` — 512KB — across the directory). | | `void setTimeKeeperReference(Timekeeper*)` | Required for ClockHandler, SystemHandler. | | `void setFirmwareValidatorReference(FirmwareValidator*)` | Required for FirmwareHandler. | | `void setTelemetryReference(Telemetry*)` | Required for TelemetryHandler, SystemHandler. | | `void setHealthMonitorReference(HealthMonitor*)` | Required for SystemHandler (`system.health`). | | `void setOutputManagerReference(OutputManager*)` | Required for RelayHandler. | ### Status | Method | Description | |--------|-------------| | `bool isMqttConnected() const` | True if `MQTTDriver` has an active broker connection. | | `bool hasActiveWebSocketClients() const` | True if at least one WebSocket client is connected. | | `size_t getWebSocketClientCount() const` | Number of currently connected WebSocket clients. | | `bool isHealthy() const` | True if network is up and at least one of MQTT or WebSocket is active. | ### Broadcast helpers (called by other subsystems) | Method | Description | |--------|-------------| | `void broadcastStatus(const String& msg)` | Sends raw string to MQTT data topic and all WebSocket clients. | | `void broadcastStatus(const JsonDocument& json)` | Serialises JSON then calls the string overload. | | `void broadcastToMasterClients(const String& msg)` | WebSocket only — master-classified clients. | | `void broadcastToSecondaryClients(const String& msg)` | WebSocket only — secondary-classified clients. | | `void broadcastToAllWebSocketClients(const String& msg)` | All WebSocket clients. | | `void broadcastToAllWebSocketClients(const JsonDocument& msg)` | Serialises then sends to all WebSocket clients. | | `void publishToMqtt(const String& data)` | Publishes to the device data topic. No-op if MQTT is not connected. | | `void sendBellOverloadNotification(const std::vector& bells, const std::vector& loads, const String& severity)` | Builds and broadcasts a structured `bell_overload` INFO event. | | `void publishAlert(const String& subsystem, const String& newState, const String& message)` | Publishes a subsystem state-change event to `vesper/{uid}/status/alerts` (QoS 1). `newState` is one of `"WARNING"`, `"CRITICAL"`, `"FAILED"`, or `"CLEARED"`. Called automatically by the HealthMonitor alert callback registered in `begin()`, and by `reportBootReasonOnce()` for fault reset reasons. No-op if MQTT is not connected. | | `void publishInfo(const String& type, const JsonDocument& payload)` | Publishes a general device state event to `vesper/{uid}/status/info` (QoS 0). No-op if MQTT is not connected. Used for e.g. `"boot_reason"` events on expected resets. | ### Network callbacks (called by Networking) | Method | Description | |--------|-------------| | `void onNetworkConnected()` | Forwards to `MQTTTransport`, which triggers the MQTT connection stabilisation timer. | | `void onNetworkDisconnected()` | Forwards to `MQTTTransport` to stop heartbeat and abort pending reconnects. | ### Legacy accessors | Method | Description | |--------|-------------| | `MQTTDriver& getMQTTClient()` | Direct access to the MQTT driver; used by `Logging` to set up the MQTT log channel. | | `UARTDriver& getUARTHandler()` | Direct access to the UART driver (currently not used outside the router). | ### UDP Discovery | Method | Description | |--------|-------------| | `void setupUdpDiscovery()` | Starts listening on the configured discovery port. Replies to UDP `"discover"` packets with a JSON `discover_reply` payload containing IP, WebSocket URL, firmware version, and client count. | --- ## Initialization In `main.cpp`, the router is constructed as a global alongside the other subsystems: ```cpp CommunicationRouter communication(configManager, otaManager, networking, server, ws, udp); ``` Before calling `begin()`, all late-bound references must be set: ```cpp communication.setPlayerReference(&player); communication.setFileManagerReference(&fileManager); communication.setTimeKeeperReference(&timekeeper); communication.setFirmwareValidatorReference(&firmwareValidator); communication.setTelemetryReference(&telemetry); communication.setHealthMonitorReference(&healthMonitor); communication.setOutputManagerReference(&outputManager); communication.begin(); ``` If any required reference is null when `registerHandlers()` runs (inside `begin()`), the corresponding handler(s) are skipped and an `LOG_ERROR` is emitted. The bus still starts; commands for missing handlers return "Unknown command". `AsyncWebServer::begin()` is **not** called inside `CommunicationRouter::begin()`. It is started from the network-connected callback in `main.cpp` to avoid conflicting with WiFiManager's captive portal on port 80. --- ## Dependencies - `ConfigManager` — MQTT config, network config, log levels, device UID - `OTAManager` — passed to `FirmwareHandler` - `Networking` — passed to `NetworkHandler`; used for health check and UDP discovery - `AsyncWebServer` / `AsyncWebSocket` / `AsyncUDP` — passed to transports - All domain handler dependencies: `Player`, `FileManager`, `Timekeeper`, `FirmwareValidator`, `Telemetry`, `HealthMonitor`, `OutputManager` - Libraries: `ESPAsyncWebServer`, `ArduinoJson`, `AsyncUDP` --- ## Gotchas / Notes - **Order matters**: All `setXxxReference()` calls must happen before `begin()`. `registerHandlers()` is called at the end of `begin()` and will silently omit handlers for any null reference. - **`server.begin()` is deferred**: The `AsyncWebServer` is not started inside `begin()` — it is started in the `onNetworkConnected` callback in `main.cpp`. This prevents a port 80 conflict when WiFiManager's captive portal is active. - **`loop()` must be called**: `UARTTransport` is the only transport that requires polling. `CommunicationRouter::loop()` delegates to it. All other transports are fully event-driven. - **MQTT log suppression**: During `begin()`, the subsystem MQTT log levels for `"MQTTClient"` and `"CommRouter"` are explicitly suppressed to `NONE` and `WARNING` respectively to prevent feedback loops when MQTT is used as a log sink. - **Boot reason reporting**: `begin()` registers a one-shot `onConnect` callback on `MQTTDriver` (`reportBootReasonOnce()`) that fires the first time MQTT connects after startup (including the very first connection). It reads `Telemetry::getResetReasonString()`/`isFaultReset()` and routes to `publishAlert` (fault reasons: panic, watchdog, brownout) or `publishInfo` (expected reasons: power-on, software reset, deep sleep wake). Guarded by `_bootReasonReported` so it only fires once per boot, not on every reconnect. - **Broadcast vs CommandBus broadcast**: The `broadcastXxx()` helpers on this class send raw pre-serialised strings. `CommandBus::broadcast()` serialises a `CommandResult` and fans it out. They are separate paths; subsystems outside the communication layer use the router's helpers. - **Handler skipping is silent to clients**: If a reference is null and a handler is not registered, the bus returns `{"status":"ERROR","type":"unknown","message":"Unknown command: ..."}`. There is no boot-time safeguard beyond the `LOG_ERROR` in `registerHandlers()`.