Files
project-vesper/src/Communication/Drivers/MQTTDriver/README.md
T
bonaminandClaude Opus 5.5 cec4db4894 fix(MQTT): self-recovering supervisor, LWT payload fix, QoS 0 publishes (F-071, F-072)
Device went cloud-silent after days of uptime while WebSocket kept working;
last thing on status/heartbeat was garbage. Causes and fixes:

- LWT payload was a dangling pointer: setWill() stores the raw char*, begin()
  passed a temporary String. The broker published freed heap as the Will on
  the unclean drop. Now held in _willPayload.
- Reconnect/stabilisation/heartbeat timers each xTaskCreate()d a short-lived
  task with the result ignored; one failed allocation ended the one-shot
  reconnect chain for good. Replaced by one persistent supervisor task that
  polls WiFi.status() itself, reconnects with backoff (cap now 60 s), sends
  the heartbeat, and force-resets the client when a connect attempt is stuck
  for 30 s or the heartbeat PUBACK is missing for 20 s.
- New mqtt.status command (all transports) exposes connect/disconnect
  counters, last reasons and forced resets for post-mortems over WebSocket.

Latency (F-072): AsyncMqttClient holds its queue behind every QoS 1 PUBACK
and only resumes on the ~500 ms poll, so each QoS 1 message cost RTT + up to
500 ms. All publishes are now QoS 0 except the heartbeat (liveness probe);
cleanSession=true on both ends meant QoS 1 never gave redelivery. WiFi modem
sleep disabled on connect to remove DTIM-induced RX delays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 21:07:14 +03:00

12 KiB
Raw Blame History

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. All time-driven work runs on one persistent supervisor task (see Initialization).

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 the command topic switch
  • control/ack (outbound replies) — gated by the command topic switch
  • status/heartbeat (retained, QoS 1) — gated by the heartbeat topic switch
  • status/playback, control/reports, system/alerts, system/info, system/logs, system/metrics — published directly by CommunicationRouter via publishDirect(), 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 = 0, 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 connect() Requests a connect now (resets backoff) and wakes the supervisor. Used by mqtt.enable.
void writeStatus(JsonObject out) const Fills the mqtt.status diagnostics object (connect/disconnect counters, last reasons, forced resets).
void onNetworkConnected() Resets _reconnectAttempts and wakes the supervisor, which connects once WiFi has been up for 2 s. Not required for reconnects — the supervisor polls WiFi.status() itself.
void onNetworkDisconnected() Force-disconnects the client if connected. The supervisor reconnects once WiFi is back.

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

begin() creates one persistent supervisor task (mqttSup, 4 KB, priority 3) that owns everything time-driven: connect/reconnect with backoff, the 2 s network stabilisation, the 30 s heartbeat, and wedge detection. It replaced three FreeRTOS timers that each spawned a short-lived task per firing; one failed xTaskCreate() on a fragmented heap used to end the reconnect chain for good. See F-071.


Reconnect Behaviour

Attempts Delay
1–3 (quick retries) 5 seconds each
4 10 seconds
5 20 seconds
6 40 seconds
7+ Capped at 60 seconds

Reconnect attempts are reset to 0 on a successful connection or a new onNetworkConnected() event.

Self-recovery (wedge detection)

The supervisor forces a reset (AsyncMqttClient::disconnect(true), then a normal reconnect) when:

Condition Why it happens
A connect attempt produced neither CONNACK nor a disconnect callback within 30 s ("connect attempt stuck") AsyncMqttClient ignores AsyncClient::connect()'s return value and stays in CONNECTING forever if it fails (e.g. lwIP out of PCBs); a failed tcp_close never fires onDisconnect. Every later connect() is then a silent no-op.
The heartbeat's PUBACK hasn't arrived 20 s after it was sent ("heartbeat PUBACK timeout") Half-open socket or stalled send queue while the library still reports CONNECTED.

Counters and last reasons are reported by mqtt.status.

QoS policy

All publishes are QoS 0 except the heartbeat. This AsyncMqttClient build sends its queue strictly in order and holds every later packet until a QoS 1 PUBACK arrives, and _onPubAck() doesn't kick the queue — the next packet waits for the ~500 ms TCP poll. A burst of QoS 1 messages (playback + ack + log lines) cost RTT + up to 500 ms each. With cleanSession=true on both device and backend, QoS 1 never provided redelivery anyway.


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}. The payload is kept in the _willPayload member: setWill() stores the raw pointer, and before F-071 it pointed at a freed temporary, so the broker published garbage as the LWT. 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 supervisor publishes the first heartbeat right after CONNACK, then every 30 s while connected. It is QoS 1 on purpose: if its PUBACK is missing after 20 s, the connection is treated as dead (see Self-recovery).


Dependencies

  • AsyncMqttClient — broker protocol
  • ConfigManager — MQTT host, port, credentials, enabled flag, device UID, per-topic switches (MqttTopicConfig)
  • Networking — IP and gateway for heartbeat (reconnect gating uses WiFi.status() directly)
  • FreeRTOS — one persistent supervisor task, woken by task notifications
  • Logging

Gotchas / Notes

  • Singleton pattern via _instance. The class uses a static _instance pointer for routing timer callbacks back to the instance. Only one MQTTDriver should exist at a time. The constructor overwrites _instance, so creating two instances will break the first one's callbacks.
  • No per-event tasks. Earlier versions spawned a short-lived task from every timer firing (reconnect, stabilisation, heartbeat). xTaskCreate() return values weren't checked, so on a fragmented heap a single failure silently ended MQTT until reboot. The supervisor task is allocated once at boot instead.
  • Free-heap guard before publishing (hasHeapForPublish()). Below MIN_FREE_HEAP_FOR_PUBLISH (20KB), publishAck(), publishDirect(), and publishHeartbeat() skip the operation entirely rather than risk AsyncMqttClient::publish()'s internal packet-buffer allocation failing. This SDK build has CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE=0 — a failed allocation under heavy fragmentation can't even throw a catchable std::bad_alloc, it calls abort() directly. This guard exists because exactly that happened in production under a rapid MQTT command burst with verbose logging (see docs/features/feature-catalog.md F-055 for the full addr2line-decoded diagnosis). The skip is logged via Serial.printf() directly, not LOG_* — 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 and MQTT_SECRET (compiled in via -DMQTT_SECRET).
  • begin() must be called before connect(). begin() registers AsyncMqttClient event handlers, configures the server, and registers the Will. Calling connect() before begin() will silently do nothing useful.
  • onConnect callback fires on every connect, not just the first. setOnConnectCallback fires on every successful connection, including reconnects after a drop — callers that want "once per boot" semantics (like CommunicationRouter::reportBootOnce()) must track that themselves.
  • command topic switch gates both directions. Turning command off both unsubscribes control/command (no more inbound commands) and blocks publishAck() (no more outbound replies) — see docs/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.