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>
11 KiB
MQTTDriver
Summary
MQTTDriver is the low-level MQTT protocol driver. It wraps AsyncMqttClient and manages the full broker connection lifecycle: configuration, authentication, subscribe/publish, exponential backoff reconnection, 30-second heartbeat, network-stabilisation delay, and Last Will and Testament. It is not aware of the CommandBus — that coupling lives in MQTTTransport. The driver uses three FreeRTOS software timers with one-shot tasks deferred off the Tmr Svc stack to avoid stack overflows in timer callbacks.
See docs/reference/vesper_mqtt_topic_spec_v2.md for the full topic table, per-topic switches, and req_id correlation. Topics:
control/command(inbound, subscribe) — gated by thecommandtopic switchcontrol/ack(outbound replies) — gated by thecommandtopic switchstatus/heartbeat(retained, QoS 1) — gated by theheartbeattopic switchstatus/playback,control/reports,system/alerts,system/info,system/logs,system/metrics— published directly byCommunicationRouterviapublishDirect(), each gated by its own topic switch (see CommunicationRouter)
Public API
| Method | Description |
|---|---|
MQTTDriver(ConfigManager& configManager, Networking& networking) |
Constructor. Creates the three FreeRTOS timers. Sets the global _instance pointer. |
void begin() |
Caches topic strings, registers AsyncMqttClient event handlers, configures broker host/port/credentials/keepalive, and registers the Last Will (see LWT below). Does not connect. |
void connect() |
Calls AsyncMqttClient::connect(). No-op if MQTT is disabled in config or already connected. |
void disconnect(bool graceful = false) |
Disconnects. If graceful is true, explicitly publishes the retained offline payload to status/heartbeat first — see Graceful disconnect. |
uint16_t publishAck(const String& payload, int qos = 1, bool retain = false) |
Publishes a reply to control/ack. Returns packet ID, or 0 on failure (not connected, low heap, or the command topic switch is off). |
uint16_t publishDirect(const String& fullTopic, const String& payload, int qos = 0, bool retain = false) |
Publishes to an absolute, fully-qualified topic (no prefix applied) — no topic-switch gating here; the caller (CommunicationRouter) checks the relevant switch before calling. Same heap guard as publishAck(). |
bool hasHeapForPublish() const |
Returns true if ESP.getFreeHeap() >= MIN_FREE_HEAP_FOR_PUBLISH (20KB). Public so MQTTTransport can apply the same threshold before its own allocation-heavy work (JSON deserialization of incoming commands) without duplicating the constant. See Gotchas below for why this exists. |
const String& getCommandTopic() const / getAckTopic() / getHeartbeatTopic() / getPlaybackTopic() / getReportsTopic() / getAlertsTopic() / getInfoTopic() / getLogsTopic() / getMetricsTopic() |
Cached full topic strings, available after begin(). |
void setCallback(MessageCallback callback) |
Registers the message-received callback. Called by MQTTTransport::begin(). |
void setOnConnectCallback(std::function<void(bool sessionPresent)> callback) |
Registers a callback fired once each time MQTT successfully connects (including reconnects). Used by CommunicationRouter for one-shot "publish now that we're online" work such as reporting the boot/reset reason. |
void setStateProvider(std::function<DeviceState()> provider) |
Registers the callback used to derive the heartbeat's state/ok fields — see Heartbeat below. Wired by CommunicationRouter from Player + HealthMonitor. |
void applyCommandTopicSwitch(bool enabled) |
Live-applies a change to the command topic switch: subscribes/unsubscribes control/command immediately if connected, no-ops otherwise (picked up naturally on next connect). Called by MQTTHandler::handleSetTopics(). |
bool isConnected() const |
Returns the AsyncMqttClient connection state. |
void onNetworkConnected() |
Starts the 2-second network-stabilisation timer; connects after it fires. Resets _reconnectAttempts. |
void onNetworkDisconnected() |
Force-disconnects the client if connected. Reconnect logic waits for the next onNetworkConnected(). |
Initialization
MQTTTransport::begin() sets the message callback on the driver, then calls MQTTDriver::begin(). The broker connection is not initiated here — it is triggered by onNetworkConnected() when the network becomes available.
MQTTDriver is constructed inside CommunicationRouter as a member:
MQTTDriver _mqttClient; // in CommunicationRouter
The constructor creates all three FreeRTOS timers. If timer creation fails (extremely low memory), the nullptr guards in each callback will prevent crashes but MQTT will not reconnect automatically.
Reconnect Behaviour
| Attempts | Delay |
|---|---|
| 1–3 (quick retries) | 5 seconds each |
| 4 | 10 seconds |
| 5 | 20 seconds |
| 6 | 40 seconds |
| 7+ | Capped at 300 seconds (5 minutes) |
Reconnect attempts are reset to 0 on a successful connection or a new onNetworkConnected() event.
Last Will and Testament (LWT)
Registered once in begin() via AsyncMqttClient::setWill(), targeting status/heartbeat (QoS 1, retained) with payload {"device_id": "...", "state": "offline", "ok": false}. AsyncMqttClient resends the Will on every CONNECT packet, including reconnects, so no manual re-registration is needed after the first begin().
The broker fires the Will only on an unclean disconnect (network loss, crash, power loss) — it does not fire on a clean, intentional disconnect. See Graceful disconnect for the intentional case.
Graceful disconnect
disconnect(true) publishes the same offline payload explicitly, with retain=true, before calling the underlying clean disconnect — this prevents a stale "online" heartbeat from staying retained after an intentional disconnect (e.g. mqtt.disable, or before an OTA flash). disconnect(false) (the default) skips this and disconnects immediately — used where the caller doesn't want an offline announcement (rare; most call sites should use graceful=true).
Heartbeat
Once connected, a heartbeat is published immediately and then every 30 seconds to status/heartbeat with retain = true, gated by the heartbeat topic switch. Payload (flat, no envelope wrapper):
{
"device_id": "PV000000000000",
"state": "idle",
"ok": true,
"fw_version": "2.1.1",
"uptime_ms": 19425000,
"uptime_human": "5h 23m 45s",
"ip_address": "10.0.0.3",
"gateway": "10.0.0.1",
"rssi": -62,
"free_heap": 142000
}
state (idle/playing/paused/error/booting) and ok are produced by the _stateProvider callback — see setStateProvider() above — and are independently derived, never mirrored from status/playback or system/alerts, per the topic spec. CommunicationRouter wires this from Player::isCurrentlyPlaying()/isCurrentlyPaused() and HealthMonitor::isFirmwareStable(). If no provider is registered, heartbeats report state="booting", ok=true.
The heartbeat timer is stopped on disconnect and restarted on reconnect.
Dependencies
AsyncMqttClient— broker protocolConfigManager— MQTT host, port, credentials, enabled flag, device UID, per-topic switches (MqttTopicConfig)Networking—isConnected()check before reconnect attempts; IP and gateway for heartbeat- FreeRTOS — three
TimerHandle_ttimers, oneTaskHandle_tfor heartbeat task guard Logging
Gotchas / Notes
- Singleton pattern via
_instance. The class uses a static_instancepointer for routing timer callbacks back to the instance. Only oneMQTTDrivershould exist at a time. The constructor overwrites_instance, so creating two instances will break the first one's callbacks. - Timer callbacks defer to tasks. Timer callbacks run in the FreeRTOS Timer Service task (Tmr Svc, default 2 KB stack). Any callback that calls
LOG_*macros,connect(), or JSON serialisation would overflow this stack. All three callbacks (mqttReconnectTimerCallback,networkStabilizationTimerCallback,heartbeatTimerCallback) spawn a 3 KB task and return immediately. - Heartbeat task guard. If the previous heartbeat task has not yet exited when the next timer fires, the new task is not spawned. This prevents task accumulation under slow broker connections.
- Error logging is suppressed on publish failure.
publishAck()does not log an error when_mqttClient.publish()returns 0 (packet ID failure), because it's also reachable from the MQTT log channel and logging an error there would recurse infinitely. - Free-heap guard before publishing (
hasHeapForPublish()). BelowMIN_FREE_HEAP_FOR_PUBLISH(20KB),publishAck(),publishDirect(), andpublishHeartbeat()skip the operation entirely rather than riskAsyncMqttClient::publish()'s internal packet-buffer allocation failing. This SDK build hasCONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE=0— a failed allocation under heavy fragmentation can't even throw a catchablestd::bad_alloc, it callsabort()directly. This guard exists because exactly that happened in production under a rapid MQTT command burst with verbose logging (seedocs/features/feature-catalog.mdF-055 for the fulladdr2line-decoded diagnosis). The skip is logged viaSerial.printf()directly, notLOG_*— logging the skip over MQTT would itself attempt a publish, recursing into the same low-heap condition. - Credentials from NVS. The broker username and password are read from
ConfigManager, which loads them from NVS at boot. The password is a 32-character HMAC-SHA256 hex digest derived from the device UID andMQTT_SECRET(compiled in via-DMQTT_SECRET). begin()must be called beforeconnect().begin()registers AsyncMqttClient event handlers, configures the server, and registers the Will. Callingconnect()beforebegin()will silently do nothing useful.onConnectcallback fires on every connect, not just the first.setOnConnectCallbackfires on every successful connection, including reconnects after a drop — callers that want "once per boot" semantics (likeCommunicationRouter::reportBootOnce()) must track that themselves.commandtopic switch gates both directions. Turningcommandoff both unsubscribescontrol/command(no more inbound commands) and blockspublishAck()(no more outbound replies) — seedocs/reference/vesper_mqtt_topic_spec_v2.md. The other seven switches (heartbeat,playback,reports,alerts,info,logs,metrics) are checked by their respective publishers, not inside this driver —publishDirect()itself does not know which topic switch applies to the topic it's given.