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:
2026-10-15 21:50:54 +03:00
co-authored by Claude Opus 5.5
parent cec4db4894
commit c43d9ae11c
59 changed files with 2674 additions and 69 deletions
@@ -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 {