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>
This commit is contained in:
2026-10-15 21:07:14 +03:00
co-authored by Claude Opus 5.5
parent 09f562cf1d
commit cec4db4894
13 changed files with 382 additions and 258 deletions
+69
View File
@@ -83,6 +83,8 @@ Check `git log -- src/Version.hpp` for the real bump history before tagging a ne
| F-068 | `loading` playback state while a melody downloads (MQTT `status/playback`), cancellable by `playback.stop`; `playback_failed` event on `control/reports` when an ACKed play never starts | v2.3.0 | Stable |
| F-069 | RF remote disabled on Vesper Standard builds (`HAS_RF=0`) — no fielded unit has a receiver; `rf.*` now only on agnus | v2.3.0 | Stable |
| F-070 | Richer crash reports — coredump backtrace + ELF SHA, abort() reason string, and last pre-crash heap/uptime snapshot in `boot_report` and the SD boot log | v2.3.0 | Stable |
| F-071 | MQTT self-recovery — single supervisor task replaces timer/task chain, wedge detection (stuck connect, missing heartbeat PUBACK), LWT payload fix, `mqtt.status` diagnostics | v2.3.0 | Stable |
| F-072 | Lower status/reply latency — all MQTT publishes QoS 0 except heartbeat; WiFi modem sleep disabled | v2.3.0 | Stable |
---
@@ -1422,3 +1424,70 @@ confirms `abort()` now calls `__wrap_esp_system_abort` (IRAM) and the breadcrumb
memory (`0x5000xxxx`). Not yet exercised with a deliberate crash on hardware.
Subsystem: `src/Telemetry/CrashBreadcrumbs.hpp`, `src/Telemetry/CrashBreadcrumbs.cpp`, `src/Telemetry/Telemetry.hpp`, `src/Telemetry/Telemetry.cpp`, `src/Communication/CommunicationRouter/CommunicationRouter.cpp`, `platformio.ini`
---
### F-071 — MQTT self-recovery and `mqtt.status`
**Incident.** A device that had been up for days stopped talking MQTT mid-session: the cloud console
saw it offline, pings and commands went unanswered, but the local WebSocket app kept working, and full
logs showed no errors. The last thing on `status/heartbeat` was a garbage payload.
**Root causes found in `MQTTDriver`:**
1. **The LWT payload was a dangling pointer.** `AsyncMqttClient::setWill()` stores the raw `const char*`;
`begin()` passed `.c_str()` of a local `String`. Every later CONNECT carried whatever was in that freed
heap block as the Will, so on an unclean drop the broker published garbage to `status/heartbeat` (retained).
The garbage seen in the incident was the broker announcing that the connection had died. Now kept in the
`_willPayload` member.
2. **The reconnect chain could die silently.** Reconnect, network stabilisation and heartbeat were
FreeRTOS timers whose callbacks each `xTaskCreate()`d a short-lived 4 KB task, with the return value
ignored. The reconnect timer is one-shot, so a single failed allocation (fragmented heap after days of
uptime) ended reconnection until reboot, and nothing was logged afterwards. A reconnect that fired while
WiFi was briefly down also gave up without rescheduling and waited for a network callback that might never come.
3. **AsyncMqttClient can wedge without telling anyone.** It ignores `AsyncClient::connect()`'s return value
(lwIP out of PCBs leaves it in CONNECTING forever), and a failed `tcp_close` never fires onDisconnect.
In both cases every later `connect()` is a silent no-op.
**What changed.** One persistent supervisor task (`mqttSup`, allocated at boot, never freed) owns
connect/reconnect with backoff (5 s ×3, then doubling, **now capped at 60 s instead of 5 min**), the 2 s
network stabilisation (it polls `WiFi.status()` itself, so it doesn't depend on Networking callbacks), the
30 s heartbeat, and wedge detection. It forces a reset (`disconnect(true)` + normal reconnect) when:
- a connect attempt gets neither CONNACK nor a disconnect callback within 30 s (`"connect attempt stuck"`), or
- the heartbeat's PUBACK is still missing 20 s after it was sent (`"heartbeat PUBACK timeout"`): a half-open
socket or stalled send queue while the library still says CONNECTED. The heartbeat stays QoS 1 for this
reason. With the `heartbeat` topic switch off, this probe is off too.
**`mqtt.status`** (new command, all transports) returns connect/disconnect counters, last disconnect reason
and age, forced-reset count/reason/age, WiFi state and free heap. If a device goes cloud-silent again, send
it over WebSocket: `forced_resets > 0` means self-recovery is firing, `connected:true` while the cloud sees
it offline points at the broker/backend side.
Not covered: if the broker is reachable but rejects the device (auth), the device keeps retrying at the
60 s cap, which is visible in `mqtt.status` as climbing `reconnect_attempts`.
Subsystem: `src/Communication/Drivers/MQTTDriver/MQTTDriver.hpp/.cpp`, `src/Communication/Handlers/MQTTHandler/MQTTHandler.hpp/.cpp`
### F-072 — Lower status/reply latency (QoS 0, WiFi sleep off)
**Symptom.** Playback status and command replies usually took 1–2 s to reach the apps, and MQTT sometimes 3–5 s+.
**Why MQTT was slow.** This AsyncMqttClient build sends its outbound queue strictly in order and holds every
later packet until a QoS 1 PUBACK arrives. `_onPubAck()` releases the packet but doesn't restart the queue,
so the next packet waits for the next lwIP poll (~500 ms). Everything the board published was QoS 1
(acks, playback, alerts, info, reports, and log lines), so a play command queued playback + ack + several
log lines, each costing a round trip plus up to 500 ms. The PUBACK the board owes the broker for the incoming
command waited in the same queue. With `cleanSession=true` on both the device and the backend
(`backend/mqtt/client.py`), QoS 1 never bought redelivery: unacked packets are dropped on reconnect either way.
**Change.** Everything is published at QoS 0 except the heartbeat (QoS 1, see F-071). Topics, retain flags
and payloads are unchanged. Subscribers receive at min(publish QoS, subscription QoS), so they now get QoS 0
delivery, which changes nothing with clean sessions.
**WiFi modem sleep off.** Arduino-ESP32 defaults to `WIFI_PS_MIN_MODEM`: the radio dozes between AP beacons
and inbound packets wait for the next DTIM (100 ms to 1 s+ depending on the AP). This affects WebSocket and
MQTT equally. `Networking::onWiFiConnected()` now calls `WiFi.setSleep(false)` on every connect. The device is
mains powered, so the extra ~80 mA doesn't matter.
Subsystem: `src/Communication/CommunicationRouter/CommunicationRouter.cpp`, `src/Communication/Drivers/MQTTDriver/MQTTDriver.hpp`, `src/Logging/Logging.cpp`, `src/Networking/Networking.cpp`
+16 -8
View File
@@ -80,9 +80,9 @@ MQTT uses the v2 topic set — see [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_to
| MQTT | `vesper/{device_id}/control/ack` | Outbound replies | Strictly request/response — nothing unsolicited |
| MQTT | `vesper/{device_id}/control/reports` | Outbound, critical unsolicited events | `bell_overload`, `playback_failed` — not retained |
| MQTT | `vesper/{device_id}/status/heartbeat` | Outbound, retained, QoS 1 | Heartbeat every 30s + LWT |
| MQTT | `vesper/{device_id}/status/playback` | Outbound, retained, QoS 1 | Playback transitions |
| MQTT | `vesper/{device_id}/system/alerts` | Outbound, retained until cleared, QoS 1 | Subsystem state-change events |
| MQTT | `vesper/{device_id}/system/info` | Outbound, retained, QoS 1 | Discrete device events (boot report) |
| MQTT | `vesper/{device_id}/status/playback` | Outbound, retained, QoS 0 | Playback transitions |
| MQTT | `vesper/{device_id}/system/alerts` | Outbound, retained until cleared, QoS 0 | Subsystem state-change events |
| MQTT | `vesper/{device_id}/system/info` | Outbound, retained, QoS 0 | Discrete device events (boot report) |
| MQTT | `vesper/{device_id}/system/logs` | Outbound, QoS 0 | Mirrors serial log stream |
| MQTT | `vesper/{device_id}/system/metrics` | Outbound, QoS 0 | Structured telemetry every 5 min |
| WebSocket | `ws://{device_ip}/ws` | Bidirectional | Send `identify` on connect |
@@ -821,6 +821,12 @@ Returns `message: "MQTT enabled and saved"` / `"MQTT disabled and saved"`. Error
Returns `data: { "enabled", "host", "port", "user", "use_ssl" }` (never the password).
### `mqtt.status`
Connection health since boot — works on every transport, so it's the command to send over WebSocket when the cloud shows a device offline but the local app still works.
Returns `data: { "enabled", "connected", "connected_for_ms", "connects", "disconnects", "reconnect_attempts", "last_disconnect_reason", "last_disconnect_ago_ms", "forced_resets", "last_forced_reset_reason", "last_forced_reset_ago_ms", "wifi_connected", "free_heap" }`.
`*_ago_ms` and `connected_for_ms` are `0` when the event never happened / not connected. `last_forced_reset_reason` is `"connect attempt stuck"` or `"heartbeat PUBACK timeout"` (empty if self-recovery never fired). No errors.
### `mqtt.get_topics`
Returns `data: { "command", "heartbeat", "playback", "reports", "alerts", "info", "logs", "metrics" }` (bools).
@@ -873,14 +879,16 @@ Published without a request, on the v2 topic set. Full field-level reference: [m
| Topic | When | QoS | Retained | Switch |
|---|---|---|---|---|
| `vesper/{id}/status/heartbeat` | Every 30s (+ LWT on unclean disconnect) | 1 | yes | `heartbeat` |
| `vesper/{id}/status/playback` | On playback transition | 1 | yes | `playback` |
| `vesper/{id}/control/reports` | Critical unsolicited events (`bell_overload`, `playback_failed`) | 1 | no | `reports` |
| `vesper/{id}/system/alerts` | On subsystem state change only | 1 | yes, until cleared | `alerts` |
| `vesper/{id}/system/info` | Discrete device events (e.g. boot report) | 1 | yes | `info` |
| `vesper/{id}/status/playback` | On playback transition | 0 | yes | `playback` |
| `vesper/{id}/control/reports` | Critical unsolicited events (`bell_overload`, `playback_failed`) | 0 | no | `reports` |
| `vesper/{id}/system/alerts` | On subsystem state change only | 0 | yes, until cleared | `alerts` |
| `vesper/{id}/system/info` | Discrete device events (e.g. boot report) | 0 | yes | `info` |
| `vesper/{id}/system/logs` | Mirrors serial log stream | 0 | no | `logs` |
| `vesper/{id}/system/metrics` | Every 5 min | 0 | no | `metrics` |
`control/ack` carries only replies (it is not an event topic).
`control/ack` carries only replies (it is not an event topic). Replies are published at QoS 0.
Everything the board publishes is QoS 0 except the heartbeat (QoS 1, its PUBACK doubles as a liveness probe) — see F-071 in the feature catalog for why.
---
+10 -10
View File
@@ -14,12 +14,12 @@ Vesper publishes on eight MQTT topics (a ninth, `system/ota`, is reserved but no
| Topic | Direction | QoS | Retained | Switch | Purpose |
|-------|-----------|-----|----------|--------|---------|
| `vesper/{id}/control/command` | Inbound | 1 | no | `command` | Commands from server/app — board only ever receives here |
| `vesper/{id}/control/ack` | Outbound | 1 | no | `command` | Replies to commands **only** — strictly request/response |
| `vesper/{id}/control/reports` | Outbound | 1 | no | `reports` | Critical, unsolicited, time-sensitive board-initiated events (`bell_overload`, `playback_failed`) |
| `vesper/{id}/control/ack` | Outbound | 0 | no | `command` | Replies to commands **only** — strictly request/response |
| `vesper/{id}/control/reports` | Outbound | 0 | no | `reports` | Critical, unsolicited, time-sensitive board-initiated events (`bell_overload`, `playback_failed`) |
| `vesper/{id}/status/heartbeat` | Outbound | 1 | yes | `heartbeat` | Periodic liveness + state signal. Also carries LWT. |
| `vesper/{id}/status/playback` | Outbound | 1 | yes | `playback` | Playback transitions only |
| `vesper/{id}/system/alerts` | Outbound | 1 | yes, until cleared | `alerts` | Subsystem state-change events |
| `vesper/{id}/system/info` | Outbound | 1 | yes | `info` | Discrete device state events (boot report, etc.) |
| `vesper/{id}/status/playback` | Outbound | 0 | yes | `playback` | Playback transitions only |
| `vesper/{id}/system/alerts` | Outbound | 0 | yes, until cleared | `alerts` | Subsystem state-change events |
| `vesper/{id}/system/info` | Outbound | 0 | yes | `info` | Discrete device state events (boot report, etc.) |
| `vesper/{id}/system/logs` | Outbound | 0 | no | `logs` | Full log stream, mirrors serial log output |
| `vesper/{id}/system/metrics` | Outbound | 0 | no | `metrics` | Structured telemetry — fleet-health graphing |
@@ -85,7 +85,7 @@ to `status/heartbeat` (QoS 1, retained), overwriting the last "online" heartbeat
## `vesper/{id}/status/playback`
**QoS:** 1 — **Retained:** yes — **Switch:** `playback` — **Trigger:** playback state transition only
**QoS:** 0 — **Retained:** yes — **Switch:** `playback` — **Trigger:** playback state transition only
Published by `Player::setStatus()` on every transition (not polled), **and on every MQTT connect/reconnect** with the Player's current real state — so a retained `playing` left behind by a power loss mid-melody is overwritten (normally with `idle`) as soon as the board is back. This topic — not the `control/ack` reply — is the source of truth for what the board is actually doing. Skipped (not queued) while free heap is below the publish guard.
@@ -151,7 +151,7 @@ On a SUCCESS play ACK the board publishes `status/playback` **before** the ACK:
## `vesper/{id}/control/reports`
**QoS:** 1 — **Retained:** no — **Switch:** `reports` — **Trigger:** critical, time-sensitive, board-initiated event
**QoS:** 0 — **Retained:** no — **Switch:** `reports` — **Trigger:** critical, time-sensitive, board-initiated event
The opposite of `control/command`: unsolicited data the board sends because it needs to be read *now*. Not a reply to anything — never carries `req_id`. Not retained, since it's an event stream, not a status snapshot.
@@ -201,7 +201,7 @@ Like every `control/reports` event it carries no `req_id` — correlate with the
## `vesper/{id}/system/alerts`
**QoS:** 1 — **Retained:** yes, until cleared — **Switch:** `alerts` — **Trigger:** subsystem state change only
**QoS:** 0 — **Retained:** yes, until cleared — **Switch:** `alerts` — **Trigger:** subsystem state change only
Published by `HealthMonitor` (via `CommunicationRouter::publishAlert()`) whenever a subsystem transitions between health states. Published once on change; not repeated until the state changes again. Silent if MQTT is not connected, or the `alerts` switch is off, at the moment of the transition. Retained so a late-connecting console (fleet webserver) immediately sees the last unresolved alert per subsystem.
@@ -262,7 +262,7 @@ A fault-class boot reset also publishes here — `subsystem: "System"`, e.g.:
## `vesper/{id}/system/info`
**QoS:** 1 — **Retained:** yes — **Switch:** `info` — **Trigger:** discrete device state event
**QoS:** 0 — **Retained:** yes — **Switch:** `info` — **Trigger:** discrete device state event
Published for general device state changes that are not health failures and not quantitative telemetry (see `system/metrics` for that). Use this topic to update the device detail panel (e.g. boot reason) without polling.
@@ -350,7 +350,7 @@ Structured telemetry for fleet-health graphing — not consumed by the phone app
## `vesper/{id}/control/command` and `vesper/{id}/control/ack`
**QoS:** 1 — **Retained:** no — **Switch:** `command`
**QoS:** 1 inbound (`control/command`), 0 outbound (`control/ack`) — **Retained:** no — **Switch:** `command`
`control/command` is read-only from the board's perspective — the board only ever receives here. `control/ack` is strictly reply-only: every message on it answers a specific request (including `pong`), and no unsolicited event is ever published there. Both support an optional `req_id` field for correlation — see [vesper_mqtt_topic_spec_v2.md](vesper_mqtt_topic_spec_v2.md#req_id-correlation).
@@ -554,7 +554,7 @@ void CommunicationRouter::publishAlert(const String& subsystem, const String& ne
// immediately sees the last unresolved alert per subsystem. A CLEARED
// publish (empty message, state="CLEARED") overwrites the retained
// message with the resolved state, same retain semantics.
_mqttClient.publishDirect(_mqttClient.getAlertsTopic(), out, 1, true);
_mqttClient.publishDirect(_mqttClient.getAlertsTopic(), out, 0, true);
LOG_DEBUG(TAG, "Alert published: %s → %s", subsystem.c_str(), newState.c_str());
}
@@ -667,7 +667,7 @@ void CommunicationRouter::publishInfo(const String& type, const JsonDocument& pa
String out;
serializeJson(doc, out);
_mqttClient.publishDirect(_mqttClient.getInfoTopic(), out, 1, true);
_mqttClient.publishDirect(_mqttClient.getInfoTopic(), out, 0, true);
LOG_DEBUG(TAG, "Info published: %s", type.c_str());
}
@@ -681,7 +681,7 @@ void CommunicationRouter::publishPlayback(const PlaybackSnapshot& snapshot) {
String out;
serializeJson(doc, out);
_mqttClient.publishDirect(_mqttClient.getPlaybackTopic(), out, 1, true);
_mqttClient.publishDirect(_mqttClient.getPlaybackTopic(), out, 0, true);
LOG_DEBUG(TAG, "Playback published: %s", snapshot.action);
}
@@ -699,7 +699,7 @@ void CommunicationRouter::publishReport(const String& type, const JsonDocument&
serializeJson(doc, out);
// Not retained — an event stream of critical-but-transient reports, not a
// status snapshot. A late subscriber doesn't need old reports replayed.
_mqttClient.publishDirect(_mqttClient.getReportsTopic(), out, 1, false);
_mqttClient.publishDirect(_mqttClient.getReportsTopic(), out, 0, false);
LOG_DEBUG(TAG, "Report published: %s", type.c_str());
}
@@ -48,10 +48,10 @@
| `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 publishPlayback(const String& action, uint32_t timeElapsedSec, uint64_t projectedRunTimeMs)` | Publishes a playback transition to `vesper/{uid}/status/playback` (QoS 0, 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 0, 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 0, 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 0, 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)
@@ -15,55 +15,22 @@ MQTTDriver::MQTTDriver(ConfigManager& configManager, Networking& networking)
: _configManager(configManager)
, _networking(networking)
, _messageCallback(nullptr)
, _mqttReconnectTimer(nullptr)
, _networkStabilizationTimer(nullptr)
, _heartbeatTimer(nullptr)
, _heartbeatTaskHandle(nullptr)
, _supervisorTask(nullptr)
, _reconnectAttempts(0)
, _lastConnectionAttempt(0) {
, _nextConnectAtMs(0)
, _connectAttemptMs(0)
, _netUpSinceMs(0)
, _heartbeatDue(false)
, _lastHeartbeatMs(0)
, _heartbeatPendingId(0)
, _heartbeatSentMs(0) {
_instance = this; // Set static instance pointer
// Create reconnection timer (initial delay will be calculated dynamically)
_mqttReconnectTimer = xTimerCreate(
"mqttReconnect", // Timer name (for debugging)
pdMS_TO_TICKS(MQTT_RECONNECT_BASE_DELAY), // Initial period: 5000ms = 5 seconds
pdFALSE, // One-shot (false) or Auto-reload (true)
(void*)0, // Timer ID (can store data)
mqttReconnectTimerCallback // Callback function when timer expires
);
// Create network stabilization timer (one-shot, 2 seconds)
_networkStabilizationTimer = xTimerCreate(
"mqttNetStable", // Timer name
pdMS_TO_TICKS(NETWORK_STABILIZATION_DELAY), // Period: 2000ms = 2 seconds
pdFALSE, // One-shot timer
(void*)0, // Timer ID
networkStabilizationTimerCallback // Callback function
);
// Create heartbeat timer (auto-reload every 30 seconds)
_heartbeatTimer = xTimerCreate(
"mqttHeartbeat", // Timer name
pdMS_TO_TICKS(HEARTBEAT_INTERVAL), // Period: 30000ms = 30 seconds
pdTRUE, // Auto-reload (true) - repeating timer
(void*)0, // Timer ID
heartbeatTimerCallback // Callback function
);
}
MQTTDriver::~MQTTDriver() {
if (_mqttReconnectTimer) {
xTimerDelete(_mqttReconnectTimer, portMAX_DELAY);
}
if (_networkStabilizationTimer) {
xTimerStop(_networkStabilizationTimer, 0);
xTimerDelete(_networkStabilizationTimer, portMAX_DELAY);
}
if (_heartbeatTimer) {
xTimerStop(_heartbeatTimer, 0);
xTimerDelete(_heartbeatTimer, portMAX_DELAY);
if (_supervisorTask) {
vTaskDelete(_supervisorTask);
}
_mqttClient.disconnect();
}
@@ -127,8 +94,14 @@ void MQTTDriver::begin() {
// crash, power loss). Must be re-registered on every reconnect, which is
// automatic here since setWill() is applied on every begin()/connect() —
// AsyncMqttClient resends CONNECT (with Will) on every reconnection attempt.
String willPayload = buildOfflinePayload();
_mqttClient.setWill(_heartbeatTopic.c_str(), 1, true, willPayload.c_str());
_willPayload = buildOfflinePayload();
_mqttClient.setWill(_heartbeatTopic.c_str(), 1, true, _willPayload.c_str());
// Created once at boot, while the heap is still unfragmented, and never
// deleted — nothing in the reconnect/heartbeat path allocates a task again.
if (!_supervisorTask) {
xTaskCreate(supervisorTaskFn, "mqttSup", 4096, this, 3, &_supervisorTask);
}
LOG_INFO(TAG, "✅ MQTT Async Client initialized");
}
@@ -144,27 +117,22 @@ String MQTTDriver::buildOfflinePayload() const {
}
void MQTTDriver::connect() {
auto& mqttConfig = _configManager.getMqttConfig();
_reconnectAttempts = 0;
_nextConnectAtMs = millis();
wakeSupervisor();
}
// 🔥 Check if MQTT is enabled
if (!mqttConfig.enabled) {
LOG_DEBUG(TAG, "MQTT is disabled in configuration - skipping connection");
return;
}
if (_mqttClient.connected()) {
LOG_DEBUG(TAG, "Already connected to MQTT");
return;
}
// Track connection attempt
_lastConnectionAttempt = millis();
LOG_INFO(TAG, "Free heap BEFORE MQTT connect: %d bytes", ESP.getFreeHeap());
// Supervisor-task only. AsyncMqttClient::connect() is a no-op unless the
// library is DISCONNECTED; if it's stuck in CONNECTING/DISCONNECTING the
// supervisor notices via _connectAttemptMs and forces a reset.
void MQTTDriver::doConnect() {
if (_mqttClient.connected()) return;
unsigned long now = millis();
_connectAttemptMs = now ? now : 1;
LOG_INFO(TAG, "Connecting to MQTT broker (attempt #%d, free heap %u bytes)...",
_reconnectAttempts + 1, (unsigned)ESP.getFreeHeap());
_mqttClient.connect();
LOG_INFO(TAG, "MQTT connect() called - waiting for async connection...");
}
void MQTTDriver::disconnect(bool graceful) {
@@ -236,34 +204,18 @@ bool MQTTDriver::isConnected() const {
}
void MQTTDriver::onNetworkConnected() {
auto& mqttConfig = _configManager.getMqttConfig();
// 🔥 Only attempt connection if MQTT is enabled
if (!mqttConfig.enabled) {
LOG_DEBUG(TAG, "Network connected but MQTT is disabled - skipping MQTT connection");
return;
}
LOG_DEBUG(TAG, "Network connected - scheduling MQTT connection after 2s stabilization (non-blocking)");
// Reset reconnect attempts on fresh network connection
// The supervisor tracks WiFi itself (it doesn't depend on this callback
// ever arriving) — this just resets backoff and wakes it up promptly.
LOG_DEBUG(TAG, "Network connected - MQTT connect after %lums stabilization", NETWORK_STABILIZATION_DELAY);
_reconnectAttempts = 0;
// 🔥 CRITICAL FIX: Use non-blocking timer instead of delay()
// This prevents blocking UDP discovery, WebSocket connections, and async operations
if (_networkStabilizationTimer) {
xTimerStart(_networkStabilizationTimer, 0);
} else {
LOG_ERROR(TAG, "Network stabilization timer not initialized!");
// Fallback to immediate connection (better than blocking)
connect();
}
_nextConnectAtMs = millis();
wakeSupervisor();
}
void MQTTDriver::onNetworkDisconnected() {
LOG_DEBUG(TAG, "Network disconnected - MQTT will auto-reconnect when network returns");
LOG_DEBUG(TAG, "Network disconnected - MQTT will reconnect when network returns");
if (_mqttClient.connected()) {
if (_mqttClient.connected()) {
_mqttClient.disconnect(true);
}
}
@@ -286,12 +238,18 @@ void MQTTDriver::onMqttConnect(bool sessionPresent) {
// Reset reconnection attempts on successful connection
_reconnectAttempts = 0;
_connectAttemptMs = 0;
_heartbeatPendingId = 0;
_diag.connects++;
_diag.connectedSinceMs = millis();
// Subscribe to control topic
subscribe();
// 🔥 Start heartbeat timer
startHeartbeat();
// First heartbeat goes out from the supervisor right away, not from here —
// this callback runs on the async_tcp task.
_heartbeatDue = true;
wakeSupervisor();
if (_onConnectCallback) {
_onConnectCallback(sessionPresent);
@@ -326,34 +284,26 @@ void MQTTDriver::onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
break;
}
LOG_ERROR(TAG, "❌ Disconnected from MQTT broker - Reason: %s (%d)", reasonStr, static_cast<int>(reason));
_diag.disconnects++;
_diag.lastDisconnectReason = reasonStr;
_diag.lastDisconnectMs = millis();
_diag.connectedSinceMs = 0;
_heartbeatPendingId = 0;
_connectAttemptMs = 0;
// Stop heartbeat timer when disconnected
stopHeartbeat();
// 🔥 Don't attempt reconnection if MQTT is disabled
if (!mqttConfig.enabled) {
LOG_INFO(TAG, "MQTT is disabled - not attempting reconnection");
LOG_INFO(TAG, "❌ Disconnected from MQTT broker - Reason: %s (%d) - MQTT disabled, not reconnecting",
reasonStr, static_cast<int>(reason));
return;
}
if (_networking.isConnected()) {
// Increment reconnection attempts
_reconnectAttempts++;
// Calculate backoff delay
unsigned long reconnectDelay = getReconnectDelay();
LOG_INFO(TAG, "Network still connected - scheduling MQTT reconnection #%d in %lu seconds (backoff active)",
_reconnectAttempts, reconnectDelay / 1000);
// Update timer period with new delay
xTimerChangePeriod(_mqttReconnectTimer, pdMS_TO_TICKS(reconnectDelay), 0);
xTimerStart(_mqttReconnectTimer, 0);
} else {
LOG_INFO(TAG, "Network is down - waiting for network to reconnect");
}
_reconnectAttempts++;
unsigned long reconnectDelay = getReconnectDelay();
_nextConnectAtMs = millis() + reconnectDelay;
LOG_ERROR(TAG, "❌ Disconnected from MQTT broker - Reason: %s (%d) - reconnect #%d in %lus",
reasonStr, static_cast<int>(reason), _reconnectAttempts, reconnectDelay / 1000);
wakeSupervisor();
}
void MQTTDriver::applyCommandTopicSwitch(bool enabled) {
@@ -390,60 +340,112 @@ void MQTTDriver::onMqttMessage(char* topic, char* payload, AsyncMqttClientMessag
}
void MQTTDriver::onMqttPublish(uint16_t packetId) {
if (packetId == _heartbeatPendingId) {
_heartbeatPendingId = 0;
}
LOG_DEBUG(TAG, "MQTT publish acknowledged (packetId=%d)", packetId);
}
void MQTTDriver::attemptReconnection() {
// Double-check network is still up
if (_networking.isConnected()) {
LOG_INFO(TAG, "Attempting MQTT reconnection...");
connect();
} else {
LOG_WARNING(TAG, "Network down during reconnect attempt - aborting");
// ═══════════════════════════════════════════════════════════════════════════════════
// SUPERVISOR TASK
// ═══════════════════════════════════════════════════════════════════════════════════
void MQTTDriver::supervisorTaskFn(void* param) {
MQTTDriver* self = static_cast<MQTTDriver*>(param);
for (;;) {
// Woken early by connect/disconnect/network events; otherwise ticks.
ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(SUPERVISOR_TICK_MS));
self->supervise();
}
}
void MQTTDriver::mqttReconnectTaskFn(void* param) {
MQTTDriver* client = static_cast<MQTTDriver*>(param);
client->attemptReconnection();
vTaskDelete(NULL);
void MQTTDriver::wakeSupervisor() {
if (_supervisorTask) xTaskNotifyGive(_supervisorTask);
}
void MQTTDriver::mqttReconnectTimerCallback(TimerHandle_t xTimer) {
if (MQTTDriver::_instance) {
xTaskCreate(mqttReconnectTaskFn, "mqttRecon", 4096, MQTTDriver::_instance, 5, NULL);
void MQTTDriver::supervise() {
if (!_configManager.getMqttConfig().enabled) {
_connectAttemptMs = 0;
return;
}
unsigned long now = millis();
if (_mqttClient.connected()) {
if (_heartbeatDue || now - _lastHeartbeatMs >= HEARTBEAT_INTERVAL) {
_heartbeatDue = false;
_lastHeartbeatMs = now;
publishHeartbeat();
}
if (_heartbeatPendingId != 0 && now - _heartbeatSentMs > HEARTBEAT_ACK_TIMEOUT) {
forceReset("heartbeat PUBACK timeout");
}
return;
}
// WiFi status straight from the driver rather than Networking's state
// machine, so a missed network callback can't strand MQTT offline.
if (WiFi.status() != WL_CONNECTED) {
_netUpSinceMs = 0;
return;
}
if (_netUpSinceMs == 0) _netUpSinceMs = now ? now : 1;
if (now - _netUpSinceMs < NETWORK_STABILIZATION_DELAY) return;
unsigned long attemptStart = _connectAttemptMs;
if (attemptStart != 0) {
if (now - attemptStart > CONNECT_STUCK_TIMEOUT) {
forceReset("connect attempt stuck");
}
return;
}
if ((long)(now - _nextConnectAtMs) >= 0) {
doConnect();
}
}
void MQTTDriver::forceReset(const char* reason) {
_diag.forcedResets++;
_diag.lastForcedResetReason = reason;
_diag.lastForcedResetMs = millis();
LOG_WARNING(TAG, "⚠️ MQTT connection wedged (%s) - forcing reset #%lu",
reason, (unsigned long)_diag.forcedResets);
// Forced close: drops the socket and resets the library to DISCONNECTED
// even when it's stuck mid-connect, so the next connect() isn't a no-op.
// onMqttDisconnect may or may not fire from inside this call.
_mqttClient.disconnect(true);
_heartbeatPendingId = 0;
_connectAttemptMs = 0;
unsigned long earliest = millis() + MQTT_RECONNECT_BASE_DELAY;
if ((long)(_nextConnectAtMs - earliest) < 0) _nextConnectAtMs = earliest;
}
void MQTTDriver::writeStatus(JsonObject out) const {
unsigned long now = millis();
out["enabled"] = _configManager.getMqttConfig().enabled;
out["connected"] = _mqttClient.connected();
out["connected_for_ms"] = _diag.connectedSinceMs ? now - _diag.connectedSinceMs : 0;
out["connects"] = _diag.connects;
out["disconnects"] = _diag.disconnects;
out["reconnect_attempts"] = _reconnectAttempts;
out["last_disconnect_reason"] = _diag.lastDisconnectReason;
out["last_disconnect_ago_ms"] = _diag.lastDisconnectMs ? now - _diag.lastDisconnectMs : 0;
out["forced_resets"] = _diag.forcedResets;
out["last_forced_reset_reason"] = _diag.lastForcedResetReason;
out["last_forced_reset_ago_ms"] = _diag.lastForcedResetMs ? now - _diag.lastForcedResetMs : 0;
out["wifi_connected"] = WiFi.status() == WL_CONNECTED;
out["free_heap"] = ESP.getFreeHeap();
}
// ═══════════════════════════════════════════════════════════════════════════════════
// HEARTBEAT FUNCTIONALITY
// ═══════════════════════════════════════════════════════════════════════════════════
void MQTTDriver::startHeartbeat() {
if (_heartbeatTimer) {
LOG_INFO(TAG, "💓 Starting MQTT heartbeat (every %d seconds)", HEARTBEAT_INTERVAL / 1000);
// Publish first heartbeat immediately
publishHeartbeat();
// Start periodic timer
xTimerStart(_heartbeatTimer, 0);
}
}
void MQTTDriver::stopHeartbeat() {
if (_heartbeatTimer) {
xTimerStop(_heartbeatTimer, 0);
_heartbeatTaskHandle = nullptr;
LOG_INFO(TAG, "❤️ Stopped MQTT heartbeat");
}
}
void MQTTDriver::publishHeartbeat() {
if (!_mqttClient.connected()) {
LOG_WARNING(TAG, "⚠️ Cannot publish heartbeat - MQTT not connected");
return;
}
if (!_mqttClient.connected()) return;
if (!_configManager.getMqttTopicConfig().heartbeat) return;
if (!hasHeapForPublish()) return; // skip building the JsonDocument too, not just the publish
@@ -481,9 +483,14 @@ void MQTTDriver::publishHeartbeat() {
serializeJson(doc, heartbeatMessage);
// Publish to heartbeat topic with RETAIN flag
// QoS 1 on purpose — its PUBACK is the liveness probe (HEARTBEAT_ACK_TIMEOUT).
uint16_t packetId = _mqttClient.publish(_heartbeatTopic.c_str(), 1, true, heartbeatMessage.c_str());
if (packetId > 0) {
if (_heartbeatPendingId == 0) { // keep timing the oldest unacked one
_heartbeatSentMs = millis();
_heartbeatPendingId = packetId;
}
LOG_DEBUG(TAG, "💓 Published heartbeat (retained) - state: %s, IP: %s, Uptime: %lums",
ds.state.c_str(), _networking.getLocalIP().c_str(), uptimeMs);
} else {
@@ -491,47 +498,6 @@ void MQTTDriver::publishHeartbeat() {
}
}
void MQTTDriver::mqttHeartbeatTaskFn(void* param) {
MQTTDriver* client = static_cast<MQTTDriver*>(param);
client->publishHeartbeat();
client->_heartbeatTaskHandle = nullptr;
vTaskDelete(NULL);
}
void MQTTDriver::heartbeatTimerCallback(TimerHandle_t xTimer) {
if (MQTTDriver::_instance) {
// Guard: skip if previous heartbeat task is still running
if (MQTTDriver::_instance->_heartbeatTaskHandle != nullptr) {
return;
}
xTaskCreate(mqttHeartbeatTaskFn, "mqttHB", 4096, MQTTDriver::_instance, 3,
&MQTTDriver::_instance->_heartbeatTaskHandle);
}
}
// ═══════════════════════════════════════════════════════════════════════════════════
// NETWORK STABILIZATION - NON-BLOCKING TIMER APPROACH
// ═══════════════════════════════════════════════════════════════════════════════════
void MQTTDriver::connectAfterStabilization() {
LOG_DEBUG(TAG, "Network stabilization complete - connecting to MQTT");
connect();
}
void MQTTDriver::mqttConnectTaskFn(void* param) {
// Runs in its own task so LOG calls don't overflow the Tmr Svc stack
MQTTDriver* client = static_cast<MQTTDriver*>(param);
client->connectAfterStabilization();
vTaskDelete(NULL);
}
void MQTTDriver::networkStabilizationTimerCallback(TimerHandle_t xTimer) {
if (MQTTDriver::_instance) {
// Defer to a task — timer callbacks run in Tmr Svc (2KB stack), not enough for connect()
xTaskCreate(mqttConnectTaskFn, "mqttConnect", 4096, MQTTDriver::_instance, 5, NULL);
}
}
// ═══════════════════════════════════════════════════════════════════════════════════
// EXPONENTIAL BACKOFF CALCULATION
// ═══════════════════════════════════════════════════════════════════════════════════
@@ -544,11 +510,12 @@ unsigned long MQTTDriver::getReconnectDelay() {
// After quick retries: Exponential backoff
// Formula: base_delay * 2^(attempts - quick_retries)
// Examples: 10s, 20s, 40s, 80s, 160s, 300s (capped at 5 minutes)
// Examples: 10s, 20s, 40s, 60s (capped at 1 minute)
uint8_t backoffPower = _reconnectAttempts - MQTT_MAX_QUICK_RETRIES;
if (backoffPower > 8) backoffPower = 8; // already past the cap; avoids shift overflow
unsigned long delay = MQTT_RECONNECT_BASE_DELAY * (1 << backoffPower); // 2^backoffPower
// Cap at maximum delay (5 minutes)
// Cap at maximum delay (1 minute)
if (delay > MQTT_RECONNECT_MAX_DELAY) {
delay = MQTT_RECONNECT_MAX_DELAY;
}
@@ -7,6 +7,13 @@
* Handles broker connection, auth, publish/subscribe, reconnect with exponential
* backoff, and heartbeat. Wrapped by MQTTTransport for CommandBus integration.
*
* QoS policy: everything is published at 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 only resumes on the next
* ~500ms TCP poll), so each QoS 1 message cost a full round trip plus up to
* half a second of head-of-line blocking for whatever was queued behind it.
* With cleanSession=true on both ends, QoS 1 never bought redelivery anyway.
*
* 📋 VERSION: 3.0 (AsyncMqttClient-based)
* 📅 DATE: 2025-01-04
* 👨‍💻 AUTHOR: Advanced Bell Systems
@@ -18,6 +25,7 @@
#include <Arduino.h>
#include <AsyncMqttClient.h>
#include <functional>
#include <ArduinoJson.h>
class ConfigManager;
class Networking;
@@ -38,7 +46,8 @@ public:
void begin();
/**
* @brief Connect to MQTT broker
* @brief Request a connection to the broker now (resets backoff). The
* supervisor task performs the actual connect on its next tick.
*/
void connect();
@@ -62,7 +71,7 @@ public:
* @return Packet ID (0 if failed, MQTT disabled, low heap, or the "command"
* topic switch is off — control/ack shares that switch with control/command)
*/
uint16_t publishAck(const String& payload, int qos = 1, bool retain = false);
uint16_t publishAck(const String& payload, int qos = 0, bool retain = false);
/**
* @brief Publish to an absolute, fully-qualified topic (no prefix applied).
@@ -136,6 +145,23 @@ public:
*/
void applyCommandTopicSwitch(bool enabled);
/**
* @brief Connection-health counters since boot, for post-mortem of "MQTT
* went silent" incidents. Exposed via mqtt.status — which works over
* WebSocket too, exactly when MQTT itself can't be asked.
*/
struct Diagnostics {
uint32_t connects = 0;
uint32_t disconnects = 0;
uint32_t forcedResets = 0;
const char* lastDisconnectReason = "";
unsigned long lastDisconnectMs = 0;
const char* lastForcedResetReason = "";
unsigned long lastForcedResetMs = 0;
unsigned long connectedSinceMs = 0; // 0 = not connected
};
void writeStatus(JsonObject out) const;
// Minimum free heap (bytes) required before attempting a publish. Below this,
// AsyncMqttClient's internal packet-buffer allocation risks failing outright —
// this SDK build has CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE=0, so a failed
@@ -176,6 +202,7 @@ private:
* @brief Subscribe to control topic
*/
void subscribe();
void doConnect();
/**
* @brief MQTT event handlers
@@ -187,32 +214,52 @@ private:
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total);
void onMqttPublish(uint16_t packetId);
// Reconnection Timer with Exponential Backoff
TimerHandle_t _mqttReconnectTimer;
// ── Supervisor ────────────────────────────────────────────────────────────
// ONE persistent task owns everything time-driven: (re)connect with backoff,
// network stabilization, the 30s heartbeat, and wedge detection. It replaced
// three FreeRTOS timers that each spawned a short-lived task per firing —
// a single failed xTaskCreate() (fragmented heap after days of uptime) ended
// a one-shot reconnect chain for good, leaving MQTT dead until reboot while
// WebSocket kept working. See docs/features/feature-catalog.md F-071.
TaskHandle_t _supervisorTask;
static void supervisorTaskFn(void* param);
void supervise();
void wakeSupervisor();
void forceReset(const char* reason);
static const unsigned long SUPERVISOR_TICK_MS = 500;
static const unsigned long NETWORK_STABILIZATION_DELAY = 2000; // 2 seconds after WiFi is up
static const unsigned long MQTT_RECONNECT_BASE_DELAY = 5000; // 5 seconds base
static const unsigned long MQTT_RECONNECT_MAX_DELAY = 300000; // 5 minutes max
static const unsigned long MQTT_RECONNECT_MAX_DELAY = 60000; // 1 minute max
static const uint8_t MQTT_MAX_QUICK_RETRIES = 3; // Try 3 times quickly
uint8_t _reconnectAttempts; // Track failed attempts
unsigned long _lastConnectionAttempt; // Track last attempt time
void attemptReconnection();
static void mqttReconnectTimerCallback(TimerHandle_t xTimer);
static void mqttReconnectTaskFn(void* param);
unsigned long getReconnectDelay(); // Calculate backoff delay
// A connect() that produces neither CONNACK nor a disconnect callback within
// this window means AsyncMqttClient is wedged in CONNECTING/DISCONNECTING
// (it ignores AsyncClient::connect()'s return value, and a failed tcp_close
// never fires onDisconnect) — every later connect() would silently no-op.
static const unsigned long CONNECT_STUCK_TIMEOUT = 30000;
// The heartbeat is the one QoS 1 publish; its PUBACK is our end-to-end
// liveness probe. No PUBACK in this window = connection is dead even if the
// library still says CONNECTED (half-open socket, stalled send queue).
static const unsigned long HEARTBEAT_ACK_TIMEOUT = 20000;
// Network Stabilization Timer (non-blocking replacement for delay)
TimerHandle_t _networkStabilizationTimer;
static const unsigned long NETWORK_STABILIZATION_DELAY = 2000; // 2 seconds
void connectAfterStabilization();
static void networkStabilizationTimerCallback(TimerHandle_t xTimer);
static void mqttConnectTaskFn(void* param);
volatile uint8_t _reconnectAttempts;
volatile unsigned long _nextConnectAtMs; // earliest time the next connect may start
volatile unsigned long _connectAttemptMs; // 0 = no attempt in flight
unsigned long _netUpSinceMs; // 0 = network down
unsigned long getReconnectDelay();
// Heartbeat Timer (30 seconds)
TimerHandle_t _heartbeatTimer;
// Heartbeat (30 seconds)
static const unsigned long HEARTBEAT_INTERVAL = 30000; // 30 seconds
TaskHandle_t _heartbeatTaskHandle; // Guard: only one heartbeat task at a time
volatile bool _heartbeatDue;
unsigned long _lastHeartbeatMs;
volatile uint16_t _heartbeatPendingId; // 0 = no heartbeat awaiting PUBACK
volatile unsigned long _heartbeatSentMs;
void publishHeartbeat();
static void heartbeatTimerCallback(TimerHandle_t xTimer);
static void mqttHeartbeatTaskFn(void* param);
void startHeartbeat();
void stopHeartbeat();
// Must outlive every CONNECT — AsyncMqttClient::setWill() stores the raw
// pointer, so a temporary String here sent freed heap as the LWT payload
// (the "gibberish on status/heartbeat" seen when a connection dropped).
String _willPayload;
Diagnostics _diag;
};
+28 -13
View File
@@ -2,7 +2,7 @@
## 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.
`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](../../../../docs/reference/vesper_mqtt_topic_spec_v2.md) for the full topic table, per-topic switches, and `req_id` correlation. Topics:
@@ -21,7 +21,7 @@ See [docs/reference/vesper_mqtt_topic_spec_v2.md](../../../../docs/reference/ves
| `void begin()` | Caches topic strings, registers AsyncMqttClient event handlers, configures broker host/port/credentials/keepalive, and registers the Last Will (see [LWT](#last-will-and-testament-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](#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 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](#gotchas--notes) below for why this exists. |
| `const String& getCommandTopic() const` / `getAckTopic()` / `getHeartbeatTopic()` / `getPlaybackTopic()` / `getReportsTopic()` / `getAlertsTopic()` / `getInfoTopic()` / `getLogsTopic()` / `getMetricsTopic()` | Cached full topic strings, available after `begin()`. |
@@ -30,8 +30,10 @@ See [docs/reference/vesper_mqtt_topic_spec_v2.md](../../../../docs/reference/ves
| `void setStateProvider(std::function<DeviceState()> provider)` | Registers the callback used to derive the heartbeat's `state`/`ok` fields — see [Heartbeat](#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()`. |
| `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. |
---
@@ -44,7 +46,7 @@ See [docs/reference/vesper_mqtt_topic_spec_v2.md](../../../../docs/reference/ves
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.
`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.
---
@@ -56,15 +58,30 @@ The constructor creates all three FreeRTOS timers. If timer creation fails (extr
| 4 | 10 seconds |
| 5 | 20 seconds |
| 6 | 40 seconds |
| 7+ | Capped at 300 seconds (5 minutes) |
| 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}`. `AsyncMqttClient` resends the Will on every CONNECT packet, including reconnects, so no manual re-registration is needed after the first `begin()`.
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](#graceful-disconnect) for the intentional case.
@@ -95,7 +112,7 @@ Once connected, a heartbeat is published immediately and then every 30 seconds t
`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.
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).
---
@@ -103,8 +120,8 @@ The heartbeat timer is stopped on disconnect and restarted on reconnect.
- `AsyncMqttClient` — broker protocol
- `ConfigManager` — 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_t` timers, one `TaskHandle_t` for heartbeat task guard
- `Networking` — IP and gateway for heartbeat (reconnect gating uses `WiFi.status()` directly)
- FreeRTOS — one persistent supervisor task, woken by task notifications
- `Logging`
---
@@ -112,9 +129,7 @@ The heartbeat timer is stopped on disconnect and restarted on reconnect.
## 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.
- **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.
- **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.
@@ -9,12 +9,13 @@ MQTTHandler::MQTTHandler(ConfigManager& configManager, MQTTDriver& mqttClient)
: _configManager(configManager), _mqttClient(mqttClient) {}
std::vector<String> MQTTHandler::commands() const {
return { "mqtt.enable", "mqtt.disable", "mqtt.get_config",
return { "mqtt.enable", "mqtt.disable", "mqtt.get_config", "mqtt.status",
"mqtt.get_topics", "mqtt.set_topics" };
}
CommandResult MQTTHandler::execute(const CommandEnvelope& envelope) {
if (envelope.command == "mqtt.get_config") return handleGetConfig(envelope);
if (envelope.command == "mqtt.status") return handleStatus(envelope);
if (envelope.command == "mqtt.get_topics") return handleGetTopics(envelope);
if (envelope.command == "mqtt.set_topics") return handleSetTopics(envelope);
@@ -51,6 +52,15 @@ CommandResult MQTTHandler::handleGetConfig(const CommandEnvelope& e) {
return CommandResult::ok("mqtt.get_config", doc);
}
// Connection health since boot. Most useful over WebSocket: when the cloud
// sees a device as offline but the local app still works, this says whether
// the device knows it's disconnected, why, and whether self-recovery fired.
CommandResult MQTTHandler::handleStatus(const CommandEnvelope& e) {
JsonDocument doc;
_mqttClient.writeStatus(doc.to<JsonObject>());
return CommandResult::ok("mqtt.status", doc);
}
CommandResult MQTTHandler::handleGetTopics(const CommandEnvelope& e) {
const auto& t = _configManager.getMqttTopicConfig();
JsonDocument doc;
@@ -20,6 +20,7 @@ private:
MQTTDriver& _mqttClient;
CommandResult handleGetConfig(const CommandEnvelope& e);
CommandResult handleStatus(const CommandEnvelope& e);
CommandResult handleGetTopics(const CommandEnvelope& e);
CommandResult handleSetTopics(const CommandEnvelope& e);
};
@@ -61,6 +61,6 @@ Responses are published to `control/ack`:
- **`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`.
- **No per-message QoS.** Command replies and broadcasts are published at QoS 0 (see F-071 — QoS 1 caused head-of-line blocking in AsyncMqttClient). 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.
+2 -2
View File
@@ -278,7 +278,7 @@ bool Logging::allowMqttPublish(const char* tag) {
payload += " log message(s) (MQTT rate limit)\",\"timestamp\":";
payload += now;
payload += "}";
_mqttCallback(_mqttLogTopic, payload, 1);
_mqttCallback(_mqttLogTopic, payload, 0);
state.droppedSinceLastPublish = 0;
state.tokens--; // the summary line itself costs a token
return state.tokens > 0;
@@ -325,7 +325,7 @@ void Logging::publishToMqtt(LogLevel level, const char* levelStr, const char* ta
payload += millis();
payload += "}";
_mqttCallback(_mqttLogTopic, payload, 1);
_mqttCallback(_mqttLogTopic, payload, 0);
isPublishing = false;
}
+7
View File
@@ -383,6 +383,13 @@ void Networking::onWiFiConnected() {
setState(NetworkState::CONNECTED_WIFI);
setActiveConnection(ConnectionType::WIFI);
// Modem sleep off (the Arduino default is WIFI_PS_MIN_MODEM). With it on, the
// radio dozes between AP beacons and inbound packets wait for the next DTIM —
// 100ms to 1s+ per packet depending on the AP, which showed up as laggy app
// commands and status updates. Mains-powered device; the power cost is moot.
// Re-applied on every connect since WiFi.mode() changes can reset it.
WiFi.setSleep(false);
// Reset failure/phase counters on successful connection
_wifiConnectionFailures = 0;
_triedSavedCredentials = false;