Files
project-vesper/src/Communication/CommunicationRouter/README.md
T
bonaminandClaude Sonnet 5 391ecb63fc feat(MQTT): rebuild topic spec to v2 (F-062)
Full MQTT topic rebuild per docs/reference/vesper_mqtt_topic_spec_v2.md.
Only the MQTT transport path changed — WebSocket, HTTP, and UART are untouched.

- control/command (in) + control/ack (out, strictly replies) replace the old
  control/data pair; new control/reports for critical unsolicited events
  (bell overload) that don't belong on the strictly-reply ack channel
- status/playback split out for playback transitions only
- status/alerts + status/info renamed to system/alerts + system/info, both
  now correctly retained; new system/logs and system/metrics (diagnostics
  report moved here from system/info, gained bell strike/heat data)
- LWT registered for the first time — status/heartbeat gets
  {"state":"offline","ok":false} on an unclean disconnect; graceful
  disconnect (mqtt.disable) announces offline explicitly since LWT doesn't
  fire on a clean disconnect
- heartbeat payload flattened, gains independently-derived state/ok fields
  (via a new MQTTDriver::setStateProvider() wired from Player+HealthMonitor)
- optional req_id correlation added bus-wide (CommandEnvelope/CommandResult),
  not MQTT-only, since any transport with multiple senders sharing one
  channel has the same problem. Always optional — v1 clients unaffected.
- per-topic ON/OFF switches (ConfigManager::MqttTopicConfig, 8 flags) as
  sub-switches under the existing mqtt.enable/disable master switch, so a
  device can breathe by disabling topics it doesn't need. New
  mqtt.get_topics/mqtt.set_topics commands; command switch applies live.

Bumped to v2.2.0. Verified: pio run -e vesper-std-v1 -e agnus-v1 both build clean.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-21 10:48:36 +03:00

14 KiB

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/publish helpers exposed on this class — WS-only broadcast helpers for WebSocket, and dedicated publishXxx() methods for each MQTT v2 topic (see docs/reference/vesper_mqtt_topic_spec_v2.md). 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) WebSocket-only fan-out (all clients). No longer also publishes to MQTT — see the dedicated topic methods below for the MQTT equivalents.
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 sendBellOverloadNotification(const std::vector<uint8_t>& bells, const std::vector<uint16_t>& loads, const String& severity) WS clients get the existing bell_overload INFO event via broadcastStatus(). MQTT clients get the same data via publishReport("bell_overload", ...) on control/reports instead.
void publishPlayback(const String& action, uint32_t timeElapsedSec, uint64_t projectedRunTimeMs) Publishes a playback transition to vesper/{uid}/status/playback (QoS 1, retained). Called by Player::setStatus() on every transition, alongside the existing WS broadcastStatus() call. Gated by the playback topic switch.
void publishReport(const String& type, const JsonDocument& payload) Publishes a critical, unsolicited, time-sensitive event to vesper/{uid}/control/reports (QoS 1, not retained). Gated by the reports topic switch.
void publishAlert(const String& subsystem, const String& newState, const String& message) Publishes a subsystem state-change event to vesper/{uid}/system/alerts (QoS 1, retained until cleared). newState is one of "WARNING", "CRITICAL", "FAILED", or "CLEARED". Called automatically by the HealthMonitor alert callback registered in begin(), and by reportBootOnce() for fault reset reasons. No-op if MQTT is not connected or the alerts topic switch is off.
void publishInfo(const String& type, const JsonDocument& payload) Publishes a general device state event to vesper/{uid}/system/info (QoS 1, retained). No-op if MQTT is not connected or the info topic switch is off. Used for e.g. the "boot_report" event published once per boot — see below.
void publishMetrics(const JsonDocument& payload) Publishes structured telemetry to vesper/{uid}/system/metrics (QoS 0, not retained). Used by the 5-minute diagnostics report — see below. Gated by the metrics topic switch.

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:

CommunicationRouter communication(configManager, otaManager, networking, server, ws, udp);

Before calling begin(), all late-bound references must be set:

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".

