Files
project-vesper/src/Communication/Drivers/MQTTDriver/MQTTDriver.cpp
T
bonaminandClaude Sonnet 4.6 d4bd990e53 feat: semver versioning, FastAPI OTA integration, health alerts via MQTT
- Version.hpp: extract FW_VERSION from main.cpp into shared header
- OTAManager: replace uint16_t version with SemVer struct; update API URLs
  to new FastAPI backend (/api/firmware/{hw_type}/{channel}/latest);
  add postDownloadTelemetry() and postFlashTelemetry() for fleet visibility
- ConfigManager: remove fwVersion from DeviceConfig (always read from
  FW_VERSION constant); saveDeviceConfig/loadDeviceConfig are now no-ops;
  fallbackServerUrl replaced with fallbackServerUrls[2] array
- HealthMonitor: add AlertCallback + setAlertCallback() firing on state
  transitions (including CLEARED on recovery)
- CommunicationRouter: wire HealthMonitor alert callback on begin();
  add publishAlert() and publishInfo() for MQTT status topics
- MQTTDriver: add _alertsTopic + _infoTopic; add publishDirect() for
  absolute topic publishing; migrate heartbeat to JsonDocument
- ResponseBuilder, ClientManager, BellEngine: StaticJsonDocument /
  DynamicJsonDocument → JsonDocument; remove dead notifyBellsFired()
- docs: reorganise into architecture/, dev/, features/, reference/

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-14 22:15:27 +02:00

491 lines
18 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)
String deviceUID = _configManager.getDeviceUID();
_controlTopic = "vesper/" + deviceUID + "/control";
_dataTopic = "vesper/" + deviceUID + "/data";
_alertsTopic = "vesper/" + deviceUID + "/status/alerts";
_infoTopic = "vesper/" + deviceUID + "/status/info";
_clientId = "vesper-" + deviceUID;
LOG_INFO(TAG, "MQTT Topics: control=%s, data=%s, alerts=%s, info=%s",
_controlTopic.c_str(), _dataTopic.c_str(),
_alertsTopic.c_str(), _infoTopic.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);
LOG_INFO(TAG, "✅ MQTT Async Client initialized");
}
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() {
_mqttClient.disconnect();
LOG_INFO(TAG, "Disconnected from MQTT broker");
}
uint16_t MQTTDriver::publish(const String& topic, 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;
}
// Build full topic (if relative)
String fullTopic = topic.startsWith("vesper/") ? topic : _dataTopic;
uint16_t packetId = _mqttClient.publish(fullTopic.c_str(), qos, retain, payload.c_str());
if (packetId > 0) {
LOG_DEBUG(TAG, "Published to %s: %s (packetId=%d)", fullTopic.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;
}
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() {
uint16_t packetId = _mqttClient.subscribe(_controlTopic.c_str(), 0);
LOG_INFO(TAG, "📬 Subscribing to control topic: %s (packetId=%d)", _controlTopic.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();
}
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::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", 3072, 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;
}
// Build heartbeat JSON message
JsonDocument doc;
doc["status"] = "INFO";
doc["type"] = "heartbeat";
JsonObject payload = doc["payload"].to<JsonObject>();
// Device ID from NVS
payload["device_id"] = _configManager.getDeviceUID();
// Firmware version
payload["firmware_version"] = _configManager.getFwVersion();
// Current date/time (from TimeKeeper if available, else uptime-based)
// For now, we'll use a simple timestamp format
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;
char timestampStr[64];
snprintf(timestampStr, sizeof(timestampStr), "Uptime: %luh %lum %lus", hours, minutes, seconds);
payload["timestamp"] = timestampStr;
// IP address
payload["ip_address"] = _networking.getLocalIP();
// Gateway address
payload["gateway"] = _networking.getGateway();
// Uptime in milliseconds
payload["uptime_ms"] = uptimeMs;
// Serialize to string
String heartbeatMessage;
serializeJson(doc, heartbeatMessage);
// Publish to heartbeat topic with RETAIN flag
String heartbeatTopic = "vesper/" + _configManager.getDeviceUID() + "/status/heartbeat";
uint16_t packetId = _mqttClient.publish(heartbeatTopic.c_str(), 1, true, heartbeatMessage.c_str());
if (packetId > 0) {
LOG_DEBUG(TAG, "💓 Published heartbeat (retained) - IP: %s, Uptime: %lums",
_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", 3072, 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", 3072, 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;
}