refactor(comms): clean up Communication folder structure

- Delete dead code: CommandHandler (700-line God Class) and
  HTTPRequestHandler — both replaced by new architecture in Stage 4
- Create Drivers/ group for the three low-level protocol drivers,
  mirroring the Transport/ pattern:
    MQTTAsyncClient    → Drivers/MQTTDriver    (class: MQTTDriver)
    WebSocketServer    → Drivers/WebSocketDriver (class: WebSocketDriver)
    UARTCommandHandler → Drivers/UARTDriver    (class: UARTDriver)
- Update all includes and type references across CommunicationRouter,
  all three Transport wrappers, and MQTTHandler
- Add -std=gnu++14 + build_unflags to platformio.ini so std::make_unique
  compiles on ESP32 (required by CommunicationRouter::registerHandlers)

Build: passing

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-28 23:22:50 +02:00
co-authored by Claude Sonnet 4.6
parent 682c604abe
commit c3dc0a79bc
20 changed files with 149 additions and 1928 deletions
@@ -0,0 +1,476 @@
/*
* 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";
_clientId = "vesper-" + deviceUID;
LOG_INFO(TAG, "MQTT Topics: control=%s, data=%s", _controlTopic.c_str(), _dataTopic.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;
}
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
StaticJsonDocument<512> doc;
doc["status"] = "INFO";
doc["type"] = "heartbeat";
JsonObject payload = doc.createNestedObject("payload");
// 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;
}
@@ -0,0 +1,134 @@
/*
* ═══════════════════════════════════════════════════════════════════════════════════
* MQTTDRIVER.HPP - MQTT Protocol Driver
* ═══════════════════════════════════════════════════════════════════════════════════
*
* Low-level MQTT protocol driver using AsyncMqttClient.
* Handles broker connection, auth, publish/subscribe, reconnect with exponential
* backoff, and heartbeat. Wrapped by MQTTTransport for CommandBus integration.
*
* 📋 VERSION: 3.0 (AsyncMqttClient-based)
* 📅 DATE: 2025-01-04
* 👨‍💻 AUTHOR: Advanced Bell Systems
* ═══════════════════════════════════════════════════════════════════════════════════
*/
#pragma once
#include <Arduino.h>
#include <AsyncMqttClient.h>
class ConfigManager;
class Networking;
class MQTTDriver {
public:
static MQTTDriver* _instance;
// Message callback type
using MessageCallback = std::function<void(const String& topic, const String& payload)>;
explicit MQTTDriver(ConfigManager& configManager, Networking& networking);
~MQTTDriver();
/**
* @brief Initialize MQTT client
*/
void begin();
/**
* @brief Connect to MQTT broker
*/
void connect();
/**
* @brief Disconnect from MQTT broker
*/
void disconnect();
/**
* @brief Publish message to MQTT
* @param topic Topic to publish to (relative, will prepend "vesper/{deviceID}/")
* @param payload Message payload
* @param qos QoS level (0, 1, or 2)
* @param retain Retain flag
* @return Packet ID (0 if failed)
*/
uint16_t publish(const String& topic, const String& payload, int qos = 0, bool retain = false);
/**
* @brief Set message received callback
*/
void setCallback(MessageCallback callback);
/**
* @brief Check if connected to MQTT broker
*/
bool isConnected() const;
/**
* @brief Handle network connection callback
*/
void onNetworkConnected();
/**
* @brief Handle network disconnection callback
*/
void onNetworkDisconnected();
private:
ConfigManager& _configManager;
Networking& _networking;
AsyncMqttClient _mqttClient;
MessageCallback _messageCallback;
// Device topic strings (cached for performance)
String _controlTopic;
String _dataTopic;
String _clientId; // Store client ID to keep it alive
/**
* @brief Subscribe to control topic
*/
void subscribe();
/**
* @brief MQTT event handlers
*/
void onMqttConnect(bool sessionPresent);
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason);
void onMqttSubscribe(uint16_t packetId, uint8_t qos);
void onMqttUnsubscribe(uint16_t packetId);
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total);
void onMqttPublish(uint16_t packetId);
// Reconnection Timer with Exponential Backoff
TimerHandle_t _mqttReconnectTimer;
static const unsigned long MQTT_RECONNECT_BASE_DELAY = 5000; // 5 seconds base
static const unsigned long MQTT_RECONNECT_MAX_DELAY = 300000; // 5 minutes max
static const uint8_t MQTT_MAX_QUICK_RETRIES = 3; // Try 3 times quickly
uint8_t _reconnectAttempts; // Track failed attempts
unsigned long _lastConnectionAttempt; // Track last attempt time
void attemptReconnection();
static void mqttReconnectTimerCallback(TimerHandle_t xTimer);
static void mqttReconnectTaskFn(void* param);
unsigned long getReconnectDelay(); // Calculate backoff delay
// Network Stabilization Timer (non-blocking replacement for delay)
TimerHandle_t _networkStabilizationTimer;
static const unsigned long NETWORK_STABILIZATION_DELAY = 2000; // 2 seconds
void connectAfterStabilization();
static void networkStabilizationTimerCallback(TimerHandle_t xTimer);
static void mqttConnectTaskFn(void* param);
// Heartbeat Timer (30 seconds)
TimerHandle_t _heartbeatTimer;
static const unsigned long HEARTBEAT_INTERVAL = 30000; // 30 seconds
TaskHandle_t _heartbeatTaskHandle; // Guard: only one heartbeat task at a time
void publishHeartbeat();
static void heartbeatTimerCallback(TimerHandle_t xTimer);
static void mqttHeartbeatTaskFn(void* param);
void startHeartbeat();
void stopHeartbeat();
};
@@ -0,0 +1,133 @@
/*
* UARTDRIVER.CPP - UART Protocol Driver Implementation
*/
#include "UARTDriver.hpp"
#define TAG "UARTHandler"
#include "../../../Logging/Logging.hpp"
UARTDriver::UARTDriver(uint8_t txPin, uint8_t rxPin, uint32_t baudRate)
: _serial(Serial2)
, _txPin(txPin)
, _rxPin(rxPin)
, _baudRate(baudRate)
, _ready(false)
, _bufferIndex(0)
, _messageCount(0)
, _errorCount(0)
, _callback(nullptr)
{
resetBuffer();
}
UARTDriver::~UARTDriver() {
_serial.end();
}
void UARTDriver::begin() {
LOG_INFO(TAG, "Initializing UART Command Handler");
LOG_INFO(TAG, " TX Pin: GPIO%d", _txPin);
LOG_INFO(TAG, " RX Pin: GPIO%d", _rxPin);
LOG_INFO(TAG, " Baud Rate: %u", _baudRate);
// Initialize Serial2 with custom pins
_serial.begin(_baudRate, SERIAL_8N1, _rxPin, _txPin);
// Clear any garbage in the buffer
while (_serial.available()) {
_serial.read();
}
_ready = true;
LOG_INFO(TAG, "UART Command Handler ready");
}
void UARTDriver::loop() {
if (!_ready) return;
// Process all available bytes
while (_serial.available()) {
char c = _serial.read();
// Check for message delimiter (newline)
if (c == '\n' || c == '\r') {
if (_bufferIndex > 0) {
// Null-terminate and process
_buffer[_bufferIndex] = '\0';
processLine(_buffer);
resetBuffer();
}
// Skip empty lines
continue;
}
// Add character to buffer
if (_bufferIndex < BUFFER_SIZE - 1) {
_buffer[_bufferIndex++] = c;
} else {
// Buffer overflow - discard and reset
LOG_ERROR(TAG, "UART buffer overflow, discarding message");
_errorCount++;
resetBuffer();
}
}
}
void UARTDriver::setCallback(MessageCallback callback) {
_callback = callback;
}
void UARTDriver::send(const String& response) {
if (!_ready) {
LOG_ERROR(TAG, "UART not ready, cannot send response");
return;
}
_serial.print(response);
_serial.print('\n'); // Newline delimiter
_serial.flush(); // Ensure data is sent
LOG_DEBUG(TAG, "UART TX: %s", response.c_str());
}
void UARTDriver::processLine(const char* line) {
LOG_DEBUG(TAG, "UART RX: %s", line);
// Skip empty lines or whitespace-only
if (strlen(line) == 0) return;
// Parse JSON
StaticJsonDocument<1024> doc;
DeserializationError error = deserializeJson(doc, line);
if (error) {
LOG_ERROR(TAG, "UART JSON parse error: %s", error.c_str());
_errorCount++;
// Send error response back
StaticJsonDocument<256> errorDoc;
errorDoc["status"] = "ERROR";
errorDoc["type"] = "parse_error";
errorDoc["payload"] = error.c_str();
String errorResponse;
serializeJson(errorDoc, errorResponse);
send(errorResponse);
return;
}
_messageCount++;
// Invoke callback if set
if (_callback) {
_callback(doc);
} else {
LOG_WARNING(TAG, "UART message received but no callback set");
}
}
void UARTDriver::resetBuffer() {
_bufferIndex = 0;
memset(_buffer, 0, BUFFER_SIZE);
}
@@ -0,0 +1,111 @@
/*
* ═══════════════════════════════════════════════════════════════════════════════════
* UARTDRIVER.HPP - UART Protocol Driver
* ═══════════════════════════════════════════════════════════════════════════════════
*
* Low-level UART protocol driver for external devices (LCD panels, button boards).
* Reads newline-delimited JSON on Serial2 (TX: GPIO12, RX: GPIO13 @ 115200 baud).
* Wrapped by UARTTransport for CommandBus integration.
*
* 📋 VERSION: 1.0
* 📅 DATE: 2025-01-19
* 👨‍💻 AUTHOR: Advanced Bell Systems
* ═══════════════════════════════════════════════════════════════════════════════════
*/
#pragma once
#include <Arduino.h>
#include <ArduinoJson.h>
#include <functional>
class UARTDriver {
public:
// Default pin configuration
static constexpr uint8_t DEFAULT_TX_PIN = 12;
static constexpr uint8_t DEFAULT_RX_PIN = 13;
static constexpr uint32_t DEFAULT_BAUD_RATE = 115200;
static constexpr size_t BUFFER_SIZE = 1024;
// Message callback type - called when a complete JSON message is received
using MessageCallback = std::function<void(JsonDocument& message)>;
/**
* @brief Construct UART handler with custom pins
* @param txPin GPIO pin for TX (default: 12)
* @param rxPin GPIO pin for RX (default: 13)
* @param baudRate Baud rate (default: 115200)
*/
explicit UARTDriver(uint8_t txPin = DEFAULT_TX_PIN,
uint8_t rxPin = DEFAULT_RX_PIN,
uint32_t baudRate = DEFAULT_BAUD_RATE);
~UARTDriver();
/**
* @brief Initialize the UART interface
*/
void begin();
/**
* @brief Process incoming UART data (call from loop or task)
* Non-blocking - processes available bytes and returns
*/
void loop();
/**
* @brief Set callback for received messages
* @param callback Function to call with parsed JSON
*/
void setCallback(MessageCallback callback);
/**
* @brief Send a response back over UART
* @param response JSON string to send (newline appended automatically)
*/
void send(const String& response);
/**
* @brief Check if UART is initialized and ready
*/
bool isReady() const { return _ready; }
/**
* @brief Get number of messages received since boot
*/
uint32_t getMessageCount() const { return _messageCount; }
/**
* @brief Get number of parse errors since boot
*/
uint32_t getErrorCount() const { return _errorCount; }
private:
HardwareSerial& _serial;
uint8_t _txPin;
uint8_t _rxPin;
uint32_t _baudRate;
bool _ready;
// Receive buffer
char _buffer[BUFFER_SIZE];
size_t _bufferIndex;
// Statistics
uint32_t _messageCount;
uint32_t _errorCount;
// Callback
MessageCallback _callback;
/**
* @brief Process a complete line from the buffer
* @param line Null-terminated string containing the message
*/
void processLine(const char* line);
/**
* @brief Reset the receive buffer
*/
void resetBuffer();
};
@@ -0,0 +1,159 @@
/*
* WEBSOCKETDRIVER.CPP - WebSocket Protocol Driver Implementation
*/
#include "WebSocketDriver.hpp"
#define TAG "WebSocket"
#include "../../../Logging/Logging.hpp"
#include "../../ResponseBuilder/ResponseBuilder.hpp"
// Static instance for callback
WebSocketDriver* WebSocketDriver::_instance = nullptr;
WebSocketDriver::WebSocketDriver(AsyncWebSocket& webSocket, ClientManager& clientManager)
: _webSocket(webSocket)
, _clientManager(clientManager)
, _messageCallback(nullptr) {
_instance = this;
}
WebSocketDriver::~WebSocketDriver() {
_instance = nullptr;
}
void WebSocketDriver::begin() {
_webSocket.onEvent(onEvent);
LOG_INFO(TAG, "WebSocket server initialized on /ws");
// 🔥 CRITICAL: This line was missing - attach WebSocket to the AsyncWebServer
// Without this, the server doesn't know about the WebSocket handler!
// Note: We can't access _server here directly, so this must be done in CommunicationRouter
}
void WebSocketDriver::setCallback(MessageCallback callback) {
_messageCallback = callback;
}
void WebSocketDriver::sendToClient(uint32_t clientId, const String& message) {
_clientManager.sendToClient(clientId, message);
}
void WebSocketDriver::broadcastToAll(const String& message) {
_clientManager.broadcastToAll(message);
LOG_DEBUG(TAG, "Broadcast to all WebSocket clients: %s", message.c_str());
}
void WebSocketDriver::broadcastToMaster(const String& message) {
_clientManager.sendToMasterClients(message);
LOG_DEBUG(TAG, "Broadcast to master clients: %s", message.c_str());
}
void WebSocketDriver::broadcastToSecondary(const String& message) {
_clientManager.sendToSecondaryClients(message);
LOG_DEBUG(TAG, "Broadcast to secondary clients: %s", message.c_str());
}
bool WebSocketDriver::hasClients() const {
return _clientManager.hasClients();
}
size_t WebSocketDriver::getClientCount() const {
return _clientManager.getClientCount();
}
void WebSocketDriver::onEvent(AsyncWebSocket* server, AsyncWebSocketClient* client,
AwsEventType type, void* arg, uint8_t* data, size_t len) {
if (!_instance) {
LOG_ERROR(TAG, "WebSocketDriver static instance is NULL - callback ignored!");
return;
}
switch (type) {
case WS_EVT_CONNECT:
_instance->onConnect(client);
break;
case WS_EVT_DISCONNECT:
_instance->onDisconnect(client);
break;
case WS_EVT_DATA:
_instance->onData(client, arg, data, len);
break;
case WS_EVT_ERROR:
LOG_ERROR(TAG, "WebSocket client #%u error(%u): %s",
client->id(), *((uint16_t*)arg), (char*)data);
break;
default:
break;
}
}
void WebSocketDriver::onConnect(AsyncWebSocketClient* client) {
LOG_INFO(TAG, "WebSocket client #%u connected from %s",
client->id(), client->remoteIP().toString().c_str());
// Add client to manager (type UNKNOWN until they identify)
_clientManager.addClient(client, ClientManager::DeviceType::UNKNOWN);
// Send welcome message
String welcomeMsg = ResponseBuilder::success("connection", "Connected to Vesper");
_clientManager.sendToClient(client->id(), welcomeMsg);
}
void WebSocketDriver::onDisconnect(AsyncWebSocketClient* client) {
LOG_INFO(TAG, "WebSocket client #%u disconnected", client->id());
_clientManager.removeClient(client->id());
_clientManager.cleanupDisconnectedClients();
}
void WebSocketDriver::onData(AsyncWebSocketClient* client, void* arg, uint8_t* data, size_t len) {
AwsFrameInfo* info = (AwsFrameInfo*)arg;
// Only handle complete, single-frame text messages
if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
// Allocate buffer for payload
char* payload = (char*)malloc(len + 1);
if (!payload) {
LOG_ERROR(TAG, "Failed to allocate memory for WebSocket payload");
String errorResponse = ResponseBuilder::error("memory_error", "Out of memory");
_clientManager.sendToClient(client->id(), errorResponse);
return;
}
memcpy(payload, data, len);
payload[len] = '\0';
LOG_DEBUG(TAG, "WebSocket client #%u sent: %s", client->id(), payload);
// Parse JSON
StaticJsonDocument<2048> doc;
DeserializationError error = deserializeJson(doc, payload);
if (error) {
LOG_ERROR(TAG, "Failed to parse WebSocket JSON from client #%u: %s", client->id(), error.c_str());
String errorResponse = ResponseBuilder::error("parse_error", "Invalid JSON");
_clientManager.sendToClient(client->id(), errorResponse);
} else {
// Update client last seen time
_clientManager.updateClientLastSeen(client->id());
// Call user callback if set
if (_messageCallback) {
LOG_DEBUG(TAG, "Routing message from client #%u to callback handler", client->id());
_messageCallback(client->id(), doc);
} else {
LOG_WARNING(TAG, "WebSocket message received but no callback handler is set!");
}
}
free(payload);
} else {
LOG_WARNING(TAG, "Received fragmented or non-text WebSocket message from client #%u - ignoring", client->id());
}
}
@@ -0,0 +1,99 @@
/*
* ═══════════════════════════════════════════════════════════════════════════════════
* WEBSOCKETDRIVER.HPP - WebSocket Protocol Driver
* ═══════════════════════════════════════════════════════════════════════════════════
*
* Low-level WebSocket protocol driver. Manages client lifecycle, broadcasts,
* and targeted messaging. Wraps AsyncWebSocket + ClientManager.
* Wrapped by WebSocketTransport for CommandBus integration.
*
* 📋 VERSION: 1.0
* 📅 DATE: 2025-10-01
* 👨‍💻 AUTHOR: Advanced Bell Systems
* ═══════════════════════════════════════════════════════════════════════════════════
*/
#pragma once
#include <Arduino.h>
#include <ESPAsyncWebServer.h>
#include <ArduinoJson.h>
#include "../../../ClientManager/ClientManager.hpp"
class WebSocketDriver {
public:
// Message callback type
using MessageCallback = std::function<void(uint32_t clientId, const JsonDocument& message)>;
explicit WebSocketDriver(AsyncWebSocket& webSocket, ClientManager& clientManager);
~WebSocketDriver();
/**
* @brief Initialize WebSocket server
*/
void begin();
/**
* @brief Set message received callback
*/
void setCallback(MessageCallback callback);
/**
* @brief Send message to specific client
*/
void sendToClient(uint32_t clientId, const String& message);
/**
* @brief Broadcast to all connected clients
*/
void broadcastToAll(const String& message);
/**
* @brief Broadcast to master devices only
*/
void broadcastToMaster(const String& message);
/**
* @brief Broadcast to secondary devices only
*/
void broadcastToSecondary(const String& message);
/**
* @brief Check if any clients are connected
*/
bool hasClients() const;
/**
* @brief Get number of connected clients
*/
size_t getClientCount() const;
private:
AsyncWebSocket& _webSocket;
ClientManager& _clientManager;
MessageCallback _messageCallback;
/**
* @brief Static WebSocket event handler
*/
static void onEvent(AsyncWebSocket* server, AsyncWebSocketClient* client,
AwsEventType type, void* arg, uint8_t* data, size_t len);
/**
* @brief Handle client connection
*/
void onConnect(AsyncWebSocketClient* client);
/**
* @brief Handle client disconnection
*/
void onDisconnect(AsyncWebSocketClient* client);
/**
* @brief Handle received data
*/
void onData(AsyncWebSocketClient* client, void* arg, uint8_t* data, size_t len);
// Static instance for callback routing
static WebSocketDriver* _instance;
};