feat(MQTT): confirmed delivery for playback/reports; vendor AsyncMqttClient; pin all deps (F-073)
- MQTTDriver::publishConfirmed(): QoS 1 + PUBACK tracking (8 s; heartbeat 20 s). A missed PUBACK forces a reconnect. status/playback relies on the existing republish-current-state-on-connect; control/reports are resent after the next CONNACK (newest 4). Publish + registration under one recursive mutex since the PUBACK can arrive before publish() returns. - AsyncMqttClient vendored into lib/ (upstream 3d93fc7) with one patch: _onPubAck()/_onPubComp() call _handleQueue(), so a QoS 1 message delays the next packet by one RTT instead of RTT + up to ~500 ms. - platformio.ini: platform and every library pinned to the exact versions already being built (git deps by commit). Clean-libdeps rebuild verified to resolve the same AsyncTCP and the vendored AsyncMqttClient. - Removed board_build.cmake_extra_args (timer stack): no effect on Arduino builds, the SDK is precompiled with 2048. Replaced by a warning comment. - mqtt.status gains resent_messages and the new forced-reset reasons. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -681,7 +681,9 @@ void CommunicationRouter::publishPlayback(const PlaybackSnapshot& snapshot) {
|
||||
|
||||
String out;
|
||||
serializeJson(doc, out);
|
||||
_mqttClient.publishDirect(_mqttClient.getPlaybackTopic(), out, 0, true);
|
||||
// QoS 1 + PUBACK tracking: playback is what the apps act on. Not resent on
|
||||
// reconnect — onConnect republishes the *current* snapshot instead (F-073).
|
||||
_mqttClient.publishConfirmed(_mqttClient.getPlaybackTopic(), out, true, false);
|
||||
LOG_DEBUG(TAG, "Playback published: %s", snapshot.action);
|
||||
}
|
||||
|
||||
@@ -699,7 +701,8 @@ 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, 0, false);
|
||||
// QoS 1 + PUBACK tracking, resent after a reconnect if unconfirmed (F-073).
|
||||
_mqttClient.publishConfirmed(_mqttClient.getReportsTopic(), out, false, true);
|
||||
LOG_DEBUG(TAG, "Report published: %s", type.c_str());
|
||||
}
|
||||
|
||||
|
||||
@@ -48,8 +48,8 @@
|
||||
| `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 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 publishPlayback(const String& action, uint32_t timeElapsedSec, uint64_t projectedRunTimeMs)` | Publishes a playback transition to `vesper/{uid}/status/playback` (QoS 1 via `publishConfirmed()`, 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 via `publishConfirmed()`, resent after reconnect if unconfirmed, 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. |
|
||||
|
||||
@@ -22,10 +22,11 @@ MQTTDriver::MQTTDriver(ConfigManager& configManager, Networking& networking)
|
||||
, _netUpSinceMs(0)
|
||||
, _heartbeatDue(false)
|
||||
, _lastHeartbeatMs(0)
|
||||
, _heartbeatPendingId(0)
|
||||
, _heartbeatSentMs(0) {
|
||||
, _pendingMutex(xSemaphoreCreateRecursiveMutex())
|
||||
, _resendDue(false) {
|
||||
|
||||
_instance = this; // Set static instance pointer
|
||||
_pending.reserve(MAX_PENDING_ACKS);
|
||||
}
|
||||
|
||||
MQTTDriver::~MQTTDriver() {
|
||||
@@ -195,6 +196,91 @@ uint16_t MQTTDriver::publishDirect(const String& fullTopic, const String& payloa
|
||||
return packetId;
|
||||
}
|
||||
|
||||
uint16_t MQTTDriver::publishConfirmed(const String& fullTopic, const String& payload, bool retain, bool resendOnReconnect) {
|
||||
if (!_mqttClient.connected()) return 0;
|
||||
if (!hasHeapForPublish()) return 0;
|
||||
|
||||
uint16_t packetId = publishTracked(fullTopic, payload, retain, CONFIRMED_ACK_TIMEOUT,
|
||||
resendOnReconnect ? "report PUBACK timeout" : "playback PUBACK timeout",
|
||||
resendOnReconnect);
|
||||
if (packetId > 0) {
|
||||
LOG_DEBUG(TAG, "Published (confirmed) to %s (packetId=%d)", fullTopic.c_str(), packetId);
|
||||
}
|
||||
return packetId;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// PUBACK TRACKING
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
uint16_t MQTTDriver::publishTracked(const String& topic, const String& payload, bool retain,
|
||||
unsigned long timeoutMs, const char* label, bool resend) {
|
||||
PendingAck p;
|
||||
p.label = label;
|
||||
p.resend = resend;
|
||||
if (resend) {
|
||||
p.topic = topic;
|
||||
p.payload = payload;
|
||||
}
|
||||
p.retain = retain;
|
||||
|
||||
// Publish and register under the same lock: the PUBACK can come back on
|
||||
// the async_tcp task before publish() even returns here, and onMqttPublish
|
||||
// must find the entry or it would time out and force a needless reset.
|
||||
// Recursive: publish() can synchronously end in onMqttDisconnect →
|
||||
// abandonPending() on this same task.
|
||||
xSemaphoreTakeRecursive(_pendingMutex, portMAX_DELAY);
|
||||
uint16_t packetId = _mqttClient.publish(topic.c_str(), 1, retain, payload.c_str());
|
||||
if (packetId > 0) {
|
||||
p.id = packetId;
|
||||
p.deadlineMs = millis() + timeoutMs;
|
||||
if (_pending.size() >= MAX_PENDING_ACKS) {
|
||||
// Eight unacked QoS 1 messages means the connection is already
|
||||
// stalled; keep the oldest — its deadline triggers the reset anyway.
|
||||
_pending.erase(_pending.begin() + 1);
|
||||
}
|
||||
_pending.push_back(std::move(p));
|
||||
}
|
||||
xSemaphoreGiveRecursive(_pendingMutex);
|
||||
return packetId;
|
||||
}
|
||||
|
||||
const char* MQTTDriver::expiredPendingLabel(unsigned long now) {
|
||||
const char* label = nullptr;
|
||||
xSemaphoreTakeRecursive(_pendingMutex, portMAX_DELAY);
|
||||
for (const auto& p : _pending) {
|
||||
if ((long)(now - p.deadlineMs) >= 0) { label = p.label; break; }
|
||||
}
|
||||
xSemaphoreGiveRecursive(_pendingMutex);
|
||||
return label;
|
||||
}
|
||||
|
||||
void MQTTDriver::abandonPending() {
|
||||
xSemaphoreTakeRecursive(_pendingMutex, portMAX_DELAY);
|
||||
for (auto& p : _pending) {
|
||||
if (p.resend) _resendQueue.push_back(std::move(p));
|
||||
}
|
||||
_pending.clear();
|
||||
while (_resendQueue.size() > MAX_RESEND) {
|
||||
_resendQueue.erase(_resendQueue.begin()); // keep the newest
|
||||
}
|
||||
xSemaphoreGiveRecursive(_pendingMutex);
|
||||
}
|
||||
|
||||
void MQTTDriver::flushResendQueue() {
|
||||
std::vector<PendingAck> toSend;
|
||||
xSemaphoreTakeRecursive(_pendingMutex, portMAX_DELAY);
|
||||
toSend.swap(_resendQueue);
|
||||
xSemaphoreGiveRecursive(_pendingMutex);
|
||||
|
||||
for (const auto& p : toSend) {
|
||||
if (publishConfirmed(p.topic, p.payload, p.retain, true) > 0) {
|
||||
_diag.resentMessages++;
|
||||
LOG_INFO(TAG, "Resent unconfirmed message to %s after reconnect", p.topic.c_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MQTTDriver::setCallback(MessageCallback callback) {
|
||||
_messageCallback = callback;
|
||||
}
|
||||
@@ -239,16 +325,21 @@ void MQTTDriver::onMqttConnect(bool sessionPresent) {
|
||||
// Reset reconnection attempts on successful connection
|
||||
_reconnectAttempts = 0;
|
||||
_connectAttemptMs = 0;
|
||||
_heartbeatPendingId = 0;
|
||||
_diag.connects++;
|
||||
|
||||
// Anything still tracked belongs to the previous connection (e.g. registered
|
||||
// after a disconnect that fired inside publish()) and would time out here.
|
||||
// Before the onConnect callback below republishes playback.
|
||||
abandonPending();
|
||||
_diag.connectedSinceMs = millis();
|
||||
|
||||
// Subscribe to control topic
|
||||
subscribe();
|
||||
|
||||
// First heartbeat goes out from the supervisor right away, not from here —
|
||||
// this callback runs on the async_tcp task.
|
||||
// First heartbeat (and any resends) go out from the supervisor right away,
|
||||
// not from here — this callback runs on the async_tcp task.
|
||||
_heartbeatDue = true;
|
||||
_resendDue = true;
|
||||
wakeSupervisor();
|
||||
|
||||
if (_onConnectCallback) {
|
||||
@@ -288,8 +379,8 @@ void MQTTDriver::onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
|
||||
_diag.lastDisconnectReason = reasonStr;
|
||||
_diag.lastDisconnectMs = millis();
|
||||
_diag.connectedSinceMs = 0;
|
||||
_heartbeatPendingId = 0;
|
||||
_connectAttemptMs = 0;
|
||||
abandonPending();
|
||||
|
||||
if (!mqttConfig.enabled) {
|
||||
LOG_INFO(TAG, "❌ Disconnected from MQTT broker - Reason: %s (%d) - MQTT disabled, not reconnecting",
|
||||
@@ -340,9 +431,11 @@ void MQTTDriver::onMqttMessage(char* topic, char* payload, AsyncMqttClientMessag
|
||||
}
|
||||
|
||||
void MQTTDriver::onMqttPublish(uint16_t packetId) {
|
||||
if (packetId == _heartbeatPendingId) {
|
||||
_heartbeatPendingId = 0;
|
||||
xSemaphoreTakeRecursive(_pendingMutex, portMAX_DELAY);
|
||||
for (auto it = _pending.begin(); it != _pending.end(); ++it) {
|
||||
if (it->id == packetId) { _pending.erase(it); break; }
|
||||
}
|
||||
xSemaphoreGiveRecursive(_pendingMutex);
|
||||
LOG_DEBUG(TAG, "MQTT publish acknowledged (packetId=%d)", packetId);
|
||||
}
|
||||
|
||||
@@ -377,8 +470,12 @@ void MQTTDriver::supervise() {
|
||||
_lastHeartbeatMs = now;
|
||||
publishHeartbeat();
|
||||
}
|
||||
if (_heartbeatPendingId != 0 && now - _heartbeatSentMs > HEARTBEAT_ACK_TIMEOUT) {
|
||||
forceReset("heartbeat PUBACK timeout");
|
||||
if (_resendDue) {
|
||||
_resendDue = false;
|
||||
flushResendQueue();
|
||||
}
|
||||
if (const char* expired = expiredPendingLabel(now)) {
|
||||
forceReset(expired);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -417,7 +514,7 @@ void MQTTDriver::forceReset(const char* reason) {
|
||||
// onMqttDisconnect may or may not fire from inside this call.
|
||||
_mqttClient.disconnect(true);
|
||||
|
||||
_heartbeatPendingId = 0;
|
||||
abandonPending();
|
||||
_connectAttemptMs = 0;
|
||||
unsigned long earliest = millis() + MQTT_RECONNECT_BASE_DELAY;
|
||||
if ((long)(_nextConnectAtMs - earliest) < 0) _nextConnectAtMs = earliest;
|
||||
@@ -436,6 +533,7 @@ void MQTTDriver::writeStatus(JsonObject out) const {
|
||||
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["resent_messages"] = _diag.resentMessages;
|
||||
out["wifi_connected"] = WiFi.status() == WL_CONNECTED;
|
||||
out["free_heap"] = ESP.getFreeHeap();
|
||||
}
|
||||
@@ -484,13 +582,10 @@ void MQTTDriver::publishHeartbeat() {
|
||||
|
||||
// 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());
|
||||
uint16_t packetId = publishTracked(_heartbeatTopic, heartbeatMessage, true,
|
||||
HEARTBEAT_ACK_TIMEOUT, "heartbeat PUBACK timeout", false);
|
||||
|
||||
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 {
|
||||
|
||||
@@ -7,12 +7,16 @@
|
||||
* 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.
|
||||
* QoS policy (F-072/F-073): QoS 1 only where losing a message matters —
|
||||
* the heartbeat, status/playback and control/reports — and those go through
|
||||
* publishConfirmed(), which tracks the PUBACK. A missing PUBACK means the
|
||||
* connection is dead, so the supervisor resets it; playback state is then
|
||||
* republished fresh on reconnect, reports are resent. Plain QoS 1 alone would
|
||||
* not recover anything here: with cleanSession=true the library drops unacked
|
||||
* packets on reconnect. Everything else (acks, alerts, info, logs, metrics)
|
||||
* is QoS 0. The queue is sent strictly in order and each QoS 1 message holds
|
||||
* what's behind it for one round trip (the vendored library is patched so it
|
||||
* no longer adds a ~500ms poll wait on top — lib/AsyncMqttClient/VENDORED.md).
|
||||
*
|
||||
* 📋 VERSION: 3.0 (AsyncMqttClient-based)
|
||||
* 📅 DATE: 2025-01-04
|
||||
@@ -26,6 +30,7 @@
|
||||
#include <AsyncMqttClient.h>
|
||||
#include <functional>
|
||||
#include <ArduinoJson.h>
|
||||
#include <vector>
|
||||
|
||||
class ConfigManager;
|
||||
class Networking;
|
||||
@@ -85,6 +90,20 @@ public:
|
||||
*/
|
||||
uint16_t publishDirect(const String& fullTopic, const String& payload, int qos = 0, bool retain = false);
|
||||
|
||||
/**
|
||||
* @brief QoS 1 publish whose PUBACK is tracked. No PUBACK within
|
||||
* CONFIRMED_ACK_TIMEOUT means the connection is dead: the supervisor
|
||||
* resets it and reconnects. Same heap guard as publishDirect(); the
|
||||
* caller still does topic-switch gating.
|
||||
* @param resendOnReconnect true for event topics (control/reports): the
|
||||
* message is kept and republished after the reconnect. false for
|
||||
* retained state topics (status/playback) whose owner republishes the
|
||||
* *current* state on every connect — resending the old one would
|
||||
* overwrite fresh state with stale.
|
||||
* @return Packet ID (0 if not sent)
|
||||
*/
|
||||
uint16_t publishConfirmed(const String& fullTopic, const String& payload, bool retain, bool resendOnReconnect);
|
||||
|
||||
/**
|
||||
* @brief Set message received callback
|
||||
*/
|
||||
@@ -159,6 +178,7 @@ public:
|
||||
const char* lastForcedResetReason = "";
|
||||
unsigned long lastForcedResetMs = 0;
|
||||
unsigned long connectedSinceMs = 0; // 0 = not connected
|
||||
uint32_t resentMessages = 0; // reports republished after a reconnect
|
||||
};
|
||||
void writeStatus(JsonObject out) const;
|
||||
|
||||
@@ -237,10 +257,12 @@ private:
|
||||
// (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).
|
||||
// PUBACK deadlines for tracked QoS 1 publishes. No PUBACK in time = the
|
||||
// connection is dead even if the library still says CONNECTED (half-open
|
||||
// socket, stalled send queue). The heartbeat is the background probe;
|
||||
// playback/reports get a tighter window because they're what the apps wait on.
|
||||
static const unsigned long HEARTBEAT_ACK_TIMEOUT = 20000;
|
||||
static const unsigned long CONFIRMED_ACK_TIMEOUT = 8000;
|
||||
|
||||
volatile uint8_t _reconnectAttempts;
|
||||
volatile unsigned long _nextConnectAtMs; // earliest time the next connect may start
|
||||
@@ -252,10 +274,32 @@ private:
|
||||
static const unsigned long HEARTBEAT_INTERVAL = 30000; // 30 seconds
|
||||
volatile bool _heartbeatDue;
|
||||
unsigned long _lastHeartbeatMs;
|
||||
volatile uint16_t _heartbeatPendingId; // 0 = no heartbeat awaiting PUBACK
|
||||
volatile unsigned long _heartbeatSentMs;
|
||||
void publishHeartbeat();
|
||||
|
||||
// Tracked QoS 1 publishes awaiting PUBACK. Touched from the async_tcp task
|
||||
// (onMqttPublish), the supervisor, and whichever task publishes — guarded
|
||||
// by a recursive mutex (not a spinlock: entries own Strings, which allocate).
|
||||
struct PendingAck {
|
||||
uint16_t id;
|
||||
unsigned long deadlineMs;
|
||||
const char* label; // static string, used as forced-reset reason
|
||||
bool resend;
|
||||
String topic; // only kept when resend == true
|
||||
String payload;
|
||||
bool retain;
|
||||
};
|
||||
static const size_t MAX_PENDING_ACKS = 8;
|
||||
static const size_t MAX_RESEND = 4;
|
||||
SemaphoreHandle_t _pendingMutex;
|
||||
std::vector<PendingAck> _pending;
|
||||
std::vector<PendingAck> _resendQueue; // waiting for the next CONNACK
|
||||
volatile bool _resendDue;
|
||||
uint16_t publishTracked(const String& topic, const String& payload, bool retain,
|
||||
unsigned long timeoutMs, const char* label, bool resend);
|
||||
const char* expiredPendingLabel(unsigned long now); // nullptr if none
|
||||
void abandonPending(); // connection gone: drop, or keep for resend
|
||||
void flushResendQueue();
|
||||
|
||||
// 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).
|
||||
|
||||
@@ -22,6 +22,7 @@ See [docs/reference/vesper_mqtt_topic_spec_v2.md](../../../../docs/reference/ves
|
||||
| `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 = 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 publishConfirmed(const String& fullTopic, const String& payload, bool retain, bool resendOnReconnect)` | QoS 1 publish with PUBACK tracking (8 s deadline). A missed deadline makes the supervisor reset the connection. `resendOnReconnect=true` keeps the message and republishes it after the reconnect (event topics); `false` for retained state the caller republishes itself on connect. Used for `status/playback` (false) and `control/reports` (true). |
|
||||
| `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()`. |
|
||||
@@ -69,13 +70,13 @@ The supervisor forces a reset (`AsyncMqttClient::disconnect(true)`, then a norma
|
||||
| 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. |
|
||||
| A tracked QoS 1 publish has no PUBACK by its deadline: heartbeat 20 s (`"heartbeat PUBACK timeout"`), playback / report 8 s (`"playback PUBACK timeout"`, `"report 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.
|
||||
QoS 1 only for the heartbeat, `status/playback` and `control/reports`, all with PUBACK tracking; everything else QoS 0. The library sends its queue strictly in order and holds later packets until a QoS 1 PUBACK arrives, so each QoS 1 message costs whatever is behind it one round trip. Upstream also waited for the next ~500 ms TCP poll after each PUBACK; the vendored copy in `lib/AsyncMqttClient` is patched to send immediately (see its `VENDORED.md`). Plain QoS 1 recovers nothing here — with `cleanSession=true` the library drops unacked packets on reconnect — which is why delivery is guaranteed by the tracking + reset + republish/resend path instead.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -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 0 (see F-071 — QoS 1 caused head-of-line blocking in AsyncMqttClient). Heartbeats use QoS 1 with `retain = true`.
|
||||
- **No per-message QoS.** Command replies and broadcasts are published at QoS 0 (see F-072/F-073). 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.
|
||||
|
||||
Reference in New Issue
Block a user