# MQTTTransport ## Summary `MQTTTransport` wraps `MQTTDriver` and connects it to the `CommandBus`. It subscribes to `control/command`, parses incoming JSON messages into `CommandEnvelope` objects (including the optional `req_id`), and dispatches them. Command replies are published back to `control/ack`. Bus-wide unsolicited broadcasts also go through `broadcast()` to `control/ack` — but purpose-specific events (playback transitions, alerts, reports, metrics) are published directly by `CommunicationRouter` to their own dedicated topics instead, so `control/ack` stays strictly request/response. The underlying `MQTTDriver` manages the broker connection lifecycle, reconnect backoff, LWT, and heartbeat independently; `MQTTTransport` only owns the message-routing glue. See [docs/reference/vesper_mqtt_topic_spec_v2.md](../../../../docs/reference/vesper_mqtt_topic_spec_v2.md) for the full topic table. --- ## Public API | Method | Description | |--------|-------------| | `MQTTTransport(MQTTDriver& mqtt, CommandBus& bus)` | Constructor. Does not start the connection. | | `void begin()` | Wires the message callback onto `MQTTDriver`, then calls `MQTTDriver::begin()` to configure the AsyncMqttClient. Does not connect to the broker — connection is triggered by `onNetworkConnected()`. | | `void loop()` | No-op. AsyncMqttClient is fully event-driven. | | `bool isHealthy() const` | Returns `MQTTDriver::isConnected()`. | | `String name() const` | Returns `"MQTT"`. | | `void broadcast(const String& msg)` | Publishes `msg` to `control/ack` (bus-wide broadcasts only — see summary above). | | `void onNetworkConnected()` | Forwards to `MQTTDriver::onNetworkConnected()`, which schedules the broker connection after a 2-second stabilisation delay. | | `void onNetworkDisconnected()` | Forwards to `MQTTDriver::onNetworkDisconnected()`. | --- ## Initialization `CommunicationRouter::begin()` calls `_mqttTransport.begin()`, then adds the transport to the bus with `_bus.addTransport(&_mqttTransport)`. Network events from `Networking` arrive via `CommunicationRouter::onNetworkConnected()` / `onNetworkDisconnected()`, which forward to this transport. --- ## Message Format Incoming control messages (on `control/command`) must be JSON with at least a `"cmd"` field: ```json { "v": 2, "cmd": "relay.set_durations", "req_id": "abc123", "contents": { "bells": { "0": 500 } } } ``` `"v"` defaults to `2` if omitted. `"v": 1` triggers legacy translation before dispatch. `"req_id"` is optional — see `CommandEnvelope.hpp` / `docs/reference/vesper_mqtt_topic_spec_v2.md` for the correlation contract. Responses are published to `control/ack`: ```json { "status": "SUCCESS", "type": "relay.set_durations", "req_id": "abc123", "message": "Bell durations updated and saved" } ``` `req_id` is only present in the reply if the request included one. --- ## Dependencies - `MQTTDriver` — broker connection, publish/subscribe, reconnect, heartbeat - `CommandBus` — dispatch and broadcast - `ArduinoJson`, `Logging` --- ## Gotchas / Notes - **`control/ack` is strictly request/response plus bus-wide broadcasts — never purpose-specific events.** The broker does not distinguish a command reply from a `CommandBus::broadcast()` fan-out; clients must inspect `"type"` and `"status"` to differentiate. But playback transitions, alerts, reports, and metrics never appear here — those go to their own topics via `CommunicationRouter` (`publishPlayback()`, `publishAlert()`, `publishReport()`, `publishMetrics()`), bypassing this transport entirely. - **Broker connection is deferred.** `begin()` does not connect. The connection is triggered by `onNetworkConnected()`, which starts a 2-second non-blocking stabilisation timer in `MQTTDriver`. - **MQTT must be enabled in config, and the `command` topic switch must be on.** `MQTTDriver::connect()` is a no-op if `mqttConfig.enabled` is false. Toggle the master switch with `mqtt.enable` / `mqtt.disable`. Independently, the `command` topic switch (via `mqtt.set_topics`) gates the `control/command` subscription and `control/ack` replies — turning it off while MQTT stays connected silently stops all command traffic. - **No per-message QoS.** Command replies and broadcasts are published at QoS 1 (matching the topic table). Heartbeats use QoS 1 with `retain = true`. - **JSON parse errors and missing `cmd` get an `ERROR` reply on `control/ack`** (`type: "parse_error"`), not a silent drop — a `LOG_WARNING` is still emitted too. A parse-error reply necessarily has no `req_id` (it can't be read from input that failed to parse); a missing-`cmd` reply echoes `req_id` if the JSON was otherwise valid and included one. - **Incoming commands are dropped under critical heap pressure.** `onMessage()` checks `MQTTDriver::hasHeapForPublish()` (free heap ≥ 20KB) before even constructing the `JsonDocument` used to deserialize the incoming payload. Below that threshold, the message is dropped with no reply and no error response — indistinguishable from a lost network message to the caller. This exists because a rapid burst of commands (each involving deserialize + dispatch + reply, all allocation-heavy, all running inline on AsyncTCP's own task) previously fragmented the heap enough to crash the device with an unrecoverable `abort()` — see `docs/features/feature-catalog.md` F-055. A full fix (queueing incoming commands to a dedicated task, so this work never runs on AsyncTCP's task at all) is a scoped future improvement, not yet implemented.