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
+4
View File
@@ -47,6 +47,7 @@ lib_deps =
https://github.com/marvinroger/async-mqtt-client.git https://github.com/marvinroger/async-mqtt-client.git
build_flags_common = build_flags_common =
-std=gnu++14
-DCORE_DEBUG_LEVEL=0 -DCORE_DEBUG_LEVEL=0
-DCONFIG_ASYNC_TCP_RUNNING_CORE=0 -DCONFIG_ASYNC_TCP_RUNNING_CORE=0
@@ -70,6 +71,9 @@ upload_protocol = esptool
; min_spiffs.csv: ~1.8MB app + ~1.8MB OTA + 64KB NVS + 128KB SPIFFS ; min_spiffs.csv: ~1.8MB app + ~1.8MB OTA + 64KB NVS + 128KB SPIFFS
board_build.partitions = min_spiffs.csv board_build.partitions = min_spiffs.csv
; Upgrade to C++14 so std::make_unique is available
build_unflags = -std=gnu++11
; FreeRTOS timer service task stack — default 2048 is too small when timer callbacks ; FreeRTOS timer service task stack — default 2048 is too small when timer callbacks
; do LOG formatting, MQTT connect(), NTP sync, etc. Increase to 4096. ; do LOG formatting, MQTT connect(), NTP sync, etc. Increase to 4096.
board_build.cmake_extra_args = -DCONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=4096 board_build.cmake_extra_args = -DCONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=4096
File diff suppressed because it is too large Load Diff
@@ -1,168 +0,0 @@
/*
* ⚠️ DEPRECATED — Stage 4 complete.
* This class is no longer used by CommunicationRouter.
* It will be deleted once Stage 4 is confirmed stable in production.
* New path: CommandBus + domain handlers under Communication/Handlers/
*
* ═══════════════════════════════════════════════════════════════════════════════════
* COMMANDHANDLER.HPP - Unified Command Processing (DEPRECATED)
* ═══════════════════════════════════════════════════════════════════════════════════
*
* ⚙️ COMMAND ROUTER AND PROCESSOR ⚙️
*
* Processes all incoming commands from both MQTT and WebSocket:
* • System commands (ping, status, identify)
* • Playback commands
* • File manager commands
* • Relay setup commands
* • Clock setup commands
* • Firmware management
* • Network configuration
*
* 📋 VERSION: 1.0
* 📅 DATE: 2025-10-01
* 👨‍💻 AUTHOR: Advanced Bell Systems
* ═══════════════════════════════════════════════════════════════════════════════════
*/
#pragma once
#include <Arduino.h>
#include <ArduinoJson.h>
// Forward declarations
class ConfigManager;
class OTAManager;
class Player;
class FileManager;
class Timekeeper;
class FirmwareValidator;
class ClientManager;
class Telemetry;
class CommunicationRouter;
class CommandHandler {
public:
// Message source identification
enum class MessageSource {
MQTT,
WEBSOCKET,
UART
};
struct MessageContext {
MessageSource source;
uint32_t clientId; // Only for WebSocket
MessageContext(MessageSource src, uint32_t id = 0)
: source(src), clientId(id) {}
};
// Response callback type
using ResponseCallback = std::function<void(const String& response, const MessageContext& context)>;
explicit CommandHandler(ConfigManager& configManager,
OTAManager& otaManager);
~CommandHandler();
/**
* @brief Set component references
*/
void setPlayerReference(Player* player);
void setFileManagerReference(FileManager* fm);
void setTimeKeeperReference(Timekeeper* tk);
void setFirmwareValidatorReference(FirmwareValidator* fv);
void setClientManagerReference(ClientManager* cm);
void setTelemetryReference(Telemetry* telemetry);
void setCommunicationRouterReference(CommunicationRouter* comm);
/**
* @brief Set response callback for sending responses back
*/
void setResponseCallback(ResponseCallback callback);
/**
* @brief Process incoming command
* @param command JSON command document
* @param context Message context (source and client ID)
*/
void processCommand(JsonDocument& command, const MessageContext& context);
private:
// Dependencies
ConfigManager& _configManager;
OTAManager& _otaManager;
Player* _player;
FileManager* _fileManager;
Timekeeper* _timeKeeper;
FirmwareValidator* _firmwareValidator;
ClientManager* _clientManager;
Telemetry* _telemetry;
CommunicationRouter* _communicationRouter;
ResponseCallback _responseCallback;
// Response helpers
void sendResponse(const String& response, const MessageContext& context);
void sendSuccessResponse(const String& type, const String& payload, const MessageContext& context);
void sendErrorResponse(const String& type, const String& message, const MessageContext& context);
// Command handlers
void handlePingCommand(const MessageContext& context);
void handleStatusCommand(const MessageContext& context);
void handleIdentifyCommand(JsonVariant contents, const MessageContext& context);
void handlePlaybackCommand(JsonVariant contents, const MessageContext& context);
void handleFileManagerCommand(JsonVariant contents, const MessageContext& context);
void handleRelaySetupCommand(JsonVariant contents, const MessageContext& context);
void handleClockSetupCommand(JsonVariant contents, const MessageContext& context);
void handleSystemInfoCommand(JsonVariant contents, const MessageContext& context);
void handleSystemCommand(JsonVariant contents, const MessageContext& context);
// File Manager sub-commands
void handleListMelodiesCommand(const MessageContext& context);
void handleDownloadMelodyCommand(JsonVariant contents, const MessageContext& context);
void handleDeleteMelodyCommand(JsonVariant contents, const MessageContext& context);
// Relay Setup sub-commands
void handleSetRelayTimersCommand(JsonVariant contents, const MessageContext& context);
void handleSetRelayOutputsCommand(JsonVariant contents, const MessageContext& context);
// Clock Setup sub-commands
void handleSetClockOutputsCommand(JsonVariant contents, const MessageContext& context);
void handleSetClockTimingsCommand(JsonVariant contents, const MessageContext& context);
void handleSetClockAlertsCommand(JsonVariant contents, const MessageContext& context);
void handleSetClockBacklightCommand(JsonVariant contents, const MessageContext& context);
void handleSetClockSilenceCommand(JsonVariant contents, const MessageContext& context);
void handleSetRtcTimeCommand(JsonVariant contents, const MessageContext& context);
void handleSetPhysicalClockTimeCommand(JsonVariant contents, const MessageContext& context);
void handlePauseClockUpdatesCommand(JsonVariant contents, const MessageContext& context);
void handleSetClockEnabledCommand(JsonVariant contents, const MessageContext& context);
// System Info sub-commands
void handleGetDeviceTimeCommand(const MessageContext& context);
void handleGetClockTimeCommand(const MessageContext& context);
void handleCommitFirmwareCommand(const MessageContext& context);
void handleRollbackFirmwareCommand(const MessageContext& context);
void handleGetFirmwareStatusCommand(const MessageContext& context);
void handleNetworkInfoCommand(const MessageContext& context);
void handleGetFullSettingsCommand(const MessageContext& context);
void handleSyncTimeToLcdCommand(const MessageContext& context);
// Network configuration
void handleSetNetworkConfigCommand(JsonVariant contents, const MessageContext& context);
// System Config
void handleResetDefaultsCommand(const MessageContext& context);
// Log Level Commands
void handleSetSerialLogLevelCommand(JsonVariant contents, const MessageContext& context);
void handleSetSdLogLevelCommand(JsonVariant contents, const MessageContext& context);
void handleSetMqttLogLevelCommand(JsonVariant contents, const MessageContext& context);
// MQTT Control Commands
void handleSetMqttEnabledCommand(JsonVariant contents, const MessageContext& context);
// Device Control Commands
void handleRestartCommand(const MessageContext& context);
void handleForceUpdateCommand(JsonVariant contents, const MessageContext& context);
void handleCustomUpdateCommand(JsonVariant contents, const MessageContext& context);
};
@@ -3,13 +3,12 @@
* *
* The router is now a thin coordinator: * The router is now a thin coordinator:
* • Owns the CommandBus and four transports (MQTT, WS, HTTP, UART) * • Owns the CommandBus and four transports (MQTT, WS, HTTP, UART)
* • Owns the underlying legacy protocol objects (MQTTAsyncClient, etc.) * • Owns the underlying legacy protocol objects (MQTTDriver, etc.)
* so the rest of the codebase doesn't need to change * so the rest of the codebase doesn't need to change
* • Registers all domain handlers in registerHandlers() * • Registers all domain handlers in registerHandlers()
* • Exposes the same public API as before so main.cpp is unchanged * • Exposes the same public API as before so main.cpp is unchanged
* *
* The 700-line if/else CommandHandler is no longer used — it stays on disk * The old CommandHandler and HTTPRequestHandler have been deleted.
* until Stage 4 is proven stable, then gets deleted.
*/ */
#pragma once #pragma once
@@ -19,10 +18,10 @@
#include <AsyncUDP.h> #include <AsyncUDP.h>
#include <ArduinoJson.h> #include <ArduinoJson.h>
// Underlying protocol objects (still owned here) // Underlying protocol drivers (still owned here)
#include "../MQTTAsyncClient/MQTTAsyncClient.hpp" #include "../Drivers/MQTTDriver/MQTTDriver.hpp"
#include "../WebSocketServer/WebSocketServer.hpp" #include "../Drivers/WebSocketDriver/WebSocketDriver.hpp"
#include "../UARTCommandHandler/UARTCommandHandler.hpp" #include "../Drivers/UARTDriver/UARTDriver.hpp"
#include "../../ClientManager/ClientManager.hpp" #include "../../ClientManager/ClientManager.hpp"
// New architecture // New architecture
@@ -81,8 +80,8 @@ public:
bool isHealthy() const; bool isHealthy() const;
// Legacy accessors used by other subsystems // Legacy accessors used by other subsystems
MQTTAsyncClient& getMQTTClient() { return _mqttClient; } MQTTDriver& getMQTTClient() { return _mqttClient; }
UARTCommandHandler& getUARTHandler() { return _uartHandler; } UARTDriver& getUARTHandler() { return _uartHandler; }
// Broadcast helpers — called by BellEngine, Player, Telemetry, etc. // Broadcast helpers — called by BellEngine, Player, Telemetry, etc.
void broadcastStatus(const String& statusMessage); void broadcastStatus(const String& statusMessage);
@@ -121,10 +120,10 @@ private:
OutputManager* _outputManager = nullptr; OutputManager* _outputManager = nullptr;
// ── Underlying protocol objects (owned) ───────────────────────────────── // ── Underlying protocol objects (owned) ─────────────────────────────────
MQTTAsyncClient _mqttClient; MQTTDriver _mqttClient;
ClientManager _clientManager; ClientManager _clientManager;
WebSocketServer _wsServer; WebSocketDriver _wsServer;
UARTCommandHandler _uartHandler; UARTDriver _uartHandler;
// ── New architecture (owned) ──────────────────────────────────────────── // ── New architecture (owned) ────────────────────────────────────────────
CommandBus _bus; CommandBus _bus;
@@ -1,17 +1,17 @@
/* /*
* MQTTASYNCCLIENT.CPP - MQTT Client Implementation with AsyncMqttClient * MQTTDRIVER.CPP - MQTT Protocol Driver Implementation
*/ */
#include "MQTTAsyncClient.hpp" #include "MQTTDriver.hpp"
#define TAG "MQTTClient" #define TAG "MQTTClient"
#include "../../ConfigManager/ConfigManager.hpp" #include "../../../ConfigManager/ConfigManager.hpp"
#include "../../Networking/Networking.hpp" #include "../../../Networking/Networking.hpp"
#include "../../Logging/Logging.hpp" #include "../../../Logging/Logging.hpp"
MQTTAsyncClient* MQTTAsyncClient::_instance = nullptr; MQTTDriver* MQTTDriver::_instance = nullptr;
MQTTAsyncClient::MQTTAsyncClient(ConfigManager& configManager, Networking& networking) MQTTDriver::MQTTDriver(ConfigManager& configManager, Networking& networking)
: _configManager(configManager) : _configManager(configManager)
, _networking(networking) , _networking(networking)
, _messageCallback(nullptr) , _messageCallback(nullptr)
@@ -53,7 +53,7 @@ MQTTAsyncClient::MQTTAsyncClient(ConfigManager& configManager, Networking& netwo
} }
MQTTAsyncClient::~MQTTAsyncClient() { MQTTDriver::~MQTTDriver() {
if (_mqttReconnectTimer) { if (_mqttReconnectTimer) {
xTimerDelete(_mqttReconnectTimer, portMAX_DELAY); xTimerDelete(_mqttReconnectTimer, portMAX_DELAY);
} }
@@ -68,7 +68,7 @@ MQTTAsyncClient::~MQTTAsyncClient() {
_mqttClient.disconnect(); _mqttClient.disconnect();
} }
void MQTTAsyncClient::begin() { void MQTTDriver::begin() {
LOG_INFO(TAG, "Initializing MQTT Async Client"); LOG_INFO(TAG, "Initializing MQTT Async Client");
auto& mqttConfig = _configManager.getMqttConfig(); auto& mqttConfig = _configManager.getMqttConfig();
@@ -116,7 +116,7 @@ void MQTTAsyncClient::begin() {
LOG_INFO(TAG, "✅ MQTT Async Client initialized"); LOG_INFO(TAG, "✅ MQTT Async Client initialized");
} }
void MQTTAsyncClient::connect() { void MQTTDriver::connect() {
auto& mqttConfig = _configManager.getMqttConfig(); auto& mqttConfig = _configManager.getMqttConfig();
// 🔥 Check if MQTT is enabled // 🔥 Check if MQTT is enabled
@@ -140,12 +140,12 @@ void MQTTAsyncClient::connect() {
LOG_INFO(TAG, "MQTT connect() called - waiting for async connection..."); LOG_INFO(TAG, "MQTT connect() called - waiting for async connection...");
} }
void MQTTAsyncClient::disconnect() { void MQTTDriver::disconnect() {
_mqttClient.disconnect(); _mqttClient.disconnect();
LOG_INFO(TAG, "Disconnected from MQTT broker"); LOG_INFO(TAG, "Disconnected from MQTT broker");
} }
uint16_t MQTTAsyncClient::publish(const String& topic, const String& payload, int qos, bool retain) { uint16_t MQTTDriver::publish(const String& topic, const String& payload, int qos, bool retain) {
// Check if connected before attempting to publish // Check if connected before attempting to publish
if (!_mqttClient.connected()) { if (!_mqttClient.connected()) {
// Don't log error here - would cause infinite loop with MQTT logging // Don't log error here - would cause infinite loop with MQTT logging
@@ -165,15 +165,15 @@ uint16_t MQTTAsyncClient::publish(const String& topic, const String& payload, in
return packetId; return packetId;
} }
void MQTTAsyncClient::setCallback(MessageCallback callback) { void MQTTDriver::setCallback(MessageCallback callback) {
_messageCallback = callback; _messageCallback = callback;
} }
bool MQTTAsyncClient::isConnected() const { bool MQTTDriver::isConnected() const {
return _mqttClient.connected(); return _mqttClient.connected();
} }
void MQTTAsyncClient::onNetworkConnected() { void MQTTDriver::onNetworkConnected() {
auto& mqttConfig = _configManager.getMqttConfig(); auto& mqttConfig = _configManager.getMqttConfig();
// 🔥 Only attempt connection if MQTT is enabled // 🔥 Only attempt connection if MQTT is enabled
@@ -198,7 +198,7 @@ void MQTTAsyncClient::onNetworkConnected() {
} }
} }
void MQTTAsyncClient::onNetworkDisconnected() { void MQTTDriver::onNetworkDisconnected() {
LOG_DEBUG(TAG, "Network disconnected - MQTT will auto-reconnect when network returns"); LOG_DEBUG(TAG, "Network disconnected - MQTT will auto-reconnect when network returns");
if (_mqttClient.connected()) { if (_mqttClient.connected()) {
@@ -206,12 +206,12 @@ void MQTTAsyncClient::onNetworkDisconnected() {
} }
} }
void MQTTAsyncClient::subscribe() { void MQTTDriver::subscribe() {
uint16_t packetId = _mqttClient.subscribe(_controlTopic.c_str(), 0); uint16_t packetId = _mqttClient.subscribe(_controlTopic.c_str(), 0);
LOG_INFO(TAG, "📬 Subscribing to control topic: %s (packetId=%d)", _controlTopic.c_str(), packetId); LOG_INFO(TAG, "📬 Subscribing to control topic: %s (packetId=%d)", _controlTopic.c_str(), packetId);
} }
void MQTTAsyncClient::onMqttConnect(bool sessionPresent) { void MQTTDriver::onMqttConnect(bool sessionPresent) {
LOG_INFO(TAG, "✅ Connected to MQTT broker (session present: %s)", sessionPresent ? "yes" : "no"); 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()); LOG_INFO(TAG, "🔍 Free heap AFTER MQTT connect: %d bytes", ESP.getFreeHeap());
@@ -225,7 +225,7 @@ void MQTTAsyncClient::onMqttConnect(bool sessionPresent) {
startHeartbeat(); startHeartbeat();
} }
void MQTTAsyncClient::onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { void MQTTDriver::onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
auto& mqttConfig = _configManager.getMqttConfig(); auto& mqttConfig = _configManager.getMqttConfig();
const char* reasonStr; const char* reasonStr;
@@ -283,15 +283,15 @@ void MQTTAsyncClient::onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
} }
void MQTTAsyncClient::onMqttSubscribe(uint16_t packetId, uint8_t qos) { void MQTTDriver::onMqttSubscribe(uint16_t packetId, uint8_t qos) {
LOG_INFO(TAG, "✅ Subscribed to topic (packetId=%d, QoS=%d)", packetId, qos); LOG_INFO(TAG, "✅ Subscribed to topic (packetId=%d, QoS=%d)", packetId, qos);
} }
void MQTTAsyncClient::onMqttUnsubscribe(uint16_t packetId) { void MQTTDriver::onMqttUnsubscribe(uint16_t packetId) {
LOG_DEBUG(TAG, "Unsubscribed from topic (packetId=%d)", packetId); LOG_DEBUG(TAG, "Unsubscribed from topic (packetId=%d)", packetId);
} }
void MQTTAsyncClient::onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) { void MQTTDriver::onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
// Convert to String // Convert to String
String topicStr = String(topic); String topicStr = String(topic);
String payloadStr = String(payload).substring(0, len); String payloadStr = String(payload).substring(0, len);
@@ -304,11 +304,11 @@ void MQTTAsyncClient::onMqttMessage(char* topic, char* payload, AsyncMqttClientM
} }
} }
void MQTTAsyncClient::onMqttPublish(uint16_t packetId) { void MQTTDriver::onMqttPublish(uint16_t packetId) {
LOG_DEBUG(TAG, "MQTT publish acknowledged (packetId=%d)", packetId); LOG_DEBUG(TAG, "MQTT publish acknowledged (packetId=%d)", packetId);
} }
void MQTTAsyncClient::attemptReconnection() { void MQTTDriver::attemptReconnection() {
// Double-check network is still up // Double-check network is still up
if (_networking.isConnected()) { if (_networking.isConnected()) {
LOG_INFO(TAG, "Attempting MQTT reconnection..."); LOG_INFO(TAG, "Attempting MQTT reconnection...");
@@ -318,15 +318,15 @@ void MQTTAsyncClient::attemptReconnection() {
} }
} }
void MQTTAsyncClient::mqttReconnectTaskFn(void* param) { void MQTTDriver::mqttReconnectTaskFn(void* param) {
MQTTAsyncClient* client = static_cast<MQTTAsyncClient*>(param); MQTTDriver* client = static_cast<MQTTDriver*>(param);
client->attemptReconnection(); client->attemptReconnection();
vTaskDelete(NULL); vTaskDelete(NULL);
} }
void MQTTAsyncClient::mqttReconnectTimerCallback(TimerHandle_t xTimer) { void MQTTDriver::mqttReconnectTimerCallback(TimerHandle_t xTimer) {
if (MQTTAsyncClient::_instance) { if (MQTTDriver::_instance) {
xTaskCreate(mqttReconnectTaskFn, "mqttRecon", 3072, MQTTAsyncClient::_instance, 5, NULL); xTaskCreate(mqttReconnectTaskFn, "mqttRecon", 3072, MQTTDriver::_instance, 5, NULL);
} }
} }
@@ -334,7 +334,7 @@ void MQTTAsyncClient::mqttReconnectTimerCallback(TimerHandle_t xTimer) {
// HEARTBEAT FUNCTIONALITY // HEARTBEAT FUNCTIONALITY
// ═══════════════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════════════
void MQTTAsyncClient::startHeartbeat() { void MQTTDriver::startHeartbeat() {
if (_heartbeatTimer) { if (_heartbeatTimer) {
LOG_INFO(TAG, "💓 Starting MQTT heartbeat (every %d seconds)", HEARTBEAT_INTERVAL / 1000); LOG_INFO(TAG, "💓 Starting MQTT heartbeat (every %d seconds)", HEARTBEAT_INTERVAL / 1000);
@@ -346,7 +346,7 @@ void MQTTAsyncClient::startHeartbeat() {
} }
} }
void MQTTAsyncClient::stopHeartbeat() { void MQTTDriver::stopHeartbeat() {
if (_heartbeatTimer) { if (_heartbeatTimer) {
xTimerStop(_heartbeatTimer, 0); xTimerStop(_heartbeatTimer, 0);
_heartbeatTaskHandle = nullptr; _heartbeatTaskHandle = nullptr;
@@ -354,7 +354,7 @@ void MQTTAsyncClient::stopHeartbeat() {
} }
} }
void MQTTAsyncClient::publishHeartbeat() { void MQTTDriver::publishHeartbeat() {
if (!_mqttClient.connected()) { if (!_mqttClient.connected()) {
LOG_WARNING(TAG, "⚠️ Cannot publish heartbeat - MQTT not connected"); LOG_WARNING(TAG, "⚠️ Cannot publish heartbeat - MQTT not connected");
return; return;
@@ -410,21 +410,21 @@ void MQTTAsyncClient::publishHeartbeat() {
} }
} }
void MQTTAsyncClient::mqttHeartbeatTaskFn(void* param) { void MQTTDriver::mqttHeartbeatTaskFn(void* param) {
MQTTAsyncClient* client = static_cast<MQTTAsyncClient*>(param); MQTTDriver* client = static_cast<MQTTDriver*>(param);
client->publishHeartbeat(); client->publishHeartbeat();
client->_heartbeatTaskHandle = nullptr; client->_heartbeatTaskHandle = nullptr;
vTaskDelete(NULL); vTaskDelete(NULL);
} }
void MQTTAsyncClient::heartbeatTimerCallback(TimerHandle_t xTimer) { void MQTTDriver::heartbeatTimerCallback(TimerHandle_t xTimer) {
if (MQTTAsyncClient::_instance) { if (MQTTDriver::_instance) {
// Guard: skip if previous heartbeat task is still running // Guard: skip if previous heartbeat task is still running
if (MQTTAsyncClient::_instance->_heartbeatTaskHandle != nullptr) { if (MQTTDriver::_instance->_heartbeatTaskHandle != nullptr) {
return; return;
} }
xTaskCreate(mqttHeartbeatTaskFn, "mqttHB", 3072, MQTTAsyncClient::_instance, 3, xTaskCreate(mqttHeartbeatTaskFn, "mqttHB", 3072, MQTTDriver::_instance, 3,
&MQTTAsyncClient::_instance->_heartbeatTaskHandle); &MQTTDriver::_instance->_heartbeatTaskHandle);
} }
} }
@@ -432,22 +432,22 @@ void MQTTAsyncClient::heartbeatTimerCallback(TimerHandle_t xTimer) {
// NETWORK STABILIZATION - NON-BLOCKING TIMER APPROACH // NETWORK STABILIZATION - NON-BLOCKING TIMER APPROACH
// ═══════════════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════════════
void MQTTAsyncClient::connectAfterStabilization() { void MQTTDriver::connectAfterStabilization() {
LOG_DEBUG(TAG, "Network stabilization complete - connecting to MQTT"); LOG_DEBUG(TAG, "Network stabilization complete - connecting to MQTT");
connect(); connect();
} }
void MQTTAsyncClient::mqttConnectTaskFn(void* param) { void MQTTDriver::mqttConnectTaskFn(void* param) {
// Runs in its own task so LOG calls don't overflow the Tmr Svc stack // Runs in its own task so LOG calls don't overflow the Tmr Svc stack
MQTTAsyncClient* client = static_cast<MQTTAsyncClient*>(param); MQTTDriver* client = static_cast<MQTTDriver*>(param);
client->connectAfterStabilization(); client->connectAfterStabilization();
vTaskDelete(NULL); vTaskDelete(NULL);
} }
void MQTTAsyncClient::networkStabilizationTimerCallback(TimerHandle_t xTimer) { void MQTTDriver::networkStabilizationTimerCallback(TimerHandle_t xTimer) {
if (MQTTAsyncClient::_instance) { if (MQTTDriver::_instance) {
// Defer to a task — timer callbacks run in Tmr Svc (2KB stack), not enough for connect() // Defer to a task — timer callbacks run in Tmr Svc (2KB stack), not enough for connect()
xTaskCreate(mqttConnectTaskFn, "mqttConnect", 3072, MQTTAsyncClient::_instance, 5, NULL); xTaskCreate(mqttConnectTaskFn, "mqttConnect", 3072, MQTTDriver::_instance, 5, NULL);
} }
} }
@@ -455,7 +455,7 @@ void MQTTAsyncClient::networkStabilizationTimerCallback(TimerHandle_t xTimer) {
// EXPONENTIAL BACKOFF CALCULATION // EXPONENTIAL BACKOFF CALCULATION
// ═══════════════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════════════
unsigned long MQTTAsyncClient::getReconnectDelay() { unsigned long MQTTDriver::getReconnectDelay() {
// First 3 attempts: Quick retries (5 seconds each) // First 3 attempts: Quick retries (5 seconds each)
if (_reconnectAttempts <= MQTT_MAX_QUICK_RETRIES) { if (_reconnectAttempts <= MQTT_MAX_QUICK_RETRIES) {
return MQTT_RECONNECT_BASE_DELAY; return MQTT_RECONNECT_BASE_DELAY;
@@ -1,17 +1,12 @@
/* /*
* ═══════════════════════════════════════════════════════════════════════════════════ * ═══════════════════════════════════════════════════════════════════════════════════
* MQTTASYNCCLIENT.HPP - MQTT Client with AsyncMqttClient * MQTTDRIVER.HPP - MQTT Protocol Driver
* ═══════════════════════════════════════════════════════════════════════════════════ * ═══════════════════════════════════════════════════════════════════════════════════
* *
* 🔒 MQTT CONNECTION WITH ASYNC ARCHITECTURE 🔒 * Low-level MQTT protocol driver using AsyncMqttClient.
* * Handles broker connection, auth, publish/subscribe, reconnect with exponential
* This class manages MQTT connections using AsyncMqttClient library: * backoff, and heartbeat. Wrapped by MQTTTransport for CommandBus integration.
* • Fully async/non-blocking operation *
* • No conflicts with AsyncWebServer
* • Auto-reconnection built-in
* • SSL/TLS support (optional)
* • Perfect for Mosquitto broker
*
* 📋 VERSION: 3.0 (AsyncMqttClient-based) * 📋 VERSION: 3.0 (AsyncMqttClient-based)
* 📅 DATE: 2025-01-04 * 📅 DATE: 2025-01-04
* 👨‍💻 AUTHOR: Advanced Bell Systems * 👨‍💻 AUTHOR: Advanced Bell Systems
@@ -26,15 +21,15 @@
class ConfigManager; class ConfigManager;
class Networking; class Networking;
class MQTTAsyncClient { class MQTTDriver {
public: public:
static MQTTAsyncClient* _instance; static MQTTDriver* _instance;
// Message callback type // Message callback type
using MessageCallback = std::function<void(const String& topic, const String& payload)>; using MessageCallback = std::function<void(const String& topic, const String& payload)>;
explicit MQTTAsyncClient(ConfigManager& configManager, Networking& networking); explicit MQTTDriver(ConfigManager& configManager, Networking& networking);
~MQTTAsyncClient(); ~MQTTDriver();
/** /**
* @brief Initialize MQTT client * @brief Initialize MQTT client
@@ -1,13 +1,13 @@
/* /*
* UARTCOMMANDHANDLER.CPP - UART Command Handler Implementation * UARTDRIVER.CPP - UART Protocol Driver Implementation
*/ */
#include "UARTCommandHandler.hpp" #include "UARTDriver.hpp"
#define TAG "UARTHandler" #define TAG "UARTHandler"
#include "../../Logging/Logging.hpp" #include "../../../Logging/Logging.hpp"
UARTCommandHandler::UARTCommandHandler(uint8_t txPin, uint8_t rxPin, uint32_t baudRate) UARTDriver::UARTDriver(uint8_t txPin, uint8_t rxPin, uint32_t baudRate)
: _serial(Serial2) : _serial(Serial2)
, _txPin(txPin) , _txPin(txPin)
, _rxPin(rxPin) , _rxPin(rxPin)
@@ -21,11 +21,11 @@ UARTCommandHandler::UARTCommandHandler(uint8_t txPin, uint8_t rxPin, uint32_t ba
resetBuffer(); resetBuffer();
} }
UARTCommandHandler::~UARTCommandHandler() { UARTDriver::~UARTDriver() {
_serial.end(); _serial.end();
} }
void UARTCommandHandler::begin() { void UARTDriver::begin() {
LOG_INFO(TAG, "Initializing UART Command Handler"); LOG_INFO(TAG, "Initializing UART Command Handler");
LOG_INFO(TAG, " TX Pin: GPIO%d", _txPin); LOG_INFO(TAG, " TX Pin: GPIO%d", _txPin);
LOG_INFO(TAG, " RX Pin: GPIO%d", _rxPin); LOG_INFO(TAG, " RX Pin: GPIO%d", _rxPin);
@@ -43,7 +43,7 @@ void UARTCommandHandler::begin() {
LOG_INFO(TAG, "UART Command Handler ready"); LOG_INFO(TAG, "UART Command Handler ready");
} }
void UARTCommandHandler::loop() { void UARTDriver::loop() {
if (!_ready) return; if (!_ready) return;
// Process all available bytes // Process all available bytes
@@ -74,11 +74,11 @@ void UARTCommandHandler::loop() {
} }
} }
void UARTCommandHandler::setCallback(MessageCallback callback) { void UARTDriver::setCallback(MessageCallback callback) {
_callback = callback; _callback = callback;
} }
void UARTCommandHandler::send(const String& response) { void UARTDriver::send(const String& response) {
if (!_ready) { if (!_ready) {
LOG_ERROR(TAG, "UART not ready, cannot send response"); LOG_ERROR(TAG, "UART not ready, cannot send response");
return; return;
@@ -91,7 +91,7 @@ void UARTCommandHandler::send(const String& response) {
LOG_DEBUG(TAG, "UART TX: %s", response.c_str()); LOG_DEBUG(TAG, "UART TX: %s", response.c_str());
} }
void UARTCommandHandler::processLine(const char* line) { void UARTDriver::processLine(const char* line) {
LOG_DEBUG(TAG, "UART RX: %s", line); LOG_DEBUG(TAG, "UART RX: %s", line);
// Skip empty lines or whitespace-only // Skip empty lines or whitespace-only
@@ -127,7 +127,7 @@ void UARTCommandHandler::processLine(const char* line) {
} }
} }
void UARTCommandHandler::resetBuffer() { void UARTDriver::resetBuffer() {
_bufferIndex = 0; _bufferIndex = 0;
memset(_buffer, 0, BUFFER_SIZE); memset(_buffer, 0, BUFFER_SIZE);
} }
@@ -1,22 +1,11 @@
/* /*
* ═══════════════════════════════════════════════════════════════════════════════════ * ═══════════════════════════════════════════════════════════════════════════════════
* UARTCOMMANDHANDLER.HPP - UART Command Interface for External Control Devices * UARTDRIVER.HPP - UART Protocol Driver
* ═══════════════════════════════════════════════════════════════════════════════════ * ═══════════════════════════════════════════════════════════════════════════════════
* *
* 🔌 UART COMMAND HANDLER 🔌 * Low-level UART protocol driver for external devices (LCD panels, button boards).
* * Reads newline-delimited JSON on Serial2 (TX: GPIO12, RX: GPIO13 @ 115200 baud).
* Enables command input from external devices (LCD panels, button controllers) * Wrapped by UARTTransport for CommandBus integration.
* via UART serial communication. Uses newline-delimited JSON protocol.
*
* Pin Configuration:
* • TX: GPIO12
* • RX: GPIO13
* • Baud: 115200 (configurable)
*
* Protocol:
* • Newline-delimited JSON messages
* • Same command format as MQTT/WebSocket
* • Responses sent back on same UART
* *
* 📋 VERSION: 1.0 * 📋 VERSION: 1.0
* 📅 DATE: 2025-01-19 * 📅 DATE: 2025-01-19
@@ -30,7 +19,7 @@
#include <ArduinoJson.h> #include <ArduinoJson.h>
#include <functional> #include <functional>
class UARTCommandHandler { class UARTDriver {
public: public:
// Default pin configuration // Default pin configuration
static constexpr uint8_t DEFAULT_TX_PIN = 12; static constexpr uint8_t DEFAULT_TX_PIN = 12;
@@ -47,11 +36,11 @@ public:
* @param rxPin GPIO pin for RX (default: 13) * @param rxPin GPIO pin for RX (default: 13)
* @param baudRate Baud rate (default: 115200) * @param baudRate Baud rate (default: 115200)
*/ */
explicit UARTCommandHandler(uint8_t txPin = DEFAULT_TX_PIN, explicit UARTDriver(uint8_t txPin = DEFAULT_TX_PIN,
uint8_t rxPin = DEFAULT_RX_PIN, uint8_t rxPin = DEFAULT_RX_PIN,
uint32_t baudRate = DEFAULT_BAUD_RATE); uint32_t baudRate = DEFAULT_BAUD_RATE);
~UARTCommandHandler(); ~UARTDriver();
/** /**
* @brief Initialize the UART interface * @brief Initialize the UART interface
@@ -1,17 +1,17 @@
/* /*
* WEBSOCKETSERVER.CPP - WebSocket Server Implementation * WEBSOCKETDRIVER.CPP - WebSocket Protocol Driver Implementation
*/ */
#include "WebSocketServer.hpp" #include "WebSocketDriver.hpp"
#define TAG "WebSocket" #define TAG "WebSocket"
#include "../../Logging/Logging.hpp" #include "../../../Logging/Logging.hpp"
#include "../ResponseBuilder/ResponseBuilder.hpp" #include "../../ResponseBuilder/ResponseBuilder.hpp"
// Static instance for callback // Static instance for callback
WebSocketServer* WebSocketServer::_instance = nullptr; WebSocketDriver* WebSocketDriver::_instance = nullptr;
WebSocketServer::WebSocketServer(AsyncWebSocket& webSocket, ClientManager& clientManager) WebSocketDriver::WebSocketDriver(AsyncWebSocket& webSocket, ClientManager& clientManager)
: _webSocket(webSocket) : _webSocket(webSocket)
, _clientManager(clientManager) , _clientManager(clientManager)
, _messageCallback(nullptr) { , _messageCallback(nullptr) {
@@ -19,11 +19,11 @@ WebSocketServer::WebSocketServer(AsyncWebSocket& webSocket, ClientManager& clien
_instance = this; _instance = this;
} }
WebSocketServer::~WebSocketServer() { WebSocketDriver::~WebSocketDriver() {
_instance = nullptr; _instance = nullptr;
} }
void WebSocketServer::begin() { void WebSocketDriver::begin() {
_webSocket.onEvent(onEvent); _webSocket.onEvent(onEvent);
LOG_INFO(TAG, "WebSocket server initialized on /ws"); LOG_INFO(TAG, "WebSocket server initialized on /ws");
@@ -32,41 +32,41 @@ void WebSocketServer::begin() {
// Note: We can't access _server here directly, so this must be done in CommunicationRouter // Note: We can't access _server here directly, so this must be done in CommunicationRouter
} }
void WebSocketServer::setCallback(MessageCallback callback) { void WebSocketDriver::setCallback(MessageCallback callback) {
_messageCallback = callback; _messageCallback = callback;
} }
void WebSocketServer::sendToClient(uint32_t clientId, const String& message) { void WebSocketDriver::sendToClient(uint32_t clientId, const String& message) {
_clientManager.sendToClient(clientId, message); _clientManager.sendToClient(clientId, message);
} }
void WebSocketServer::broadcastToAll(const String& message) { void WebSocketDriver::broadcastToAll(const String& message) {
_clientManager.broadcastToAll(message); _clientManager.broadcastToAll(message);
LOG_DEBUG(TAG, "Broadcast to all WebSocket clients: %s", message.c_str()); LOG_DEBUG(TAG, "Broadcast to all WebSocket clients: %s", message.c_str());
} }
void WebSocketServer::broadcastToMaster(const String& message) { void WebSocketDriver::broadcastToMaster(const String& message) {
_clientManager.sendToMasterClients(message); _clientManager.sendToMasterClients(message);
LOG_DEBUG(TAG, "Broadcast to master clients: %s", message.c_str()); LOG_DEBUG(TAG, "Broadcast to master clients: %s", message.c_str());
} }
void WebSocketServer::broadcastToSecondary(const String& message) { void WebSocketDriver::broadcastToSecondary(const String& message) {
_clientManager.sendToSecondaryClients(message); _clientManager.sendToSecondaryClients(message);
LOG_DEBUG(TAG, "Broadcast to secondary clients: %s", message.c_str()); LOG_DEBUG(TAG, "Broadcast to secondary clients: %s", message.c_str());
} }
bool WebSocketServer::hasClients() const { bool WebSocketDriver::hasClients() const {
return _clientManager.hasClients(); return _clientManager.hasClients();
} }
size_t WebSocketServer::getClientCount() const { size_t WebSocketDriver::getClientCount() const {
return _clientManager.getClientCount(); return _clientManager.getClientCount();
} }
void WebSocketServer::onEvent(AsyncWebSocket* server, AsyncWebSocketClient* client, void WebSocketDriver::onEvent(AsyncWebSocket* server, AsyncWebSocketClient* client,
AwsEventType type, void* arg, uint8_t* data, size_t len) { AwsEventType type, void* arg, uint8_t* data, size_t len) {
if (!_instance) { if (!_instance) {
LOG_ERROR(TAG, "WebSocketServer static instance is NULL - callback ignored!"); LOG_ERROR(TAG, "WebSocketDriver static instance is NULL - callback ignored!");
return; return;
} }
@@ -93,7 +93,7 @@ void WebSocketServer::onEvent(AsyncWebSocket* server, AsyncWebSocketClient* clie
} }
} }
void WebSocketServer::onConnect(AsyncWebSocketClient* client) { void WebSocketDriver::onConnect(AsyncWebSocketClient* client) {
LOG_INFO(TAG, "WebSocket client #%u connected from %s", LOG_INFO(TAG, "WebSocket client #%u connected from %s",
client->id(), client->remoteIP().toString().c_str()); client->id(), client->remoteIP().toString().c_str());
@@ -105,14 +105,14 @@ void WebSocketServer::onConnect(AsyncWebSocketClient* client) {
_clientManager.sendToClient(client->id(), welcomeMsg); _clientManager.sendToClient(client->id(), welcomeMsg);
} }
void WebSocketServer::onDisconnect(AsyncWebSocketClient* client) { void WebSocketDriver::onDisconnect(AsyncWebSocketClient* client) {
LOG_INFO(TAG, "WebSocket client #%u disconnected", client->id()); LOG_INFO(TAG, "WebSocket client #%u disconnected", client->id());
_clientManager.removeClient(client->id()); _clientManager.removeClient(client->id());
_clientManager.cleanupDisconnectedClients(); _clientManager.cleanupDisconnectedClients();
} }
void WebSocketServer::onData(AsyncWebSocketClient* client, void* arg, uint8_t* data, size_t len) { void WebSocketDriver::onData(AsyncWebSocketClient* client, void* arg, uint8_t* data, size_t len) {
AwsFrameInfo* info = (AwsFrameInfo*)arg; AwsFrameInfo* info = (AwsFrameInfo*)arg;
// Only handle complete, single-frame text messages // Only handle complete, single-frame text messages
@@ -1,16 +1,12 @@
/* /*
* ═══════════════════════════════════════════════════════════════════════════════════ * ═══════════════════════════════════════════════════════════════════════════════════
* WEBSOCKETSERVER.HPP - WebSocket Server Manager * WEBSOCKETDRIVER.HPP - WebSocket Protocol Driver
* ═══════════════════════════════════════════════════════════════════════════════════ * ═══════════════════════════════════════════════════════════════════════════════════
* *
* 📡 WEBSOCKET MULTI-CLIENT MANAGER 📡 * Low-level WebSocket protocol driver. Manages client lifecycle, broadcasts,
* * and targeted messaging. Wraps AsyncWebSocket + ClientManager.
* Handles WebSocket connections with: * Wrapped by WebSocketTransport for CommandBus integration.
* • Multi-client support with device type identification *
* • Automatic client cleanup
* • Broadcast and targeted messaging
* • Integration with ClientManager
*
* 📋 VERSION: 1.0 * 📋 VERSION: 1.0
* 📅 DATE: 2025-10-01 * 📅 DATE: 2025-10-01
* 👨‍💻 AUTHOR: Advanced Bell Systems * 👨‍💻 AUTHOR: Advanced Bell Systems
@@ -22,15 +18,15 @@
#include <Arduino.h> #include <Arduino.h>
#include <ESPAsyncWebServer.h> #include <ESPAsyncWebServer.h>
#include <ArduinoJson.h> #include <ArduinoJson.h>
#include "../../ClientManager/ClientManager.hpp" #include "../../../ClientManager/ClientManager.hpp"
class WebSocketServer { class WebSocketDriver {
public: public:
// Message callback type // Message callback type
using MessageCallback = std::function<void(uint32_t clientId, const JsonDocument& message)>; using MessageCallback = std::function<void(uint32_t clientId, const JsonDocument& message)>;
explicit WebSocketServer(AsyncWebSocket& webSocket, ClientManager& clientManager); explicit WebSocketDriver(AsyncWebSocket& webSocket, ClientManager& clientManager);
~WebSocketServer(); ~WebSocketDriver();
/** /**
* @brief Initialize WebSocket server * @brief Initialize WebSocket server
@@ -99,5 +95,5 @@ private:
void onData(AsyncWebSocketClient* client, void* arg, uint8_t* data, size_t len); void onData(AsyncWebSocketClient* client, void* arg, uint8_t* data, size_t len);
// Static instance for callback routing // Static instance for callback routing
static WebSocketServer* _instance; static WebSocketDriver* _instance;
}; };
@@ -1,189 +0,0 @@
/*
* ═══════════════════════════════════════════════════════════════════════════════════
* HTTPREQUESTHANDLER.CPP - HTTP REST API Request Handler Implementation
* ═══════════════════════════════════════════════════════════════════════════════════
*/
#include "HTTPRequestHandler.hpp"
#define TAG "HTTPHandler"
#include "../CommandHandler/CommandHandler.hpp"
#include "../../ConfigManager/ConfigManager.hpp"
#include "../../Logging/Logging.hpp"
HTTPRequestHandler::HTTPRequestHandler(AsyncWebServer& server,
ConfigManager& configManager)
: _server(server)
, _configManager(configManager)
, _commandHandler(nullptr) {
}
HTTPRequestHandler::~HTTPRequestHandler() {
}
void HTTPRequestHandler::begin() {
LOG_INFO(TAG, "HTTPRequestHandler - Initializing HTTP REST API endpoints");
// POST /api/command - Execute any command
_server.on("/api/command", HTTP_POST,
[](AsyncWebServerRequest* request) {
// This is called when request is complete but body is empty
request->send(400, "application/json", "{\"error\":\"No body provided\"}");
},
nullptr, // No file upload handler
[this](AsyncWebServerRequest* request, uint8_t* data, size_t len, size_t index, size_t total) {
// This is called for body data
if (index == 0) {
// First chunk - could allocate buffers if needed
}
if (index + len == total) {
// Last chunk - process the complete request
handleCommandRequest(request, data, len);
}
}
);
// GET /api/status - Get system status
_server.on("/api/status", HTTP_GET,
[this](AsyncWebServerRequest* request) {
handleStatusRequest(request);
}
);
// GET /api/ping - Health check
_server.on("/api/ping", HTTP_GET,
[this](AsyncWebServerRequest* request) {
handlePingRequest(request);
}
);
// Enable CORS for API endpoints (allows web apps to call the API)
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*");
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Headers", "Content-Type");
LOG_INFO(TAG, "HTTPRequestHandler - REST API endpoints registered");
LOG_INFO(TAG, " POST /api/command - Execute commands");
LOG_INFO(TAG, " GET /api/status - System status");
LOG_INFO(TAG, " GET /api/ping - Health check");
}
void HTTPRequestHandler::setCommandHandlerReference(CommandHandler* handler) {
_commandHandler = handler;
LOG_DEBUG(TAG, "HTTPRequestHandler - CommandHandler reference set");
}
bool HTTPRequestHandler::isHealthy() const {
// HTTP handler is healthy if it has been initialized with dependencies
return _commandHandler != nullptr;
}
void HTTPRequestHandler::handleCommandRequest(AsyncWebServerRequest* request, uint8_t* data, size_t len) {
if (!_commandHandler) {
sendErrorResponse(request, 503, "Command handler not initialized");
return;
}
// Parse JSON from body
JsonDocument doc;
DeserializationError error = deserializeJson(doc, data, len);
if (error) {
LOG_WARNING(TAG, "HTTPRequestHandler - JSON parse error: %s", error.c_str());
sendErrorResponse(request, 400, "Invalid JSON");
return;
}
LOG_DEBUG(TAG, "HTTPRequestHandler - Processing command via HTTP");
// Create message context for HTTP (treat as WebSocket with special ID)
CommandHandler::MessageContext context(CommandHandler::MessageSource::WEBSOCKET, 0xFFFFFFFF);
// Capture request pointer for response
AsyncWebServerRequest* capturedRequest = request;
bool responseSent = false;
// Set temporary response callback to capture the response
auto originalCallback = [capturedRequest, &responseSent](const String& response, const CommandHandler::MessageContext& ctx) {
if (!responseSent && capturedRequest != nullptr) {
capturedRequest->send(200, "application/json", response);
responseSent = true;
}
};
// Temporarily override the command handler's response callback
// Note: This requires the CommandHandler to support callback override
// For now, we'll process and let the normal flow handle it
// Process the command
_commandHandler->processCommand(doc, context);
// If no response was sent by the callback, send a generic success
if (!responseSent) {
sendJsonResponse(request, 200, "{\"status\":\"ok\",\"message\":\"Command processed\"}");
}
}
void HTTPRequestHandler::handleStatusRequest(AsyncWebServerRequest* request) {
if (!_commandHandler) {
sendErrorResponse(request, 503, "Command handler not initialized");
return;
}
LOG_DEBUG(TAG, "HTTPRequestHandler - Status request via HTTP");
// Create a status command
JsonDocument doc;
doc["group"] = "system";
doc["action"] = "status";
// Create message context
CommandHandler::MessageContext context(CommandHandler::MessageSource::WEBSOCKET, 0xFFFFFFFF);
// Capture request for response
AsyncWebServerRequest* capturedRequest = request;
bool responseSent = false;
// Process via command handler
_commandHandler->processCommand(doc, context);
// Fallback response if needed
if (!responseSent) {
JsonDocument response;
response["status"] = "ok";
response["device_uid"] = _configManager.getDeviceUID();
response["fw_version"] = _configManager.getFwVersion();
String output;
serializeJson(response, output);
sendJsonResponse(request, 200, output);
}
}
void HTTPRequestHandler::handlePingRequest(AsyncWebServerRequest* request) {
LOG_DEBUG(TAG, "HTTPRequestHandler - Ping request via HTTP");
JsonDocument response;
response["status"] = "ok";
response["message"] = "pong";
response["uptime"] = millis();
String output;
serializeJson(response, output);
sendJsonResponse(request, 200, output);
}
void HTTPRequestHandler::sendJsonResponse(AsyncWebServerRequest* request, int code, const String& json) {
request->send(code, "application/json", json);
}
void HTTPRequestHandler::sendErrorResponse(AsyncWebServerRequest* request, int code, const String& error) {
JsonDocument doc;
doc["status"] = "error";
doc["error"] = error;
String output;
serializeJson(doc, output);
sendJsonResponse(request, code, output);
}
@@ -1,76 +0,0 @@
/*
* ═══════════════════════════════════════════════════════════════════════════════════
* HTTPREQUESTHANDLER.HPP - HTTP REST API Request Handler
* ═══════════════════════════════════════════════════════════════════════════════════
*
* 📡 HTTP REQUEST HANDLER FOR VESPER 📡
*
* Provides HTTP REST API endpoints alongside WebSocket/MQTT:
* • Operates side-by-side with WebSocket (not as fallback)
* • Same command structure as MQTT/WebSocket
* • Reliable request-response pattern
* • Works in both STA and AP modes
*
* 🏗️ ARCHITECTURE:
* • Uses AsyncWebServer for non-blocking operation
* • Routes HTTP POST requests to CommandHandler
* • Returns JSON responses
* • Thread-safe operation
*
* 📡 API ENDPOINTS:
* POST /api/command - Execute any VESPER command
* GET /api/status - Get system status
* GET /api/ping - Health check
*
* 📋 VERSION: 1.0
* 📅 DATE: 2025-12-28
* 👨‍💻 AUTHOR: Advanced Bell Systems
* ═══════════════════════════════════════════════════════════════════════════════════
*/
#pragma once
#include <Arduino.h>
#include <ESPAsyncWebServer.h>
#include <ArduinoJson.h>
// Forward declarations
class CommandHandler;
class ConfigManager;
class HTTPRequestHandler {
public:
explicit HTTPRequestHandler(AsyncWebServer& server,
ConfigManager& configManager);
~HTTPRequestHandler();
/**
* @brief Initialize HTTP request handler and register endpoints
*/
void begin();
/**
* @brief Set CommandHandler reference for processing commands
*/
void setCommandHandlerReference(CommandHandler* handler);
/**
* @brief Check if HTTP handler is healthy
*/
bool isHealthy() const;
private:
// Dependencies
AsyncWebServer& _server;
ConfigManager& _configManager;
CommandHandler* _commandHandler;
// Endpoint handlers
void handleCommandRequest(AsyncWebServerRequest* request, uint8_t* data, size_t len);
void handleStatusRequest(AsyncWebServerRequest* request);
void handlePingRequest(AsyncWebServerRequest* request);
// Helper methods
void sendJsonResponse(AsyncWebServerRequest* request, int code, const String& json);
void sendErrorResponse(AsyncWebServerRequest* request, int code, const String& error);
};
@@ -1,11 +1,11 @@
#include "MQTTHandler.hpp" #include "MQTTHandler.hpp"
#include "../../../ConfigManager/ConfigManager.hpp" #include "../../../ConfigManager/ConfigManager.hpp"
#include "../../../Communication/MQTTAsyncClient/MQTTAsyncClient.hpp" #include "../../../Communication/Drivers/MQTTDriver/MQTTDriver.hpp"
#include "../../../Logging/Logging.hpp" #include "../../../Logging/Logging.hpp"
#define TAG "MQTTHandler" #define TAG "MQTTHandler"
MQTTHandler::MQTTHandler(ConfigManager& configManager, MQTTAsyncClient& mqttClient) MQTTHandler::MQTTHandler(ConfigManager& configManager, MQTTDriver& mqttClient)
: _configManager(configManager), _mqttClient(mqttClient) {} : _configManager(configManager), _mqttClient(mqttClient) {}
std::vector<String> MQTTHandler::commands() const { std::vector<String> MQTTHandler::commands() const {
@@ -5,18 +5,17 @@
class ConfigManager; class ConfigManager;
// Forward declare the transport so we don't pull in all of MQTT yet. // Forward declare the driver to avoid pulling in full MQTTDriver header.
// In Stage 3 this will be MQTTTransport; for now it wraps MQTTAsyncClient. class MQTTDriver;
class MQTTAsyncClient;
class MQTTHandler : public ICommandHandler { class MQTTHandler : public ICommandHandler {
public: public:
MQTTHandler(ConfigManager& configManager, MQTTAsyncClient& mqttClient); MQTTHandler(ConfigManager& configManager, MQTTDriver& mqttClient);
std::vector<String> commands() const override; std::vector<String> commands() const override;
CommandResult execute(const CommandEnvelope& envelope) override; CommandResult execute(const CommandEnvelope& envelope) override;
private: private:
ConfigManager& _configManager; ConfigManager& _configManager;
MQTTAsyncClient& _mqttClient; MQTTDriver& _mqttClient;
}; };
@@ -6,7 +6,7 @@
#define TAG "MQTTTransport" #define TAG "MQTTTransport"
#include "../../../Logging/Logging.hpp" #include "../../../Logging/Logging.hpp"
MQTTTransport::MQTTTransport(MQTTAsyncClient& mqttClient, CommandBus& bus) MQTTTransport::MQTTTransport(MQTTDriver& mqttClient, CommandBus& bus)
: _mqtt(mqttClient) : _mqtt(mqttClient)
, _bus(bus) { , _bus(bus) {
} }
@@ -31,7 +31,7 @@ bool MQTTTransport::isHealthy() const {
} }
void MQTTTransport::broadcast(const String& message) { void MQTTTransport::broadcast(const String& message) {
_mqtt.publish("", message); // MQTTAsyncClient::publish() routes "" → _dataTopic _mqtt.publish("", message); // MQTTDriver::publish() routes "" → _dataTopic
} }
void MQTTTransport::onNetworkConnected() { void MQTTTransport::onNetworkConnected() {
@@ -2,29 +2,29 @@
#include <Arduino.h> #include <Arduino.h>
#include "../ITransport.hpp" #include "../ITransport.hpp"
#include "../../MQTTAsyncClient/MQTTAsyncClient.hpp" #include "../../Drivers/MQTTDriver/MQTTDriver.hpp"
class CommandBus; class CommandBus;
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// MQTTTransport // MQTTTransport
// //
// ITransport wrapper around the existing MQTTAsyncClient. // ITransport wrapper around the existing MQTTDriver.
// //
// Responsibilities: // Responsibilities:
// - Delegates connection lifecycle to MQTTAsyncClient // - Delegates connection lifecycle to MQTTDriver
// - Parses incoming MQTT JSON messages into CommandEnvelopes // - Parses incoming MQTT JSON messages into CommandEnvelopes
// - Injects a reply lambda that publishes the response to the data topic // - Injects a reply lambda that publishes the response to the data topic
// - Dispatches to the CommandBus // - Dispatches to the CommandBus
// - broadcast() publishes to the device data topic (telemetry, events) // - broadcast() publishes to the device data topic (telemetry, events)
// //
// The underlying MQTTAsyncClient (and its timers, heartbeat, reconnect logic) // The underlying MQTTDriver (and its timers, heartbeat, reconnect logic)
// is unchanged — this transport just owns the bus glue. // is unchanged — this transport just owns the bus glue.
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
class MQTTTransport : public ITransport { class MQTTTransport : public ITransport {
public: public:
MQTTTransport(MQTTAsyncClient& mqttClient, CommandBus& bus); MQTTTransport(MQTTDriver& mqttClient, CommandBus& bus);
void begin() override; void begin() override;
void loop() override; // no-op — AsyncMqttClient is fully async void loop() override; // no-op — AsyncMqttClient is fully async
@@ -40,9 +40,9 @@ public:
void onNetworkDisconnected(); void onNetworkDisconnected();
private: private:
MQTTAsyncClient& _mqtt; MQTTDriver& _mqtt;
CommandBus& _bus; CommandBus& _bus;
// Invoked by MQTTAsyncClient's message callback // Invoked by MQTTDriver's message callback
void onMessage(const String& topic, const String& payload); void onMessage(const String& topic, const String& payload);
}; };
@@ -23,7 +23,7 @@ const size_t UARTTransport::WHITELIST_SIZE =
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
UARTTransport::UARTTransport(UARTCommandHandler& uart, CommandBus& bus) UARTTransport::UARTTransport(UARTDriver& uart, CommandBus& bus)
: _uart(uart) : _uart(uart)
, _bus(bus) { , _bus(bus) {
} }
@@ -2,14 +2,14 @@
#include <Arduino.h> #include <Arduino.h>
#include "../ITransport.hpp" #include "../ITransport.hpp"
#include "../../UARTCommandHandler/UARTCommandHandler.hpp" #include "../../Drivers/UARTDriver/UARTDriver.hpp"
class CommandBus; class CommandBus;
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// UARTTransport // UARTTransport
// //
// ITransport wrapper around the existing UARTCommandHandler. // ITransport wrapper around the existing UARTDriver.
// //
// The UART port talks to a slave LCD/button board. Only a small whitelist of // The UART port talks to a slave LCD/button board. Only a small whitelist of
// commands are accepted from this transport to prevent feedback loops and // commands are accepted from this transport to prevent feedback loops and
@@ -31,10 +31,10 @@ class CommandBus;
class UARTTransport : public ITransport { class UARTTransport : public ITransport {
public: public:
UARTTransport(UARTCommandHandler& uart, CommandBus& bus); UARTTransport(UARTDriver& uart, CommandBus& bus);
void begin() override; void begin() override;
void loop() override; // polls UARTCommandHandler::loop() void loop() override; // polls UARTDriver::loop()
bool isHealthy() const override; bool isHealthy() const override;
String name() const override { return "UART"; } String name() const override { return "UART"; }
@@ -42,7 +42,7 @@ public:
void broadcast(const String& message) override; void broadcast(const String& message) override;
private: private:
UARTCommandHandler& _uart; UARTDriver& _uart;
CommandBus& _bus; CommandBus& _bus;
// Commands the UART slave is allowed to issue // Commands the UART slave is allowed to issue
@@ -51,6 +51,6 @@ private:
bool isWhitelisted(const String& command) const; bool isWhitelisted(const String& command) const;
// Invoked by UARTCommandHandler's message callback // Invoked by UARTDriver's message callback
void onMessage(JsonDocument& doc); void onMessage(JsonDocument& doc);
}; };
@@ -6,7 +6,7 @@
#define TAG "WebSocketTransport" #define TAG "WebSocketTransport"
#include "../../../Logging/Logging.hpp" #include "../../../Logging/Logging.hpp"
WebSocketTransport::WebSocketTransport(WebSocketServer& wsServer, CommandBus& bus) WebSocketTransport::WebSocketTransport(WebSocketDriver& wsServer, CommandBus& bus)
: _ws(wsServer) : _ws(wsServer)
, _bus(bus) { , _bus(bus) {
} }
@@ -2,17 +2,17 @@
#include <Arduino.h> #include <Arduino.h>
#include "../ITransport.hpp" #include "../ITransport.hpp"
#include "../../WebSocketServer/WebSocketServer.hpp" #include "../../Drivers/WebSocketDriver/WebSocketDriver.hpp"
class CommandBus; class CommandBus;
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// WebSocketTransport // WebSocketTransport
// //
// ITransport wrapper around the existing WebSocketServer. // ITransport wrapper around the existing WebSocketDriver.
// //
// Responsibilities: // Responsibilities:
// - Delegates connection lifecycle and client management to WebSocketServer // - Delegates connection lifecycle and client management to WebSocketDriver
// - Parses incoming WebSocket JSON messages into CommandEnvelopes // - Parses incoming WebSocket JSON messages into CommandEnvelopes
// - Injects a reply lambda that sends the response back to the originating client // - Injects a reply lambda that sends the response back to the originating client
// - Dispatches to the CommandBus // - Dispatches to the CommandBus
@@ -24,7 +24,7 @@ class CommandBus;
class WebSocketTransport : public ITransport { class WebSocketTransport : public ITransport {
public: public:
WebSocketTransport(WebSocketServer& wsServer, CommandBus& bus); WebSocketTransport(WebSocketDriver& wsServer, CommandBus& bus);
void begin() override; void begin() override;
void loop() override; // no-op — AsyncWebServer is event-driven void loop() override; // no-op — AsyncWebServer is event-driven
@@ -45,9 +45,9 @@ public:
size_t getClientCount() const; size_t getClientCount() const;
private: private:
WebSocketServer& _ws; WebSocketDriver& _ws;
CommandBus& _bus; CommandBus& _bus;
// Invoked by WebSocketServer's message callback // Invoked by WebSocketDriver's message callback
void onMessage(uint32_t clientId, const JsonDocument& doc); void onMessage(uint32_t clientId, const JsonDocument& doc);
}; };