- 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>
619 lines
25 KiB
C++
619 lines
25 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)
|
|
, _supervisorTask(nullptr)
|
|
, _reconnectAttempts(0)
|
|
, _nextConnectAtMs(0)
|
|
, _connectAttemptMs(0)
|
|
, _netUpSinceMs(0)
|
|
, _heartbeatDue(false)
|
|
, _lastHeartbeatMs(0)
|
|
, _pendingMutex(xSemaphoreCreateRecursiveMutex())
|
|
, _resendDue(false) {
|
|
|
|
_instance = this; // Set static instance pointer
|
|
_pending.reserve(MAX_PENDING_ACKS);
|
|
}
|
|
|
|
MQTTDriver::~MQTTDriver() {
|
|
if (_supervisorTask) {
|
|
vTaskDelete(_supervisorTask);
|
|
}
|
|
_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.
|
|
_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");
|
|
}
|
|
|
|
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() {
|
|
_reconnectAttempts = 0;
|
|
_nextConnectAtMs = millis();
|
|
wakeSupervisor();
|
|
}
|
|
|
|
// 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();
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
bool MQTTDriver::isConnected() const {
|
|
return _mqttClient.connected();
|
|
}
|
|
|
|
void MQTTDriver::onNetworkConnected() {
|
|
// 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;
|
|
_nextConnectAtMs = millis();
|
|
wakeSupervisor();
|
|
}
|
|
|
|
void MQTTDriver::onNetworkDisconnected() {
|
|
LOG_DEBUG(TAG, "Network disconnected - MQTT will 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;
|
|
_connectAttemptMs = 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 (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) {
|
|
_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;
|
|
}
|
|
|
|
_diag.disconnects++;
|
|
_diag.lastDisconnectReason = reasonStr;
|
|
_diag.lastDisconnectMs = millis();
|
|
_diag.connectedSinceMs = 0;
|
|
_connectAttemptMs = 0;
|
|
abandonPending();
|
|
|
|
if (!mqttConfig.enabled) {
|
|
LOG_INFO(TAG, "❌ Disconnected from MQTT broker - Reason: %s (%d) - MQTT disabled, not reconnecting",
|
|
reasonStr, static_cast<int>(reason));
|
|
return;
|
|
}
|
|
|
|
_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) {
|
|
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) {
|
|
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);
|
|
}
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════════════
|
|
// 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::wakeSupervisor() {
|
|
if (_supervisorTask) xTaskNotifyGive(_supervisorTask);
|
|
}
|
|
|
|
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 (_resendDue) {
|
|
_resendDue = false;
|
|
flushResendQueue();
|
|
}
|
|
if (const char* expired = expiredPendingLabel(now)) {
|
|
forceReset(expired);
|
|
}
|
|
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);
|
|
|
|
abandonPending();
|
|
_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["resent_messages"] = _diag.resentMessages;
|
|
out["wifi_connected"] = WiFi.status() == WL_CONNECTED;
|
|
out["free_heap"] = ESP.getFreeHeap();
|
|
}
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════════════
|
|
// HEARTBEAT FUNCTIONALITY
|
|
// ═══════════════════════════════════════════════════════════════════════════════════
|
|
|
|
void MQTTDriver::publishHeartbeat() {
|
|
if (!_mqttClient.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
|
|
// QoS 1 on purpose — its PUBACK is the liveness probe (HEARTBEAT_ACK_TIMEOUT).
|
|
uint16_t packetId = publishTracked(_heartbeatTopic, heartbeatMessage, true,
|
|
HEARTBEAT_ACK_TIMEOUT, "heartbeat PUBACK timeout", false);
|
|
|
|
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");
|
|
}
|
|
}
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════════════
|
|
// 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, 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 (1 minute)
|
|
if (delay > MQTT_RECONNECT_MAX_DELAY) {
|
|
delay = MQTT_RECONNECT_MAX_DELAY;
|
|
}
|
|
|
|
return delay;
|
|
} |