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
@@ -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;
}