refactor: Fixed the file hierarchy and switched to platform.io
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,163 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* COMMANDHANDLER.HPP - Unified Command Processing
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* ⚙️ 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);
|
||||
};
|
||||
@@ -0,0 +1,417 @@
|
||||
/*
|
||||
* COMMUNICATIONROUTER.CPP - Communication Router Implementation
|
||||
*/
|
||||
|
||||
#include "CommunicationRouter.hpp"
|
||||
|
||||
#define TAG "CommRouter"
|
||||
#include "../../ConfigManager/ConfigManager.hpp"
|
||||
#include "../../OTAManager/OTAManager.hpp"
|
||||
#include "../../Networking/Networking.hpp"
|
||||
#include "../../Logging/Logging.hpp"
|
||||
#include "../../Player/Player.hpp"
|
||||
#include "../../FileManager/FileManager.hpp"
|
||||
#include "../../TimeKeeper/TimeKeeper.hpp"
|
||||
#include "../../FirmwareValidator/FirmwareValidator.hpp"
|
||||
|
||||
CommunicationRouter::CommunicationRouter(ConfigManager& configManager,
|
||||
OTAManager& otaManager,
|
||||
Networking& networking,
|
||||
AsyncWebServer& server,
|
||||
AsyncWebSocket& webSocket,
|
||||
AsyncUDP& udp)
|
||||
: _configManager(configManager)
|
||||
, _otaManager(otaManager)
|
||||
, _networking(networking)
|
||||
, _server(server)
|
||||
, _webSocket(webSocket)
|
||||
, _udp(udp)
|
||||
, _player(nullptr)
|
||||
, _fileManager(nullptr)
|
||||
, _timeKeeper(nullptr)
|
||||
, _firmwareValidator(nullptr)
|
||||
, _mqttClient(configManager, networking)
|
||||
, _clientManager()
|
||||
, _wsServer(webSocket, _clientManager)
|
||||
, _commandHandler(configManager, otaManager)
|
||||
, _httpHandler(server, configManager)
|
||||
, _uartHandler()
|
||||
, _settingsServer(server, configManager, networking) {}
|
||||
|
||||
CommunicationRouter::~CommunicationRouter() {}
|
||||
|
||||
void CommunicationRouter::begin() {
|
||||
LOG_INFO(TAG, "Initializing Communication Router v4.0 (Modular)");
|
||||
|
||||
// 🔥 CRITICAL: Initialize WebSocket FIRST to ensure it's always set up
|
||||
// Even if MQTT fails, we want WebSocket to work!
|
||||
LOG_INFO(TAG, "Setting up WebSocket server...");
|
||||
|
||||
// Initialize WebSocket server
|
||||
_wsServer.begin();
|
||||
_wsServer.setCallback([this](uint32_t clientId, const JsonDocument& message) {
|
||||
onWebSocketMessage(clientId, message);
|
||||
});
|
||||
|
||||
// 🔥 CRITICAL FIX: Attach WebSocket handler to AsyncWebServer
|
||||
// This MUST happen before any potential failures!
|
||||
_server.addHandler(&_webSocket);
|
||||
LOG_INFO(TAG, "✅ WebSocket handler attached to AsyncWebServer on /ws");
|
||||
|
||||
//Now initialize MQTT client (can fail without breaking WebSocket)
|
||||
try {
|
||||
LOG_INFO(TAG, "Setting up MQTT client...");
|
||||
_mqttClient.begin();
|
||||
_mqttClient.setCallback([this](const String& topic, const String& payload) {
|
||||
onMqttMessage(topic, payload);
|
||||
});
|
||||
|
||||
// Setup MQTT logging callback
|
||||
String logTopic = "vesper/" + _configManager.getDeviceUID() + "/logs";
|
||||
Logging::setMqttPublishCallback(
|
||||
[this](const String& topic, const String& payload, int qos) {
|
||||
_mqttClient.publish(topic, payload, qos, false);
|
||||
},
|
||||
logTopic
|
||||
);
|
||||
|
||||
// Apply log levels from config for all three channels
|
||||
Logging::setSerialLevel((Logging::LogLevel)_configManager.getSerialLogLevel());
|
||||
Logging::setMqttLevel((Logging::LogLevel)_configManager.getMqttLogLevel());
|
||||
Logging::setSdLevel((Logging::LogLevel)_configManager.getSdLogLevel());
|
||||
LOG_INFO(TAG, "Log levels applied — Serial:%d MQTT:%d SD:%d",
|
||||
_configManager.getSerialLogLevel(),
|
||||
_configManager.getMqttLogLevel(),
|
||||
_configManager.getSdLogLevel());
|
||||
|
||||
// Silence MQTT-internal subsystems on the MQTT channel to prevent log storms.
|
||||
// These systems generate logs while sending logs — suppress them over MQTT only.
|
||||
Logging::setSubsystemMqttLevel("MQTTClient", Logging::NONE);
|
||||
Logging::setSubsystemMqttLevel("CommRouter", Logging::WARNING);
|
||||
Logging::setSubsystemMqttLevel("Logger", Logging::NONE);
|
||||
|
||||
LOG_INFO(TAG, "✅ MQTT client initialized");
|
||||
} catch (...) {
|
||||
LOG_ERROR(TAG, "❌ MQTT initialization failed, but WebSocket is still available");
|
||||
}
|
||||
|
||||
// Wire up SD logging channel (requires FileManager to be set first via setFileManagerReference)
|
||||
// SD callback is registered lazily in setFileManagerReference once the pointer is available
|
||||
|
||||
// 🔥 CRITICAL FIX: Connect ClientManager to CommandHandler
|
||||
_commandHandler.setClientManagerReference(&_clientManager);
|
||||
LOG_INFO(TAG, "ClientManager reference set for CommandHandler");
|
||||
|
||||
// 🔥 Set CommunicationRouter reference for MQTT control commands
|
||||
_commandHandler.setCommunicationRouterReference(this);
|
||||
LOG_INFO(TAG, "CommunicationRouter reference set for CommandHandler");
|
||||
|
||||
// Setup command handler response callback
|
||||
_commandHandler.setResponseCallback([this](const String& response, const CommandHandler::MessageContext& context) {
|
||||
sendResponse(response, context);
|
||||
});
|
||||
|
||||
// Initialize HTTP Request Handler
|
||||
LOG_INFO(TAG, "Setting up HTTP REST API...");
|
||||
_httpHandler.begin();
|
||||
_httpHandler.setCommandHandlerReference(&_commandHandler);
|
||||
LOG_INFO(TAG, "✅ HTTP REST API initialized");
|
||||
|
||||
// Initialize Settings Web Server
|
||||
LOG_INFO(TAG, "Setting up Settings Web Server...");
|
||||
_settingsServer.begin();
|
||||
LOG_INFO(TAG, "✅ Settings Web Server initialized at /settings");
|
||||
|
||||
// Initialize UART Command Handler
|
||||
LOG_INFO(TAG, "Setting up UART Command Handler...");
|
||||
_uartHandler.begin();
|
||||
_uartHandler.setCallback([this](JsonDocument& message) {
|
||||
onUartMessage(message);
|
||||
});
|
||||
LOG_INFO(TAG, "✅ UART Command Handler initialized (TX: GPIO12, RX: GPIO13)");
|
||||
|
||||
LOG_INFO(TAG, "Communication Router initialized with modular architecture");
|
||||
LOG_INFO(TAG, " • MQTT: AsyncMqttClient");
|
||||
LOG_INFO(TAG, " • WebSocket: Multi-client support");
|
||||
LOG_INFO(TAG, " • HTTP REST API: /api endpoints");
|
||||
LOG_INFO(TAG, " • UART: External device control");
|
||||
LOG_INFO(TAG, " • Settings Page: /settings");
|
||||
}
|
||||
|
||||
void CommunicationRouter::loop() {
|
||||
// Process UART incoming data
|
||||
_uartHandler.loop();
|
||||
}
|
||||
|
||||
void CommunicationRouter::setPlayerReference(Player* player) {
|
||||
_player = player;
|
||||
_commandHandler.setPlayerReference(player);
|
||||
}
|
||||
|
||||
void CommunicationRouter::setFileManagerReference(FileManager* fm) {
|
||||
_fileManager = fm;
|
||||
_commandHandler.setFileManagerReference(fm);
|
||||
|
||||
// Register SD log channel now that FileManager is available
|
||||
if (fm != nullptr) {
|
||||
Logging::setSdWriteCallback([fm](const String& line) {
|
||||
fm->appendLine("/logs/vesper.log", line);
|
||||
});
|
||||
LOG_INFO(TAG, "SD log channel registered -> /logs/vesper.log");
|
||||
}
|
||||
}
|
||||
|
||||
void CommunicationRouter::setTimeKeeperReference(Timekeeper* tk) {
|
||||
_timeKeeper = tk;
|
||||
_commandHandler.setTimeKeeperReference(tk);
|
||||
}
|
||||
|
||||
void CommunicationRouter::setFirmwareValidatorReference(FirmwareValidator* fv) {
|
||||
_firmwareValidator = fv;
|
||||
_commandHandler.setFirmwareValidatorReference(fv);
|
||||
}
|
||||
|
||||
void CommunicationRouter::setTelemetryReference(Telemetry* telemetry) {
|
||||
_commandHandler.setTelemetryReference(telemetry);
|
||||
}
|
||||
|
||||
void CommunicationRouter::setupUdpDiscovery() {
|
||||
uint16_t discoveryPort = _configManager.getNetworkConfig().discoveryPort;
|
||||
if (_udp.listen(discoveryPort)) {
|
||||
LOG_INFO(TAG, "UDP discovery listening on port %u", discoveryPort);
|
||||
|
||||
_udp.onPacket([this](AsyncUDPPacket packet) {
|
||||
String msg = String((const char*)packet.data(), packet.length());
|
||||
LOG_DEBUG(TAG, "UDP from %s:%u -> %s",
|
||||
packet.remoteIP().toString().c_str(),
|
||||
packet.remotePort(),
|
||||
msg.c_str());
|
||||
|
||||
bool shouldReply = false;
|
||||
|
||||
if (msg.indexOf("discover") >= 0) {
|
||||
shouldReply = true;
|
||||
} else {
|
||||
StaticJsonDocument<128> req;
|
||||
DeserializationError err = deserializeJson(req, msg);
|
||||
if (!err) {
|
||||
shouldReply = (req["op"] == "discover");
|
||||
}
|
||||
}
|
||||
|
||||
if (!shouldReply) return;
|
||||
|
||||
StaticJsonDocument<256> doc;
|
||||
doc["op"] = "discover_reply";
|
||||
doc["svc"] = "vesper";
|
||||
doc["ver"] = 1;
|
||||
|
||||
doc["name"] = "Proj. Vesper v2.0";
|
||||
doc["id"] = _configManager.getDeviceUID();
|
||||
doc["ip"] = _networking.getLocalIP();
|
||||
char wsUrl[64];
|
||||
snprintf(wsUrl, sizeof(wsUrl), "ws://%s:80/ws", _networking.getLocalIP().c_str());
|
||||
doc["ws"] = wsUrl;
|
||||
doc["port"] = 80;
|
||||
doc["fw"] = "2.0";
|
||||
doc["clients"] = _clientManager.getClientCount();
|
||||
|
||||
String out;
|
||||
serializeJson(doc, out);
|
||||
|
||||
_udp.writeTo((const uint8_t*)out.c_str(), out.length(),
|
||||
packet.remoteIP(), packet.remotePort());
|
||||
});
|
||||
} else {
|
||||
LOG_ERROR(TAG, "Failed to start UDP discovery.");
|
||||
}
|
||||
}
|
||||
|
||||
bool CommunicationRouter::isMqttConnected() const {
|
||||
return _mqttClient.isConnected();
|
||||
}
|
||||
|
||||
bool CommunicationRouter::hasActiveWebSocketClients() const {
|
||||
return _wsServer.hasClients();
|
||||
}
|
||||
|
||||
size_t CommunicationRouter::getWebSocketClientCount() const {
|
||||
return _wsServer.getClientCount();
|
||||
}
|
||||
|
||||
bool CommunicationRouter::isHealthy() const {
|
||||
// Check if required references are set
|
||||
if (!_player || !_fileManager || !_timeKeeper) {
|
||||
LOG_WARNING(TAG, "Unhealthy - missing subsystem references (player=%d fileManager=%d timeKeeper=%d)",
|
||||
_player != nullptr, _fileManager != nullptr, _timeKeeper != nullptr);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check network connectivity first — no point checking connections without a network
|
||||
if (!_networking.isConnected()) {
|
||||
LOG_WARNING(TAG, "Unhealthy - no network connection");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if at least one protocol is connected
|
||||
if (!isMqttConnected() && !hasActiveWebSocketClients()) {
|
||||
LOG_WARNING(TAG, "Unhealthy - no active connections (MQTT=%d, WebSocket=%d)",
|
||||
isMqttConnected(), hasActiveWebSocketClients());
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void CommunicationRouter::broadcastStatus(const String& statusMessage) {
|
||||
publishToMqtt(statusMessage);
|
||||
_wsServer.broadcastToAll(statusMessage);
|
||||
}
|
||||
|
||||
void CommunicationRouter::broadcastStatus(const JsonDocument& statusJson) {
|
||||
String statusMessage;
|
||||
serializeJson(statusJson, statusMessage);
|
||||
broadcastStatus(statusMessage);
|
||||
}
|
||||
|
||||
void CommunicationRouter::broadcastToMasterClients(const String& message) {
|
||||
_wsServer.broadcastToMaster(message);
|
||||
}
|
||||
|
||||
void CommunicationRouter::broadcastToSecondaryClients(const String& message) {
|
||||
_wsServer.broadcastToSecondary(message);
|
||||
}
|
||||
|
||||
void CommunicationRouter::broadcastToAllWebSocketClients(const String& message) {
|
||||
_wsServer.broadcastToAll(message);
|
||||
}
|
||||
|
||||
void CommunicationRouter::broadcastToAllWebSocketClients(const JsonDocument& message) {
|
||||
String messageStr;
|
||||
serializeJson(message, messageStr);
|
||||
_wsServer.broadcastToAll(messageStr);
|
||||
}
|
||||
|
||||
void CommunicationRouter::publishToMqtt(const String& data) {
|
||||
if (_mqttClient.isConnected()) {
|
||||
_mqttClient.publish("data", data, 0, false);
|
||||
LOG_DEBUG(TAG, "Published to MQTT: %s", data.c_str());
|
||||
} else {
|
||||
LOG_ERROR(TAG, "MQTT Not Connected! Message Failed: %s", data.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
void CommunicationRouter::sendBellOverloadNotification(const std::vector<uint8_t>& bellNumbers,
|
||||
const std::vector<uint16_t>& bellLoads,
|
||||
const String& severity) {
|
||||
StaticJsonDocument<512> overloadMsg;
|
||||
overloadMsg["status"] = "INFO";
|
||||
overloadMsg["type"] = "bell_overload";
|
||||
|
||||
JsonArray bellsArray = overloadMsg["payload"]["bells"].to<JsonArray>();
|
||||
JsonArray loadsArray = overloadMsg["payload"]["loads"].to<JsonArray>();
|
||||
|
||||
for (size_t i = 0; i < bellNumbers.size() && i < bellLoads.size(); i++) {
|
||||
bellsArray.add(bellNumbers[i] + 1);
|
||||
loadsArray.add(bellLoads[i]);
|
||||
}
|
||||
|
||||
overloadMsg["payload"]["severity"] = severity;
|
||||
broadcastStatus(overloadMsg);
|
||||
|
||||
LOG_WARNING(TAG, "Bell overload notification sent: %d bells, severity: %s",
|
||||
bellNumbers.size(), severity.c_str());
|
||||
}
|
||||
|
||||
void CommunicationRouter::onNetworkConnected() {
|
||||
LOG_DEBUG(TAG, "Network connected - notifying MQTT client");
|
||||
_mqttClient.onNetworkConnected();
|
||||
}
|
||||
|
||||
void CommunicationRouter::onNetworkDisconnected() {
|
||||
LOG_DEBUG(TAG, "Network disconnected - notifying MQTT client");
|
||||
_mqttClient.onNetworkDisconnected();
|
||||
}
|
||||
|
||||
void CommunicationRouter::onMqttMessage(const String& topic, const String& payload) {
|
||||
LOG_DEBUG(TAG, "MQTT message received: %s", payload.c_str());
|
||||
|
||||
// Parse JSON
|
||||
StaticJsonDocument<2048> doc;
|
||||
DeserializationError error = deserializeJson(doc, payload);
|
||||
|
||||
if (error) {
|
||||
LOG_ERROR(TAG, "Failed to parse MQTT JSON: %s", error.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
// Create message context for MQTT
|
||||
CommandHandler::MessageContext context(CommandHandler::MessageSource::MQTT);
|
||||
|
||||
// Forward to command handler
|
||||
_commandHandler.processCommand(doc, context);
|
||||
}
|
||||
|
||||
void CommunicationRouter::onWebSocketMessage(uint32_t clientId, const JsonDocument& message) {
|
||||
// Extract command for logging
|
||||
String cmd = message["cmd"] | "unknown";
|
||||
LOG_INFO(TAG, "📨 WebSocket message from client #%u: cmd=%s", clientId, cmd.c_str());
|
||||
|
||||
// Create message context for WebSocket with client ID
|
||||
CommandHandler::MessageContext context(CommandHandler::MessageSource::WEBSOCKET, clientId);
|
||||
|
||||
// Forward to command handler (need to cast away const for now)
|
||||
JsonDocument& mutableDoc = const_cast<JsonDocument&>(message);
|
||||
_commandHandler.processCommand(mutableDoc, context);
|
||||
|
||||
LOG_DEBUG(TAG, "WebSocket message from client #%u processed", clientId);
|
||||
}
|
||||
|
||||
void CommunicationRouter::onUartMessage(JsonDocument& message) {
|
||||
// Extract command and action for filtering
|
||||
String cmd = message["cmd"] | "";
|
||||
String action = message["contents"]["action"] | "";
|
||||
|
||||
// UART COMMAND WHITELIST: Only allow specific commands
|
||||
// This prevents feedback loops between devices when bad messages occur.
|
||||
// To re-enable full UART command support, remove this filter.
|
||||
bool allowed = false;
|
||||
|
||||
if (cmd == "system_info" && action == "sync_time_to_lcd") {
|
||||
allowed = true;
|
||||
} else if (cmd == "playback" && (action == "play" || action == "stop")) {
|
||||
allowed = true;
|
||||
}
|
||||
|
||||
if (!allowed) {
|
||||
// Silently ignore - do NOT send error response to avoid feedback loop
|
||||
LOG_DEBUG(TAG, "UART: Ignoring non-whitelisted command (cmd=%s, action=%s)",
|
||||
cmd.c_str(), action.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
LOG_INFO(TAG, "🔌 UART command received: cmd=%s, action=%s", cmd.c_str(), action.c_str());
|
||||
|
||||
// Create message context for UART
|
||||
CommandHandler::MessageContext context(CommandHandler::MessageSource::UART);
|
||||
|
||||
// Forward to command handler
|
||||
_commandHandler.processCommand(message, context);
|
||||
|
||||
LOG_DEBUG(TAG, "UART message processed");
|
||||
}
|
||||
|
||||
void CommunicationRouter::sendResponse(const String& response, const CommandHandler::MessageContext& context) {
|
||||
if (context.source == CommandHandler::MessageSource::MQTT) {
|
||||
LOG_DEBUG(TAG, "↗️ Sending response via MQTT: %s", response.c_str());
|
||||
publishToMqtt(response);
|
||||
} else if (context.source == CommandHandler::MessageSource::WEBSOCKET) {
|
||||
LOG_DEBUG(TAG, "↗️ Sending response to WebSocket client #%u: %s", context.clientId, response.c_str());
|
||||
_wsServer.sendToClient(context.clientId, response);
|
||||
} else if (context.source == CommandHandler::MessageSource::UART) {
|
||||
LOG_DEBUG(TAG, "↗️ Sending response via UART: %s", response.c_str());
|
||||
_uartHandler.send(response);
|
||||
} else {
|
||||
LOG_ERROR(TAG, "❌ Unknown message source for response routing!");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* COMMUNICATIONROUTER.HPP - Multi-Protocol Communication Router v4.0
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 📡 THE COMMUNICATION ROUTER OF VESPER 📡
|
||||
*
|
||||
* Routes messages between protocols and command handlers:
|
||||
* • MQTTAsyncClient: AsyncMqttClient for non-blocking MQTT
|
||||
* • WebSocketServer: Multi-client WebSocket management
|
||||
* • CommandHandler: Unified command processing
|
||||
* • ResponseBuilder: Structured response generation
|
||||
*
|
||||
* 🏗️ ARCHITECTURE:
|
||||
* • Message routing between protocols and handlers
|
||||
* • MQTT on dedicated RTOS task (Core 0)
|
||||
* • Unified command processing
|
||||
* • Thread-safe message routing
|
||||
*
|
||||
* 📡 SUPPORTED PROTOCOLS:
|
||||
* • MQTT: AsyncMqttClient for reliable async connectivity
|
||||
* • WebSocket: Real-time multi-client web interface
|
||||
* • UDP Discovery: Auto-discovery service
|
||||
*
|
||||
* 📋 VERSION: 5.0 (AsyncMqttClient)
|
||||
* 📅 DATE: 2025-10-01
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <ESPAsyncWebServer.h>
|
||||
#include <AsyncUDP.h>
|
||||
#include <ArduinoJson.h>
|
||||
#include "../MQTTAsyncClient/MQTTAsyncClient.hpp"
|
||||
#include "../WebSocketServer/WebSocketServer.hpp"
|
||||
#include "../CommandHandler/CommandHandler.hpp"
|
||||
#include "../ResponseBuilder/ResponseBuilder.hpp"
|
||||
#include "../HTTPRequestHandler/HTTPRequestHandler.hpp"
|
||||
#include "../UARTCommandHandler/UARTCommandHandler.hpp"
|
||||
#include "../../ClientManager/ClientManager.hpp"
|
||||
#include "../../SettingsWebServer/SettingsWebServer.hpp"
|
||||
|
||||
class ConfigManager;
|
||||
class OTAManager;
|
||||
class Player;
|
||||
class FileManager;
|
||||
class Timekeeper;
|
||||
class Networking;
|
||||
class FirmwareValidator;
|
||||
class Telemetry;
|
||||
|
||||
class CommunicationRouter {
|
||||
public:
|
||||
explicit CommunicationRouter(ConfigManager& configManager,
|
||||
OTAManager& otaManager,
|
||||
Networking& networking,
|
||||
AsyncWebServer& server,
|
||||
AsyncWebSocket& webSocket,
|
||||
AsyncUDP& udp);
|
||||
|
||||
~CommunicationRouter();
|
||||
|
||||
void begin();
|
||||
void loop(); // Must be called from main loop for UART processing
|
||||
void setPlayerReference(Player* player);
|
||||
void setFileManagerReference(FileManager* fm);
|
||||
void setTimeKeeperReference(Timekeeper* tk);
|
||||
void setFirmwareValidatorReference(FirmwareValidator* fv);
|
||||
void setTelemetryReference(Telemetry* telemetry);
|
||||
void setupUdpDiscovery();
|
||||
|
||||
// Status methods
|
||||
bool isMqttConnected() const;
|
||||
bool hasActiveWebSocketClients() const;
|
||||
size_t getWebSocketClientCount() const;
|
||||
bool isHealthy() const;
|
||||
|
||||
// Component accessors
|
||||
MQTTAsyncClient& getMQTTClient() { return _mqttClient; }
|
||||
UARTCommandHandler& getUARTHandler() { return _uartHandler; }
|
||||
|
||||
// Broadcast methods
|
||||
void broadcastStatus(const String& statusMessage);
|
||||
void broadcastStatus(const JsonDocument& statusJson);
|
||||
void broadcastToMasterClients(const String& message);
|
||||
void broadcastToSecondaryClients(const String& message);
|
||||
void broadcastToAllWebSocketClients(const String& message);
|
||||
void broadcastToAllWebSocketClients(const JsonDocument& message);
|
||||
void publishToMqtt(const String& data);
|
||||
|
||||
// Bell overload notification
|
||||
void sendBellOverloadNotification(const std::vector<uint8_t>& bellNumbers,
|
||||
const std::vector<uint16_t>& bellLoads,
|
||||
const String& severity);
|
||||
|
||||
// Network connection callbacks
|
||||
void onNetworkConnected();
|
||||
void onNetworkDisconnected();
|
||||
|
||||
private:
|
||||
// Dependencies
|
||||
ConfigManager& _configManager;
|
||||
OTAManager& _otaManager;
|
||||
Networking& _networking;
|
||||
AsyncWebServer& _server;
|
||||
AsyncWebSocket& _webSocket;
|
||||
AsyncUDP& _udp;
|
||||
Player* _player;
|
||||
FileManager* _fileManager;
|
||||
Timekeeper* _timeKeeper;
|
||||
FirmwareValidator* _firmwareValidator;
|
||||
|
||||
// Communication subsystems
|
||||
MQTTAsyncClient _mqttClient;
|
||||
ClientManager _clientManager;
|
||||
WebSocketServer _wsServer;
|
||||
CommandHandler _commandHandler;
|
||||
HTTPRequestHandler _httpHandler;
|
||||
UARTCommandHandler _uartHandler;
|
||||
SettingsWebServer _settingsServer;
|
||||
|
||||
// Message handlers
|
||||
void onMqttMessage(const String& topic, const String& payload);
|
||||
void onWebSocketMessage(uint32_t clientId, const JsonDocument& message);
|
||||
void onUartMessage(JsonDocument& message);
|
||||
|
||||
// Response routing
|
||||
void sendResponse(const String& response, const CommandHandler::MessageContext& context);
|
||||
};
|
||||
@@ -0,0 +1,189 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* 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);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* 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);
|
||||
};
|
||||
@@ -0,0 +1,476 @@
|
||||
/*
|
||||
* MQTTASYNCCLIENT.CPP - MQTT Client Implementation with AsyncMqttClient
|
||||
*/
|
||||
|
||||
#include "MQTTAsyncClient.hpp"
|
||||
|
||||
#define TAG "MQTTClient"
|
||||
#include "../../ConfigManager/ConfigManager.hpp"
|
||||
#include "../../Networking/Networking.hpp"
|
||||
#include "../../Logging/Logging.hpp"
|
||||
|
||||
MQTTAsyncClient* MQTTAsyncClient::_instance = nullptr;
|
||||
|
||||
MQTTAsyncClient::MQTTAsyncClient(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
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
MQTTAsyncClient::~MQTTAsyncClient() {
|
||||
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 MQTTAsyncClient::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 MQTTAsyncClient::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 MQTTAsyncClient::disconnect() {
|
||||
_mqttClient.disconnect();
|
||||
LOG_INFO(TAG, "Disconnected from MQTT broker");
|
||||
}
|
||||
|
||||
uint16_t MQTTAsyncClient::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 MQTTAsyncClient::setCallback(MessageCallback callback) {
|
||||
_messageCallback = callback;
|
||||
}
|
||||
|
||||
bool MQTTAsyncClient::isConnected() const {
|
||||
return _mqttClient.connected();
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::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 MQTTAsyncClient::onNetworkDisconnected() {
|
||||
LOG_DEBUG(TAG, "Network disconnected - MQTT will auto-reconnect when network returns");
|
||||
|
||||
if (_mqttClient.connected()) {
|
||||
_mqttClient.disconnect(true);
|
||||
}
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::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 MQTTAsyncClient::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 MQTTAsyncClient::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 MQTTAsyncClient::onMqttSubscribe(uint16_t packetId, uint8_t qos) {
|
||||
LOG_INFO(TAG, "✅ Subscribed to topic (packetId=%d, QoS=%d)", packetId, qos);
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::onMqttUnsubscribe(uint16_t 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) {
|
||||
// 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 MQTTAsyncClient::onMqttPublish(uint16_t packetId) {
|
||||
LOG_DEBUG(TAG, "MQTT publish acknowledged (packetId=%d)", packetId);
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::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 MQTTAsyncClient::mqttReconnectTaskFn(void* param) {
|
||||
MQTTAsyncClient* client = static_cast<MQTTAsyncClient*>(param);
|
||||
client->attemptReconnection();
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::mqttReconnectTimerCallback(TimerHandle_t xTimer) {
|
||||
if (MQTTAsyncClient::_instance) {
|
||||
xTaskCreate(mqttReconnectTaskFn, "mqttRecon", 3072, MQTTAsyncClient::_instance, 5, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// HEARTBEAT FUNCTIONALITY
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void MQTTAsyncClient::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 MQTTAsyncClient::stopHeartbeat() {
|
||||
if (_heartbeatTimer) {
|
||||
xTimerStop(_heartbeatTimer, 0);
|
||||
_heartbeatTaskHandle = nullptr;
|
||||
LOG_INFO(TAG, "❤️ Stopped MQTT heartbeat");
|
||||
}
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::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 MQTTAsyncClient::mqttHeartbeatTaskFn(void* param) {
|
||||
MQTTAsyncClient* client = static_cast<MQTTAsyncClient*>(param);
|
||||
client->publishHeartbeat();
|
||||
client->_heartbeatTaskHandle = nullptr;
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::heartbeatTimerCallback(TimerHandle_t xTimer) {
|
||||
if (MQTTAsyncClient::_instance) {
|
||||
// Guard: skip if previous heartbeat task is still running
|
||||
if (MQTTAsyncClient::_instance->_heartbeatTaskHandle != nullptr) {
|
||||
return;
|
||||
}
|
||||
xTaskCreate(mqttHeartbeatTaskFn, "mqttHB", 3072, MQTTAsyncClient::_instance, 3,
|
||||
&MQTTAsyncClient::_instance->_heartbeatTaskHandle);
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// NETWORK STABILIZATION - NON-BLOCKING TIMER APPROACH
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
void MQTTAsyncClient::connectAfterStabilization() {
|
||||
LOG_DEBUG(TAG, "Network stabilization complete - connecting to MQTT");
|
||||
connect();
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::mqttConnectTaskFn(void* param) {
|
||||
// Runs in its own task so LOG calls don't overflow the Tmr Svc stack
|
||||
MQTTAsyncClient* client = static_cast<MQTTAsyncClient*>(param);
|
||||
client->connectAfterStabilization();
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
void MQTTAsyncClient::networkStabilizationTimerCallback(TimerHandle_t xTimer) {
|
||||
if (MQTTAsyncClient::_instance) {
|
||||
// Defer to a task — timer callbacks run in Tmr Svc (2KB stack), not enough for connect()
|
||||
xTaskCreate(mqttConnectTaskFn, "mqttConnect", 3072, MQTTAsyncClient::_instance, 5, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
// EXPONENTIAL BACKOFF CALCULATION
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
unsigned long MQTTAsyncClient::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,139 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* MQTTASYNCCLIENT.HPP - MQTT Client with AsyncMqttClient
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 🔒 MQTT CONNECTION WITH ASYNC ARCHITECTURE 🔒
|
||||
*
|
||||
* This class manages MQTT connections using AsyncMqttClient library:
|
||||
* • 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)
|
||||
* 📅 DATE: 2025-01-04
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <AsyncMqttClient.h>
|
||||
|
||||
class ConfigManager;
|
||||
class Networking;
|
||||
|
||||
class MQTTAsyncClient {
|
||||
public:
|
||||
static MQTTAsyncClient* _instance;
|
||||
|
||||
// Message callback type
|
||||
using MessageCallback = std::function<void(const String& topic, const String& payload)>;
|
||||
|
||||
explicit MQTTAsyncClient(ConfigManager& configManager, Networking& networking);
|
||||
~MQTTAsyncClient();
|
||||
|
||||
/**
|
||||
* @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,165 @@
|
||||
#include "ResponseBuilder.hpp"
|
||||
|
||||
#define TAG "ResponseBuilder"
|
||||
#include "../../Logging/Logging.hpp"
|
||||
|
||||
// Static member initialization
|
||||
StaticJsonDocument<512> ResponseBuilder::_responseDoc;
|
||||
|
||||
String ResponseBuilder::success(const String& type, const String& payload) {
|
||||
return buildResponse(Status::SUCCESS, type, payload);
|
||||
}
|
||||
|
||||
String ResponseBuilder::success(const String& type, const JsonObject& payload) {
|
||||
return buildResponse(Status::SUCCESS, type, payload);
|
||||
}
|
||||
|
||||
String ResponseBuilder::error(const String& type, const String& message) {
|
||||
return buildResponse(Status::ERROR, type, message);
|
||||
}
|
||||
|
||||
String ResponseBuilder::status(const String& type, const JsonObject& data) {
|
||||
return buildResponse(Status::SUCCESS, type, data);
|
||||
}
|
||||
|
||||
String ResponseBuilder::status(const String& type, const String& data) {
|
||||
return buildResponse(Status::SUCCESS, type, data);
|
||||
}
|
||||
|
||||
String ResponseBuilder::acknowledgment(const String& commandType) {
|
||||
return success(commandType, "Command acknowledged");
|
||||
}
|
||||
|
||||
String ResponseBuilder::pong() {
|
||||
return success("pong", "");
|
||||
}
|
||||
|
||||
String ResponseBuilder::deviceStatus(PlayerStatus playerStatus, uint32_t timeElapsed, uint64_t projectedRunTime, const uint32_t strikeCounters[16]) {
|
||||
DynamicJsonDocument statusDoc(1024); // Increased size for strikeCounters array
|
||||
|
||||
statusDoc["status"] = "SUCCESS";
|
||||
statusDoc["type"] = "current_status";
|
||||
|
||||
// Create payload object with the exact format expected by Flutter
|
||||
JsonObject payload = statusDoc.createNestedObject("payload");
|
||||
|
||||
// Convert PlayerStatus to string
|
||||
const char* statusStr;
|
||||
switch (playerStatus) {
|
||||
case PlayerStatus::PLAYING:
|
||||
statusStr = "playing";
|
||||
break;
|
||||
case PlayerStatus::PAUSED:
|
||||
statusStr = "paused";
|
||||
break;
|
||||
case PlayerStatus::STOPPING:
|
||||
statusStr = "stopping";
|
||||
break;
|
||||
case PlayerStatus::STOPPED:
|
||||
default:
|
||||
statusStr = "idle"; // STOPPED maps to "idle" in Flutter
|
||||
break;
|
||||
}
|
||||
|
||||
payload["player_status"] = statusStr;
|
||||
payload["time_elapsed"] = timeElapsed; // in milliseconds
|
||||
payload["projected_run_time"] = projectedRunTime; // NEW: total projected duration
|
||||
|
||||
// Add strike counters array
|
||||
JsonArray strikeCountersArray = payload.createNestedArray("strike_counters");
|
||||
for (uint8_t i = 0; i < 16; i++) {
|
||||
strikeCountersArray.add(strikeCounters[i]);
|
||||
}
|
||||
|
||||
String result;
|
||||
serializeJson(statusDoc, result);
|
||||
|
||||
LOG_DEBUG(TAG, "Device status response: %s", result.c_str());
|
||||
return result;
|
||||
}
|
||||
|
||||
String ResponseBuilder::melodyList(const String& fileListJson) {
|
||||
// The fileListJson is already a JSON string, so we pass it as payload
|
||||
return success("melody_list", fileListJson);
|
||||
}
|
||||
|
||||
String ResponseBuilder::downloadResult(bool success, const String& filename) {
|
||||
if (success) {
|
||||
String message = "Download successful";
|
||||
if (filename.length() > 0) {
|
||||
message += ": " + filename;
|
||||
}
|
||||
return ResponseBuilder::success("download", message);
|
||||
} else {
|
||||
String message = "Download failed";
|
||||
if (filename.length() > 0) {
|
||||
message += ": " + filename;
|
||||
}
|
||||
return error("download", message);
|
||||
}
|
||||
}
|
||||
|
||||
String ResponseBuilder::configUpdate(const String& configType) {
|
||||
return success(configType, configType + " configuration updated");
|
||||
}
|
||||
|
||||
String ResponseBuilder::invalidCommand(const String& command) {
|
||||
return error("invalid_command", "Unknown command: " + command);
|
||||
}
|
||||
|
||||
String ResponseBuilder::missingParameter(const String& parameter) {
|
||||
return error("missing_parameter", "Required parameter missing: " + parameter);
|
||||
}
|
||||
|
||||
String ResponseBuilder::operationFailed(const String& operation, const String& reason) {
|
||||
String message = operation + " failed";
|
||||
if (reason.length() > 0) {
|
||||
message += ": " + reason;
|
||||
}
|
||||
return error(operation, message);
|
||||
}
|
||||
|
||||
String ResponseBuilder::deviceBusy() {
|
||||
return error("device_busy", "Device is currently busy, try again later");
|
||||
}
|
||||
|
||||
String ResponseBuilder::unauthorized() {
|
||||
return error("unauthorized", "Operation not authorized for this client");
|
||||
}
|
||||
|
||||
// Response Builder with String Payload
|
||||
String ResponseBuilder::buildResponse(Status status, const String& type, const String& payload) {
|
||||
_responseDoc.clear();
|
||||
_responseDoc["status"] = statusToString(status);
|
||||
_responseDoc["type"] = type;
|
||||
_responseDoc["payload"] = payload;
|
||||
|
||||
String result;
|
||||
serializeJson(_responseDoc, result);
|
||||
|
||||
LOG_DEBUG(TAG, "Response built: %s", result.c_str());
|
||||
return result;
|
||||
}
|
||||
|
||||
// Response Builder with JSON Payload
|
||||
String ResponseBuilder::buildResponse(Status status, const String& type, const JsonObject& payload) {
|
||||
_responseDoc.clear();
|
||||
_responseDoc["status"] = statusToString(status);
|
||||
_responseDoc["type"] = type;
|
||||
_responseDoc["payload"] = payload;
|
||||
|
||||
String result;
|
||||
serializeJson(_responseDoc, result);
|
||||
|
||||
LOG_DEBUG(TAG, "Response built: %s", result.c_str());
|
||||
return result;
|
||||
}
|
||||
|
||||
const char* ResponseBuilder::statusToString(Status status) {
|
||||
switch (status) {
|
||||
case Status::SUCCESS: return "SUCCESS";
|
||||
case Status::ERROR: return "ERROR";
|
||||
case Status::INFO: return "INFO";
|
||||
default: return "UNKNOWN";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* RESPONSEBUILDER.HPP - Unified Response Generation System
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 📡 STANDARDIZED COMMUNICATION RESPONSES 📡
|
||||
*
|
||||
* This class provides a unified interface for generating consistent JSON responses
|
||||
* across all communication protocols (MQTT, WebSocket). It ensures all responses
|
||||
* follow the same format and structure.
|
||||
*
|
||||
* 🏗️ ARCHITECTURE:
|
||||
* • Static methods for response generation
|
||||
* • Consistent JSON structure across all protocols
|
||||
* • Memory-efficient response building
|
||||
* • Type-safe response categories
|
||||
*
|
||||
* 📡 RESPONSE TYPES:
|
||||
* • Success: Successful command execution
|
||||
* • Error: Command execution failures
|
||||
* • Status: System status reports and updates
|
||||
* • Data: Information requests and telemetry
|
||||
*
|
||||
* 🔄 RESPONSE STRUCTURE:
|
||||
* {
|
||||
* "status": "OK|ERROR",
|
||||
* "type": "command_type",
|
||||
* "payload": "data_or_message"
|
||||
* }
|
||||
*
|
||||
* 📋 USAGE EXAMPLES:
|
||||
* • ResponseBuilder::success("playback", "Started playing melody")
|
||||
* • ResponseBuilder::error("download", "File not found")
|
||||
* • ResponseBuilder::status("telemetry", telemetryData)
|
||||
*
|
||||
* 📋 VERSION: 1.0 (Initial unified response system)
|
||||
* 📅 DATE: 2025
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <ArduinoJson.h>
|
||||
#include "../../Player/Player.hpp" // For PlayerStatus enum
|
||||
|
||||
class ResponseBuilder {
|
||||
public:
|
||||
// Response status types
|
||||
enum class Status {
|
||||
SUCCESS,
|
||||
ERROR,
|
||||
INFO
|
||||
};
|
||||
|
||||
// Main response builders
|
||||
static String success(const String& type, const String& payload = "");
|
||||
static String success(const String& type, const JsonObject& payload);
|
||||
static String error(const String& type, const String& message);
|
||||
static String status(const String& type, const JsonObject& data);
|
||||
static String status(const String& type, const String& data);
|
||||
|
||||
// Specialized response builders for common scenarios
|
||||
static String acknowledgment(const String& commandType);
|
||||
static String pong();
|
||||
static String deviceStatus(PlayerStatus playerStatus, uint32_t timeElapsedMs, uint64_t projectedRunTime, const uint32_t strikeCounters[16]);
|
||||
static String melodyList(const String& fileListJson);
|
||||
static String downloadResult(bool success, const String& filename = "");
|
||||
static String configUpdate(const String& configType);
|
||||
|
||||
// Error response builders
|
||||
static String invalidCommand(const String& command);
|
||||
static String missingParameter(const String& parameter);
|
||||
static String operationFailed(const String& operation, const String& reason = "");
|
||||
static String deviceBusy();
|
||||
static String unauthorized();
|
||||
|
||||
// Utility methods
|
||||
static String buildResponse(Status status, const String& type, const String& payload);
|
||||
static String buildResponse(Status status, const String& type, const JsonObject& payload);
|
||||
|
||||
private:
|
||||
// Internal helper methods
|
||||
static const char* statusToString(Status status);
|
||||
static StaticJsonDocument<512> _responseDoc; // Reusable document for efficiency
|
||||
};
|
||||
@@ -0,0 +1,133 @@
|
||||
/*
|
||||
* UARTCOMMANDHANDLER.CPP - UART Command Handler Implementation
|
||||
*/
|
||||
|
||||
#include "UARTCommandHandler.hpp"
|
||||
|
||||
#define TAG "UARTHandler"
|
||||
#include "../../Logging/Logging.hpp"
|
||||
|
||||
UARTCommandHandler::UARTCommandHandler(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();
|
||||
}
|
||||
|
||||
UARTCommandHandler::~UARTCommandHandler() {
|
||||
_serial.end();
|
||||
}
|
||||
|
||||
void UARTCommandHandler::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 UARTCommandHandler::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 UARTCommandHandler::setCallback(MessageCallback callback) {
|
||||
_callback = callback;
|
||||
}
|
||||
|
||||
void UARTCommandHandler::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 UARTCommandHandler::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 UARTCommandHandler::resetBuffer() {
|
||||
_bufferIndex = 0;
|
||||
memset(_buffer, 0, BUFFER_SIZE);
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* UARTCOMMANDHANDLER.HPP - UART Command Interface for External Control Devices
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 🔌 UART COMMAND HANDLER 🔌
|
||||
*
|
||||
* Enables command input from external devices (LCD panels, button controllers)
|
||||
* 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
|
||||
* 📅 DATE: 2025-01-19
|
||||
* 👨💻 AUTHOR: Advanced Bell Systems
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <ArduinoJson.h>
|
||||
#include <functional>
|
||||
|
||||
class UARTCommandHandler {
|
||||
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 UARTCommandHandler(uint8_t txPin = DEFAULT_TX_PIN,
|
||||
uint8_t rxPin = DEFAULT_RX_PIN,
|
||||
uint32_t baudRate = DEFAULT_BAUD_RATE);
|
||||
|
||||
~UARTCommandHandler();
|
||||
|
||||
/**
|
||||
* @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 @@
|
||||
/*
|
||||
* WEBSOCKETSERVER.CPP - WebSocket Server Implementation
|
||||
*/
|
||||
|
||||
#include "WebSocketServer.hpp"
|
||||
|
||||
#define TAG "WebSocket"
|
||||
#include "../../Logging/Logging.hpp"
|
||||
#include "../ResponseBuilder/ResponseBuilder.hpp"
|
||||
|
||||
// Static instance for callback
|
||||
WebSocketServer* WebSocketServer::_instance = nullptr;
|
||||
|
||||
WebSocketServer::WebSocketServer(AsyncWebSocket& webSocket, ClientManager& clientManager)
|
||||
: _webSocket(webSocket)
|
||||
, _clientManager(clientManager)
|
||||
, _messageCallback(nullptr) {
|
||||
|
||||
_instance = this;
|
||||
}
|
||||
|
||||
WebSocketServer::~WebSocketServer() {
|
||||
_instance = nullptr;
|
||||
}
|
||||
|
||||
void WebSocketServer::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 WebSocketServer::setCallback(MessageCallback callback) {
|
||||
_messageCallback = callback;
|
||||
}
|
||||
|
||||
void WebSocketServer::sendToClient(uint32_t clientId, const String& message) {
|
||||
_clientManager.sendToClient(clientId, message);
|
||||
}
|
||||
|
||||
void WebSocketServer::broadcastToAll(const String& message) {
|
||||
_clientManager.broadcastToAll(message);
|
||||
LOG_DEBUG(TAG, "Broadcast to all WebSocket clients: %s", message.c_str());
|
||||
}
|
||||
|
||||
void WebSocketServer::broadcastToMaster(const String& message) {
|
||||
_clientManager.sendToMasterClients(message);
|
||||
LOG_DEBUG(TAG, "Broadcast to master clients: %s", message.c_str());
|
||||
}
|
||||
|
||||
void WebSocketServer::broadcastToSecondary(const String& message) {
|
||||
_clientManager.sendToSecondaryClients(message);
|
||||
LOG_DEBUG(TAG, "Broadcast to secondary clients: %s", message.c_str());
|
||||
}
|
||||
|
||||
bool WebSocketServer::hasClients() const {
|
||||
return _clientManager.hasClients();
|
||||
}
|
||||
|
||||
size_t WebSocketServer::getClientCount() const {
|
||||
return _clientManager.getClientCount();
|
||||
}
|
||||
|
||||
void WebSocketServer::onEvent(AsyncWebSocket* server, AsyncWebSocketClient* client,
|
||||
AwsEventType type, void* arg, uint8_t* data, size_t len) {
|
||||
if (!_instance) {
|
||||
LOG_ERROR(TAG, "WebSocketServer 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 WebSocketServer::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 WebSocketServer::onDisconnect(AsyncWebSocketClient* client) {
|
||||
LOG_INFO(TAG, "WebSocket client #%u disconnected", client->id());
|
||||
|
||||
_clientManager.removeClient(client->id());
|
||||
_clientManager.cleanupDisconnectedClients();
|
||||
}
|
||||
|
||||
void WebSocketServer::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,103 @@
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
* WEBSOCKETSERVER.HPP - WebSocket Server Manager
|
||||
* ═══════════════════════════════════════════════════════════════════════════════════
|
||||
*
|
||||
* 📡 WEBSOCKET MULTI-CLIENT MANAGER 📡
|
||||
*
|
||||
* Handles WebSocket connections with:
|
||||
* • Multi-client support with device type identification
|
||||
* • Automatic client cleanup
|
||||
* • Broadcast and targeted messaging
|
||||
* • Integration with ClientManager
|
||||
*
|
||||
* 📋 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 WebSocketServer {
|
||||
public:
|
||||
// Message callback type
|
||||
using MessageCallback = std::function<void(uint32_t clientId, const JsonDocument& message)>;
|
||||
|
||||
explicit WebSocketServer(AsyncWebSocket& webSocket, ClientManager& clientManager);
|
||||
~WebSocketServer();
|
||||
|
||||
/**
|
||||
* @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 WebSocketServer* _instance;
|
||||
};
|
||||
Reference in New Issue
Block a user