Full MQTT topic rebuild per docs/reference/vesper_mqtt_topic_spec_v2.md.
Only the MQTT transport path changed — WebSocket, HTTP, and UART are untouched.
- control/command (in) + control/ack (out, strictly replies) replace the old
control/data pair; new control/reports for critical unsolicited events
(bell overload) that don't belong on the strictly-reply ack channel
- status/playback split out for playback transitions only
- status/alerts + status/info renamed to system/alerts + system/info, both
now correctly retained; new system/logs and system/metrics (diagnostics
report moved here from system/info, gained bell strike/heat data)
- LWT registered for the first time — status/heartbeat gets
{"state":"offline","ok":false} on an unclean disconnect; graceful
disconnect (mqtt.disable) announces offline explicitly since LWT doesn't
fire on a clean disconnect
- heartbeat payload flattened, gains independently-derived state/ok fields
(via a new MQTTDriver::setStateProvider() wired from Player+HealthMonitor)
- optional req_id correlation added bus-wide (CommandEnvelope/CommandResult),
not MQTT-only, since any transport with multiple senders sharing one
channel has the same problem. Always optional — v1 clients unaffected.
- per-topic ON/OFF switches (ConfigManager::MqttTopicConfig, 8 flags) as
sub-switches under the existing mqtt.enable/disable master switch, so a
device can breathe by disabling topics it doesn't need. New
mqtt.get_topics/mqtt.set_topics commands; command switch applies live.
Bumped to v2.2.0. Verified: pio run -e vesper-std-v1 -e agnus-v1 both build clean.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
557 lines
22 KiB
C++
557 lines
22 KiB
C++
/*
|
|
* MQTTDRIVER.CPP - MQTT Protocol Driver Implementation
|
|
*/
|
|
|
|
#include "MQTTDriver.hpp"
|
|
|
|
#define TAG "MQTTClient"
|
|
#include "../../../ConfigManager/ConfigManager.hpp"
|
|
#include "../../../Networking/Networking.hpp"
|
|
#include "../../../Logging/Logging.hpp"
|
|
|
|
MQTTDriver* MQTTDriver::_instance = nullptr;
|
|
|
|
MQTTDriver::MQTTDriver(ConfigManager& configManager, Networking& networking)
|
|
: _configManager(configManager)
|
|
, _networking(networking)
|
|
, _messageCallback(nullptr)
|
|
, _mqttReconnectTimer(nullptr)
|
|
, _networkStabilizationTimer(nullptr)
|
|
, _heartbeatTimer(nullptr)
|
|
, _heartbeatTaskHandle(nullptr)
|
|
, _reconnectAttempts(0)
|
|
, _lastConnectionAttempt(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);
|
|
}
|
|
_mqttClient.disconnect();
|
|
}
|
|
|
|
void MQTTDriver::begin() {
|
|
LOG_INFO(TAG, "Initializing MQTT Async Client");
|
|
|
|
auto& mqttConfig = _configManager.getMqttConfig();
|
|
|
|
// Build topic strings (cache for performance) — see docs/reference/vesper_mqtt_topic_spec_v2.md
|
|
String deviceUID = _configManager.getDeviceUID();
|
|
_commandTopic = "vesper/" + deviceUID + "/control/command";
|
|
_ackTopic = "vesper/" + deviceUID + "/control/ack";
|
|
_heartbeatTopic = "vesper/" + deviceUID + "/status/heartbeat";
|
|
_playbackTopic = "vesper/" + deviceUID + "/status/playback";
|
|
_reportsTopic = "vesper/" + deviceUID + "/control/reports";
|
|
_alertsTopic = "vesper/" + deviceUID + "/system/alerts";
|
|
_infoTopic = "vesper/" + deviceUID + "/system/info";
|
|
_logsTopic = "vesper/" + deviceUID + "/system/logs";
|
|
_metricsTopic = "vesper/" + deviceUID + "/system/metrics";
|
|
_clientId = "vesper-" + deviceUID;
|
|
|
|
LOG_INFO(TAG, "MQTT Topics: command=%s, ack=%s, heartbeat=%s, playback=%s, reports=%s, alerts=%s, info=%s, logs=%s, metrics=%s",
|
|
_commandTopic.c_str(), _ackTopic.c_str(), _heartbeatTopic.c_str(), _playbackTopic.c_str(),
|
|
_reportsTopic.c_str(), _alertsTopic.c_str(), _infoTopic.c_str(), _logsTopic.c_str(), _metricsTopic.c_str());
|
|
|
|
// Setup event handlers
|
|
_mqttClient.onConnect([this](bool sessionPresent) {
|
|
this->onMqttConnect(sessionPresent);
|
|
});
|
|
|
|
_mqttClient.onDisconnect([this](AsyncMqttClientDisconnectReason reason) {
|
|
this->onMqttDisconnect(reason);
|
|
});
|
|
|
|
_mqttClient.onSubscribe([this](uint16_t packetId, uint8_t qos) {
|
|
this->onMqttSubscribe(packetId, qos);
|
|
});
|
|
|
|
_mqttClient.onUnsubscribe([this](uint16_t packetId) {
|
|
this->onMqttUnsubscribe(packetId);
|
|
});
|
|
|
|
_mqttClient.onMessage([this](char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
|
|
this->onMqttMessage(topic, payload, properties, len, index, total);
|
|
});
|
|
|
|
_mqttClient.onPublish([this](uint16_t packetId) {
|
|
this->onMqttPublish(packetId);
|
|
});
|
|
|
|
// Configure connection
|
|
_mqttClient.setServer(mqttConfig.host, mqttConfig.port);
|
|
_mqttClient.setCredentials(mqttConfig.user.c_str(), mqttConfig.password.c_str());
|
|
_mqttClient.setClientId(_clientId.c_str()); // Use member variable
|
|
_mqttClient.setKeepAlive(15);
|
|
_mqttClient.setCleanSession(true);
|
|
|
|
// Last Will and Testament — the broker publishes this to status/heartbeat
|
|
// (retained) automatically if the connection drops uncleanly (network loss,
|
|
// 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());
|
|
|
|
LOG_INFO(TAG, "✅ MQTT Async Client initialized");
|
|
}
|
|
|
|
String MQTTDriver::buildOfflinePayload() const {
|
|
JsonDocument doc;
|
|
doc["device_id"] = _configManager.getDeviceUID();
|
|
doc["state"] = "offline";
|
|
doc["ok"] = false;
|
|
String out;
|
|
serializeJson(doc, out);
|
|
return out;
|
|
}
|
|
|
|
void MQTTDriver::connect() {
|
|
auto& mqttConfig = _configManager.getMqttConfig();
|
|
|
|
// 🔥 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());
|
|
|
|
_mqttClient.connect();
|
|
|
|
LOG_INFO(TAG, "MQTT connect() called - waiting for async connection...");
|
|
}
|
|
|
|
void MQTTDriver::disconnect(bool graceful) {
|
|
if (graceful && _mqttClient.connected()) {
|
|
// LWT only fires on an *unclean* disconnect — announce offline explicitly
|
|
// before a clean one so status/heartbeat doesn't keep a stale "online"
|
|
// retained message around (e.g. before an OTA flash).
|
|
String offlinePayload = buildOfflinePayload();
|
|
_mqttClient.publish(_heartbeatTopic.c_str(), 1, true, offlinePayload.c_str());
|
|
LOG_INFO(TAG, "Published graceful offline heartbeat before disconnect");
|
|
}
|
|
_mqttClient.disconnect();
|
|
LOG_INFO(TAG, "Disconnected from MQTT broker");
|
|
}
|
|
|
|
bool MQTTDriver::hasHeapForPublish() const {
|
|
if (ESP.getFreeHeap() >= MIN_FREE_HEAP_FOR_PUBLISH) return true;
|
|
|
|
// Serial.printf directly, not LOG_* — MQTT-channel logging would try to publish
|
|
// this very warning, recursing straight back into the low-heap condition we're
|
|
// trying to avoid. Same reasoning as the disconnected-check below.
|
|
Serial.printf("[MQTTClient] Skipping publish - free heap %u below %u byte threshold\n",
|
|
(unsigned)ESP.getFreeHeap(), (unsigned)MIN_FREE_HEAP_FOR_PUBLISH);
|
|
return false;
|
|
}
|
|
|
|
uint16_t MQTTDriver::publishAck(const String& payload, int qos, bool retain) {
|
|
// Check if connected before attempting to publish
|
|
if (!_mqttClient.connected()) {
|
|
// Don't log error here - would cause infinite loop with MQTT logging
|
|
return 0;
|
|
}
|
|
if (!hasHeapForPublish()) return 0;
|
|
|
|
// control/ack shares the "command" topic switch with control/command — if a
|
|
// client somehow gets a reply queued while the switch just got turned off
|
|
// mid-flight, drop it rather than publish to a channel the operator disabled.
|
|
if (!_configManager.getMqttTopicConfig().command) return 0;
|
|
|
|
uint16_t packetId = _mqttClient.publish(_ackTopic.c_str(), qos, retain, payload.c_str());
|
|
|
|
if (packetId > 0) {
|
|
LOG_DEBUG(TAG, "Published to %s: %s (packetId=%d)", _ackTopic.c_str(), payload.c_str(), packetId);
|
|
}
|
|
// REMOVED: Error logging here to prevent infinite recursion with MQTT logs
|
|
|
|
return packetId;
|
|
}
|
|
|
|
uint16_t MQTTDriver::publishDirect(const String& fullTopic, const String& payload, int qos, bool retain) {
|
|
if (!_mqttClient.connected()) {
|
|
return 0;
|
|
}
|
|
if (!hasHeapForPublish()) return 0;
|
|
|
|
uint16_t packetId = _mqttClient.publish(fullTopic.c_str(), qos, retain, payload.c_str());
|
|
if (packetId > 0) {
|
|
LOG_DEBUG(TAG, "Published to %s (packetId=%d)", fullTopic.c_str(), packetId);
|
|
}
|
|
return packetId;
|
|
}
|
|
|
|
void MQTTDriver::setCallback(MessageCallback callback) {
|
|
_messageCallback = callback;
|
|
}
|
|
|
|
bool MQTTDriver::isConnected() const {
|
|
return _mqttClient.connected();
|
|
}
|
|
|
|
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
|
|
_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();
|
|
}
|
|
}
|
|
|
|
void MQTTDriver::onNetworkDisconnected() {
|
|
LOG_DEBUG(TAG, "Network disconnected - MQTT will auto-reconnect when network returns");
|
|
|
|
if (_mqttClient.connected()) {
|
|
_mqttClient.disconnect(true);
|
|
}
|
|
}
|
|
|
|
void MQTTDriver::subscribe() {
|
|
// Gated by the "command" topic switch — a device that doesn't need remote
|
|
// control (e.g. fleet-monitoring-only) can turn this off entirely and skip
|
|
// both control/command (this subscribe) and control/ack (its replies).
|
|
if (!_configManager.getMqttTopicConfig().command) {
|
|
LOG_INFO(TAG, "control/command subscription skipped — 'command' topic switch is off");
|
|
return;
|
|
}
|
|
uint16_t packetId = _mqttClient.subscribe(_commandTopic.c_str(), 1);
|
|
LOG_INFO(TAG, "📬 Subscribing to control/command topic: %s (packetId=%d)", _commandTopic.c_str(), packetId);
|
|
}
|
|
|
|
void MQTTDriver::onMqttConnect(bool sessionPresent) {
|
|
LOG_INFO(TAG, "✅ Connected to MQTT broker (session present: %s)", sessionPresent ? "yes" : "no");
|
|
LOG_INFO(TAG, "🔍 Free heap AFTER MQTT connect: %d bytes", ESP.getFreeHeap());
|
|
|
|
// Reset reconnection attempts on successful connection
|
|
_reconnectAttempts = 0;
|
|
|
|
// Subscribe to control topic
|
|
subscribe();
|
|
|
|
// 🔥 Start heartbeat timer
|
|
startHeartbeat();
|
|
|
|
if (_onConnectCallback) {
|
|
_onConnectCallback(sessionPresent);
|
|
}
|
|
}
|
|
|
|
void MQTTDriver::onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
|
|
auto& mqttConfig = _configManager.getMqttConfig();
|
|
|
|
const char* reasonStr;
|
|
switch(reason) {
|
|
case AsyncMqttClientDisconnectReason::TCP_DISCONNECTED:
|
|
reasonStr = "TCP disconnected";
|
|
break;
|
|
case AsyncMqttClientDisconnectReason::MQTT_UNACCEPTABLE_PROTOCOL_VERSION:
|
|
reasonStr = "Unacceptable protocol version";
|
|
break;
|
|
case AsyncMqttClientDisconnectReason::MQTT_IDENTIFIER_REJECTED:
|
|
reasonStr = "Identifier rejected";
|
|
break;
|
|
case AsyncMqttClientDisconnectReason::MQTT_SERVER_UNAVAILABLE:
|
|
reasonStr = "Server unavailable";
|
|
break;
|
|
case AsyncMqttClientDisconnectReason::MQTT_MALFORMED_CREDENTIALS:
|
|
reasonStr = "Malformed credentials";
|
|
break;
|
|
case AsyncMqttClientDisconnectReason::MQTT_NOT_AUTHORIZED:
|
|
reasonStr = "Not authorized";
|
|
break;
|
|
default:
|
|
reasonStr = "Unknown";
|
|
break;
|
|
}
|
|
|
|
LOG_ERROR(TAG, "❌ Disconnected from MQTT broker - Reason: %s (%d)", reasonStr, static_cast<int>(reason));
|
|
|
|
// 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");
|
|
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");
|
|
}
|
|
|
|
}
|
|
|
|
void MQTTDriver::applyCommandTopicSwitch(bool enabled) {
|
|
if (!_mqttClient.connected()) return; // picked up naturally by subscribe() on next connect
|
|
|
|
if (enabled) {
|
|
uint16_t packetId = _mqttClient.subscribe(_commandTopic.c_str(), 1);
|
|
LOG_INFO(TAG, "control/command switch turned on — subscribing live (packetId=%d)", packetId);
|
|
} else {
|
|
uint16_t packetId = _mqttClient.unsubscribe(_commandTopic.c_str());
|
|
LOG_INFO(TAG, "control/command switch turned off — unsubscribing live (packetId=%d)", packetId);
|
|
}
|
|
}
|
|
|
|
void MQTTDriver::onMqttSubscribe(uint16_t packetId, uint8_t qos) {
|
|
LOG_INFO(TAG, "✅ Subscribed to topic (packetId=%d, QoS=%d)", packetId, qos);
|
|
}
|
|
|
|
void MQTTDriver::onMqttUnsubscribe(uint16_t packetId) {
|
|
LOG_DEBUG(TAG, "Unsubscribed from topic (packetId=%d)", packetId);
|
|
}
|
|
|
|
void MQTTDriver::onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
|
|
// Convert to String
|
|
String topicStr = String(topic);
|
|
String payloadStr = String(payload).substring(0, len);
|
|
|
|
LOG_DEBUG(TAG, "MQTT message received - topic: %s, payload: %s", topicStr.c_str(), payloadStr.c_str());
|
|
|
|
// Call user callback
|
|
if (_messageCallback) {
|
|
_messageCallback(topicStr, payloadStr);
|
|
}
|
|
}
|
|
|
|
void MQTTDriver::onMqttPublish(uint16_t packetId) {
|
|
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");
|
|
}
|
|
}
|
|
|
|
void MQTTDriver::mqttReconnectTaskFn(void* param) {
|
|
MQTTDriver* client = static_cast<MQTTDriver*>(param);
|
|
client->attemptReconnection();
|
|
vTaskDelete(NULL);
|
|
}
|
|
|
|
void MQTTDriver::mqttReconnectTimerCallback(TimerHandle_t xTimer) {
|
|
if (MQTTDriver::_instance) {
|
|
xTaskCreate(mqttReconnectTaskFn, "mqttRecon", 4096, MQTTDriver::_instance, 5, NULL);
|
|
}
|
|
}
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════════════
|
|
// 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 (!_configManager.getMqttTopicConfig().heartbeat) return;
|
|
if (!hasHeapForPublish()) return; // skip building the JsonDocument too, not just the publish
|
|
|
|
// Build heartbeat JSON message — flat shape per docs/reference/vesper_mqtt_topic_spec_v2.md.
|
|
// state/ok are independently derived via _stateProvider, never mirrored from
|
|
// status/playback or system/alerts.
|
|
JsonDocument doc;
|
|
|
|
doc["device_id"] = _configManager.getDeviceUID();
|
|
|
|
DeviceState ds = _stateProvider ? _stateProvider() : DeviceState{"booting", true};
|
|
doc["state"] = ds.state;
|
|
doc["ok"] = ds.ok;
|
|
|
|
doc["fw_version"] = _configManager.getFwVersion();
|
|
|
|
unsigned long uptimeMs = millis();
|
|
unsigned long uptimeSec = uptimeMs / 1000;
|
|
unsigned long hours = uptimeSec / 3600;
|
|
unsigned long minutes = (uptimeSec % 3600) / 60;
|
|
unsigned long seconds = uptimeSec % 60;
|
|
doc["uptime_ms"] = uptimeMs;
|
|
|
|
char uptimeHuman[32];
|
|
snprintf(uptimeHuman, sizeof(uptimeHuman), "%luh %lum %lus", hours, minutes, seconds);
|
|
doc["uptime_human"] = uptimeHuman;
|
|
|
|
doc["ip_address"] = _networking.getLocalIP();
|
|
doc["gateway"] = _networking.getGateway();
|
|
doc["rssi"] = WiFi.RSSI();
|
|
doc["free_heap"] = ESP.getFreeHeap();
|
|
|
|
// Serialize to string
|
|
String heartbeatMessage;
|
|
serializeJson(doc, heartbeatMessage);
|
|
|
|
// Publish to heartbeat topic with RETAIN flag
|
|
uint16_t packetId = _mqttClient.publish(_heartbeatTopic.c_str(), 1, true, heartbeatMessage.c_str());
|
|
|
|
if (packetId > 0) {
|
|
LOG_DEBUG(TAG, "💓 Published heartbeat (retained) - state: %s, IP: %s, Uptime: %lums",
|
|
ds.state.c_str(), _networking.getLocalIP().c_str(), uptimeMs);
|
|
} else {
|
|
LOG_ERROR(TAG, "❌ Failed to publish heartbeat");
|
|
}
|
|
}
|
|
|
|
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
|
|
// ═══════════════════════════════════════════════════════════════════════════════════
|
|
|
|
unsigned long MQTTDriver::getReconnectDelay() {
|
|
// First 3 attempts: Quick retries (5 seconds each)
|
|
if (_reconnectAttempts <= MQTT_MAX_QUICK_RETRIES) {
|
|
return MQTT_RECONNECT_BASE_DELAY;
|
|
}
|
|
|
|
// After quick retries: Exponential backoff
|
|
// Formula: base_delay * 2^(attempts - quick_retries)
|
|
// Examples: 10s, 20s, 40s, 80s, 160s, 300s (capped at 5 minutes)
|
|
uint8_t backoffPower = _reconnectAttempts - MQTT_MAX_QUICK_RETRIES;
|
|
unsigned long delay = MQTT_RECONNECT_BASE_DELAY * (1 << backoffPower); // 2^backoffPower
|
|
|
|
// Cap at maximum delay (5 minutes)
|
|
if (delay > MQTT_RECONNECT_MAX_DELAY) {
|
|
delay = MQTT_RECONNECT_MAX_DELAY;
|
|
}
|
|
|
|
return delay;
|
|
} |