begin() also registers MQTTDriver::setStateProvider() — a lambda that reads _player/_healthMonitor at call time (not registration time) to derive the heartbeat's state/ok fields. Because _player/_healthMonitor are late-bound, this lambda safely returns state="booting", ok=true if called before setPlayerReference()/setHealthMonitorReference() run — in practice this never happens, since the heartbeat timer only starts once MQTT connects, well after main.cpp finishes wiring all references.

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 reporting: begin() registers a one-shot onConnect callback on MQTTDriver (reportBootOnce()) that fires the first time MQTT connects after startup (including the very first connection). Guarded by _bootReasonReported so it only fires once per boot, not on every reconnect. It does two things:
    1. If Telemetry::isFaultReset() is true (panic, watchdog, brownout), publishes the existing fault alert via publishAlert("System", "WARNING", "Device reset due to fault: " + reason) — unchanged behavior/topic from before.
    2. Always — fault or not — publishes a consolidated "boot_report" event via publishInfo to vesper/{uid}/system/info:
      {
        "type": "boot_report",
        "boot_count": 47,
        "reset_reason": "PANIC",
        "is_fault": true,
        "free_heap": 187234,
        "crash": {
          "task": "TelemetryTask",
          "pc": 1074111832,
          "exc_cause": 1,
          "exc_vaddr": 0
        }
      }
      
      boot_count is Telemetry::getLifetimeBootCount() — see Telemetry's Boot tracking section for why this is a separate counter from FirmwareValidator's NVS boot_count. The crash object is present only when a coredump was found for the crash that caused this boot (CrashReport::available == true) — omitted entirely on a clean/expected reset, or when no coredump was captured for a fault reset (e.g. a brownout, which doesn't produce one).
  • Diagnostics/metrics reporting: loop() calls reportDiagnosticsIfDue() every main-loop iteration, which no-ops until DIAGNOSTICS_REPORT_INTERVAL_MS (5 minutes, Telemetry.hpp) has elapsed and _telemetry is set. Unlike reportBootOnce() (a one-shot MQTT-onConnect callback), this is a plain millis()-diff check — same style as Telemetry's own RUNTIME_FLUSH_INTERVAL_MS check — so it fires on a fixed wall-clock cadence regardless of MQTT connection churn (a no-op publishMetrics() call if disconnected). Publishes a consolidated payload to vesper/{uid}/system/metrics (not wrapped in a "type" envelope — the topic itself is the discriminator):
    {
      "cpu_temp": { "avg": 47.1, "min": 44.8, "max": 52.8, "samples": 20 },
      "wifi_reconnects": { "lifetime_count": 2, "last_reason": "AUTH_EXPIRE", "last_at_uptime_ms": 3600000 },
      "ota": { "current_version": "2.7.3", "update_available": false, "last_check_uptime_ms": 180000, "last_error": "NONE" },
      "stack_high_water": { "TelemetryTask": 1024, "HealthMonitor": 890 },
      "bell_strikes": { "0": 1234, "1": 567, "...": "..." },
      "bell_loads": { "0": 12, "1": 0, "...": "..." },
      "cooling_active": false
    }
    
    cpu_temp pulls from Telemetry::writeTemperatureStats() then calls resetDiagnosticsStats() — the accumulator is consumed on the periodic path (unlike the on-demand telemetry.get_diagnostics command, which peeks without resetting). wifi_reconnects/ota read directly from the router's own _networking/_otaManager references (constructor-injected, not late-bound — no null guard needed). stack_high_water comes from Telemetry::writeStackHighWaterMarks()'s static task registry — see Telemetry's Diagnostics reporting section for the full design rationale (F-056 in the feature catalog), including why temperature alone needs local 15s sampling while the other three fields are read once per report. bell_strikes/bell_loads/cooling_active are read directly from Telemetry::getStrikeCount()/getBellLoad()/isCoolingActive() for all 16 bell channels — added when this report moved from system/info to system/metrics, matching the topic spec's explicit call-out of "bell heat ratings" for this topic.
  • Broadcast vs CommandBus broadcast: The broadcastXxx() helpers on this class send raw pre-serialised strings over WebSocket only. CommandBus::broadcast() serialises a CommandResult and fans it out to every registered transport, including MQTT's control/ack (see MQTTTransport::broadcast()). They are separate paths; subsystems outside the communication layer use whichever fits — the router's WS-only helpers for WS-specific fan-out, or the dedicated publishXxx() topic methods for MQTT-specific events.
  • 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().