diff --git a/platformio.ini b/platformio.ini index 38cd854..3938d75 100644 --- a/platformio.ini +++ b/platformio.ini @@ -47,6 +47,7 @@ lib_deps = https://github.com/marvinroger/async-mqtt-client.git build_flags_common = + -std=gnu++14 -DCORE_DEBUG_LEVEL=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 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 ; do LOG formatting, MQTT connect(), NTP sync, etc. Increase to 4096. board_build.cmake_extra_args = -DCONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=4096 diff --git a/src/Communication/CommandHandler/CommandHandler.cpp b/src/Communication/CommandHandler/CommandHandler.cpp deleted file mode 100644 index 73deee8..0000000 --- a/src/Communication/CommandHandler/CommandHandler.cpp +++ /dev/null @@ -1,1328 +0,0 @@ -/* - * COMMANDHANDLER.CPP - Command Processing Implementation - */ - -#include "CommandHandler.hpp" - -#define TAG "CommandHandler" -#include "../../ConfigManager/ConfigManager.hpp" -#include "../../OTAManager/OTAManager.hpp" -#include "../../Player/Player.hpp" -#include "../../FileManager/FileManager.hpp" -#include "../../TimeKeeper/TimeKeeper.hpp" -#include "../../FirmwareValidator/FirmwareValidator.hpp" -#include "../../ClientManager/ClientManager.hpp" -#include "../../Telemetry/Telemetry.hpp" -#include "../../Logging/Logging.hpp" -#include "../ResponseBuilder/ResponseBuilder.hpp" -#include "../CommunicationRouter/CommunicationRouter.hpp" - -CommandHandler::CommandHandler(ConfigManager& configManager, OTAManager& otaManager) - : _configManager(configManager) - , _otaManager(otaManager) - , _player(nullptr) - , _fileManager(nullptr) - , _timeKeeper(nullptr) - , _firmwareValidator(nullptr) - , _clientManager(nullptr) - , _telemetry(nullptr) - , _communicationRouter(nullptr) - , _responseCallback(nullptr) {} - -CommandHandler::~CommandHandler() {} - -void CommandHandler::setPlayerReference(Player* player) { - _player = player; -} - -void CommandHandler::setFileManagerReference(FileManager* fm) { - _fileManager = fm; -} - -void CommandHandler::setTimeKeeperReference(Timekeeper* tk) { - _timeKeeper = tk; -} - -void CommandHandler::setFirmwareValidatorReference(FirmwareValidator* fv) { - _firmwareValidator = fv; -} - -void CommandHandler::setClientManagerReference(ClientManager* cm) { - _clientManager = cm; -} - -void CommandHandler::setTelemetryReference(Telemetry* telemetry) { - _telemetry = telemetry; -} - -void CommandHandler::setCommunicationRouterReference(CommunicationRouter* comm) { - _communicationRouter = comm; -} - -void CommandHandler::setResponseCallback(ResponseCallback callback) { - _responseCallback = callback; -} - -void CommandHandler::processCommand(JsonDocument& command, const MessageContext& context) { - String cmd = command["cmd"]; - JsonVariant contents = command["contents"]; - - LOG_DEBUG(TAG, "Processing command: %s from %s", cmd.c_str(), - context.source == MessageSource::MQTT ? "MQTT" : "WebSocket"); - - if (cmd == "ping") { - handlePingCommand(context); - } else if (cmd == "identify") { - handleIdentifyCommand(contents, context); - } else if (cmd == "playback") { - handlePlaybackCommand(contents, context); - } else if (cmd == "file_manager") { - handleFileManagerCommand(contents, context); - } else if (cmd == "relay_setup") { - handleRelaySetupCommand(contents, context); - } else if (cmd == "clock_setup") { - handleClockSetupCommand(contents, context); - } else if (cmd == "system_info") { - handleSystemInfoCommand(contents, context); - } else if (cmd == "system") { - handleSystemCommand(contents, context); - } else { - LOG_WARNING(TAG, "Unknown command received: %s", cmd.c_str()); - sendErrorResponse("unknown_command", "Command not recognized: " + cmd, context); - } -} - -void CommandHandler::sendResponse(const String& response, const MessageContext& context) { - if (_responseCallback) { - _responseCallback(response, context); - } -} - -void CommandHandler::sendSuccessResponse(const String& type, const String& payload, const MessageContext& context) { - String response = ResponseBuilder::success(type, payload); - sendResponse(response, context); -} - -void CommandHandler::sendErrorResponse(const String& type, const String& message, const MessageContext& context) { - String response = ResponseBuilder::error(type, message); - sendResponse(response, context); -} - -void CommandHandler::handlePingCommand(const MessageContext& context) { - String response = ResponseBuilder::pong(); - sendResponse(response, context); -} - -void CommandHandler::handleStatusCommand(const MessageContext& context) { - PlayerStatus playerStatus = _player ? _player->getStatus() : PlayerStatus::STOPPED; - uint32_t timeElapsedMs = 0; - uint64_t projectedRunTime = 0; - - if (_player) { - if (_player->getStatus() == PlayerStatus::PLAYING || - _player->getStatus() == PlayerStatus::PAUSED || - _player->getStatus() == PlayerStatus::STOPPING) { - timeElapsedMs = millis() - _player->startTime; - } - - projectedRunTime = _player->calculateProjectedRunTime(); - } - - // Collect strike counters from Telemetry - uint32_t strikeCounters[16] = {0}; - if (_telemetry) { - for (uint8_t i = 0; i < 16; i++) { - strikeCounters[i] = _telemetry->getStrikeCount(i); - } - } - - String response = ResponseBuilder::deviceStatus(playerStatus, timeElapsedMs, projectedRunTime, strikeCounters); - sendResponse(response, context); -} - -void CommandHandler::handleIdentifyCommand(JsonVariant contents, const MessageContext& context) { - if (context.source != MessageSource::WEBSOCKET) { - sendErrorResponse("identify", "Identify command only available via WebSocket", context); - return; - } - - // 🛡️ SAFETY CHECK: Ensure ClientManager reference is set - if (!_clientManager) { - LOG_ERROR(TAG, "ClientManager reference not set in CommandHandler!"); - sendErrorResponse("identify", "Internal error: ClientManager not available", context); - return; - } - - if (!contents.containsKey("device_type")) { - sendErrorResponse("identify", "Missing device_type parameter", context); - return; - } - - String deviceTypeStr = contents["device_type"]; - ClientManager::DeviceType deviceType = ClientManager::DeviceType::UNKNOWN; - - if (deviceTypeStr == "master") { - deviceType = ClientManager::DeviceType::MASTER; - } else if (deviceTypeStr == "secondary") { - deviceType = ClientManager::DeviceType::SECONDARY; - } - - if (deviceType != ClientManager::DeviceType::UNKNOWN) { - _clientManager->updateClientType(context.clientId, deviceType); - sendSuccessResponse("identify", "Device identified as " + deviceTypeStr, context); - LOG_INFO(TAG, "Client #%u identified as %s device", context.clientId, deviceTypeStr.c_str()); - } else { - sendErrorResponse("identify", "Invalid device_type. Use 'master' or 'secondary'", context); - } -} - -void CommandHandler::handlePlaybackCommand(JsonVariant contents, const MessageContext& context) { - if (_player) { - bool success = _player->command(contents); - - if (success) { - sendSuccessResponse("playback", "Playback command executed", context); - } else { - sendErrorResponse("playback", "Playback command failed", context); - } - } else { - LOG_ERROR(TAG, "Player reference not set"); - sendErrorResponse("playback", "Player not available", context); - } -} - -void CommandHandler::handleFileManagerCommand(JsonVariant contents, const MessageContext& context) { - if (!contents.containsKey("action")) { - sendErrorResponse("file_manager", "Missing action parameter", context); - return; - } - - String action = contents["action"]; - LOG_DEBUG(TAG, "Processing file manager action: %s", action.c_str()); - - if (action == "list_melodies") { - handleListMelodiesCommand(context); - } else if (action == "download_melody") { - handleDownloadMelodyCommand(contents, context); - } else if (action == "delete_melody") { - handleDeleteMelodyCommand(contents, context); - } else { - LOG_WARNING(TAG, "Unknown file manager action: %s", action.c_str()); - sendErrorResponse("file_manager", "Unknown action: " + action, context); - } -} - -void CommandHandler::handleRelaySetupCommand(JsonVariant contents, const MessageContext& context) { - if (!contents.containsKey("action")) { - sendErrorResponse("relay_setup", "Missing action parameter", context); - return; - } - - String action = contents["action"]; - LOG_DEBUG(TAG, "Processing relay setup action: %s", action.c_str()); - - if (action == "set_timings") { - handleSetRelayTimersCommand(contents, context); - } else if (action == "set_outputs") { - handleSetRelayOutputsCommand(contents, context); - } else { - LOG_WARNING(TAG, "Unknown relay setup action: %s", action.c_str()); - sendErrorResponse("relay_setup", "Unknown action: " + action, context); - } -} - -void CommandHandler::handleClockSetupCommand(JsonVariant contents, const MessageContext& context) { - if (!contents.containsKey("action")) { - sendErrorResponse("clock_setup", "Missing action parameter", context); - return; - } - - String action = contents["action"]; - LOG_DEBUG(TAG, "Processing clock setup action: %s", action.c_str()); - - if (action == "set_outputs") { - handleSetClockOutputsCommand(contents, context); - } else if (action == "set_timings") { - handleSetClockTimingsCommand(contents, context); - } else if (action == "set_alerts") { - handleSetClockAlertsCommand(contents, context); - } else if (action == "set_backlight") { - handleSetClockBacklightCommand(contents, context); - } else if (action == "set_silence") { - handleSetClockSilenceCommand(contents, context); - } else if (action == "set_rtc_time") { - handleSetRtcTimeCommand(contents, context); - } else if (action == "set_physical_clock_time") { - handleSetPhysicalClockTimeCommand(contents, context); - } else if (action == "pause_clock_updates" || action == "resume_clock_updates") { - handlePauseClockUpdatesCommand(contents, context); - } else if (action == "set_enabled") { - handleSetClockEnabledCommand(contents, context); - } else { - LOG_WARNING(TAG, "Unknown clock setup action: %s", action.c_str()); - sendErrorResponse("clock_setup", "Unknown action: " + action, context); - } -} - -void CommandHandler::handleSystemInfoCommand(JsonVariant contents, const MessageContext& context) { - if (!contents.containsKey("action")) { - sendErrorResponse("system_info", "Missing action parameter", context); - return; - } - - String action = contents["action"]; - LOG_DEBUG(TAG, "Processing system info action: %s", action.c_str()); - - if (action == "report_status") { - handleStatusCommand(context); - } else if (action == "get_device_time") { - handleGetDeviceTimeCommand(context); - } else if (action == "get_clock_time") { - handleGetClockTimeCommand(context); - } else if (action == "get_firmware_status") { - handleGetFirmwareStatusCommand(context); - } else if (action == "network_info") { - handleNetworkInfoCommand(context); - } else if (action == "get_full_settings") { - handleGetFullSettingsCommand(context); - } else if (action == "sync_time_to_lcd") { - handleSyncTimeToLcdCommand(context); - } else { - LOG_WARNING(TAG, "Unknown system info action: %s", action.c_str()); - sendErrorResponse("system_info", "Unknown action: " + action, context); - } -} - -void CommandHandler::handleListMelodiesCommand(const MessageContext& context) { - if (!_fileManager) { - sendErrorResponse("list_melodies", "FileManager not available", context); - return; - } - - String fileListJson = _fileManager->listFilesAsJson("/melodies"); - - StaticJsonDocument<1024> doc; - DeserializationError error = deserializeJson(doc, fileListJson); - - if (error) { - LOG_ERROR(TAG, "Failed to parse file list JSON: %s", error.c_str()); - sendErrorResponse("list_melodies", "Failed to parse file list", context); - return; - } - - StaticJsonDocument<1024> response; - response["status"] = "SUCCESS"; - response["type"] = "list_melodies"; - response["payload"] = doc["files"]; - - String responseStr; - serializeJson(response, responseStr); - sendResponse(responseStr, context); -} - -void CommandHandler::handleDownloadMelodyCommand(JsonVariant contents, const MessageContext& context) { - if (!_fileManager) { - sendErrorResponse("download_melody", "FileManager not available", context); - return; - } - - bool success = _fileManager->addMelody(contents); - String filename = contents.containsKey("name") ? contents["name"].as() : - contents.containsKey("melodys_uid") ? contents["melodys_uid"].as() : "unknown"; - - String response = ResponseBuilder::downloadResult(success, filename); - sendResponse(response, context); -} - -void CommandHandler::handleDeleteMelodyCommand(JsonVariant contents, const MessageContext& context) { - if (!_fileManager) { - sendErrorResponse("delete_melody", "FileManager not available", context); - return; - } - - if (!contents.containsKey("name")) { - sendErrorResponse("delete_melody", "Missing name parameter", context); - return; - } - - String melodyName = contents["name"]; - String filepath = "/melodies/" + melodyName; - - bool success = _fileManager->deleteFile(filepath); - - if (success) { - sendSuccessResponse("delete_melody", "Melody deleted: " + melodyName, context); - } else { - sendErrorResponse("delete_melody", "Failed to delete melody: " + melodyName, context); - } -} - -void CommandHandler::handleSetRelayTimersCommand(JsonVariant contents, const MessageContext& context) { - try { - _configManager.updateBellDurations(contents); - // Save configuration to ensure persistence - bool saved = _configManager.saveBellDurations(); - if (saved) { - sendSuccessResponse("set_relay_timers", "Relay timers updated and saved", context); - LOG_INFO(TAG, "Relay timers updated and saved successfully"); - } else { - sendErrorResponse("set_relay_timers", "Failed to save relay timers to SD card", context); - LOG_ERROR(TAG, "Failed to save relay timers configuration"); - } - } catch (...) { - sendErrorResponse("set_relay_timers", "Failed to update relay timers", context); - LOG_ERROR(TAG, "Exception occurred while updating relay timers"); - } -} - -void CommandHandler::handleSetRelayOutputsCommand(JsonVariant contents, const MessageContext& context) { - try { - _configManager.updateBellOutputs(contents); - // Save bell outputs configuration to SD card for persistence - bool saved = _configManager.saveBellOutputs(); - if (saved) { - sendSuccessResponse("set_relay_outputs", "Relay outputs updated and saved", context); - LOG_INFO(TAG, "Relay outputs updated and saved successfully"); - } else { - sendErrorResponse("set_relay_outputs", "Failed to save relay outputs to SD card", context); - LOG_ERROR(TAG, "Failed to save relay outputs configuration"); - } - } catch (...) { - sendErrorResponse("set_relay_outputs", "Failed to update relay outputs", context); - LOG_ERROR(TAG, "Exception occurred while updating relay outputs"); - } -} - -void CommandHandler::handleSetClockOutputsCommand(JsonVariant contents, const MessageContext& context) { - try { - _configManager.updateClockOutputs(contents); - // Save configuration to ensure persistence - bool saved = _configManager.saveClockConfig(); - if (saved) { - sendSuccessResponse("set_clock_outputs", "Clock outputs updated and saved", context); - LOG_INFO(TAG, "Clock outputs updated and saved successfully"); - } else { - sendErrorResponse("set_clock_outputs", "Failed to save clock outputs to SD card", context); - LOG_ERROR(TAG, "Failed to save clock outputs configuration"); - } - } catch (...) { - sendErrorResponse("set_clock_outputs", "Failed to update clock outputs", context); - LOG_ERROR(TAG, "Exception occurred while updating clock outputs"); - } -} - -void CommandHandler::handleSetClockTimingsCommand(JsonVariant contents, const MessageContext& context) { - try { - _configManager.updateClockOutputs(contents); - // Save configuration to ensure persistence - bool saved = _configManager.saveClockConfig(); - if (saved) { - sendSuccessResponse("set_clock_timings", "Clock timings updated and saved", context); - LOG_INFO(TAG, "Clock timings updated and saved successfully"); - } else { - sendErrorResponse("set_clock_timings", "Failed to save clock timings to SD card", context); - LOG_ERROR(TAG, "Failed to save clock timings configuration"); - } - } catch (...) { - sendErrorResponse("set_clock_timings", "Failed to update clock timings", context); - LOG_ERROR(TAG, "Exception occurred while updating clock timings"); - } -} - -void CommandHandler::handleSetClockAlertsCommand(JsonVariant contents, const MessageContext& context) { - try { - _configManager.updateClockAlerts(contents); - // Save configuration to ensure persistence - bool saved = _configManager.saveClockConfig(); - if (saved) { - sendSuccessResponse("set_clock_alerts", "Clock alerts updated and saved", context); - LOG_INFO(TAG, "Clock alerts updated and saved successfully"); - } else { - sendErrorResponse("set_clock_alerts", "Failed to save clock alerts to SD card", context); - LOG_ERROR(TAG, "Failed to save clock alerts configuration"); - } - } catch (...) { - sendErrorResponse("set_clock_alerts", "Failed to update clock alerts", context); - LOG_ERROR(TAG, "Exception occurred while updating clock alerts"); - } -} - -void CommandHandler::handleSetClockBacklightCommand(JsonVariant contents, const MessageContext& context) { - try { - _configManager.updateClockBacklight(contents); - // Save configuration to ensure persistence - bool saved = _configManager.saveClockConfig(); - if (saved) { - sendSuccessResponse("set_clock_backlight", "Clock backlight updated and saved", context); - LOG_INFO(TAG, "Clock backlight updated and saved successfully"); - } else { - sendErrorResponse("set_clock_backlight", "Failed to save clock backlight to SD card", context); - LOG_ERROR(TAG, "Failed to save clock backlight configuration"); - } - } catch (...) { - sendErrorResponse("set_clock_backlight", "Failed to update clock backlight", context); - LOG_ERROR(TAG, "Exception occurred while updating clock backlight"); - } -} - -void CommandHandler::handleSetClockSilenceCommand(JsonVariant contents, const MessageContext& context) { - try { - _configManager.updateClockSilence(contents); - // Save configuration to ensure persistence - bool saved = _configManager.saveClockConfig(); - if (saved) { - sendSuccessResponse("set_clock_silence", "Clock silence periods updated and saved", context); - LOG_INFO(TAG, "Clock silence periods updated and saved successfully"); - } else { - sendErrorResponse("set_clock_silence", "Failed to save clock silence configuration to SD card", context); - LOG_ERROR(TAG, "Failed to save clock silence configuration"); - } - } catch (...) { - sendErrorResponse("set_clock_silence", "Failed to update clock silence periods", context); - LOG_ERROR(TAG, "Exception occurred while updating clock silence periods"); - } -} - -void CommandHandler::handleSetRtcTimeCommand(JsonVariant contents, const MessageContext& context) { - if (!_timeKeeper) { - sendErrorResponse("set_rtc_time", "TimeKeeper not available", context); - return; - } - - if (!contents.containsKey("timestamp")) { - sendErrorResponse("set_rtc_time", "Missing timestamp parameter", context); - return; - } - - unsigned long timestamp = contents["timestamp"]; - if (timestamp == 0) { - sendErrorResponse("set_rtc_time", "Invalid timestamp value", context); - return; - } - - // Handle timezone parameters (optional for backward compatibility) - if (contents.containsKey("timezone_offset") && contents.containsKey("dst_offset")) { - // New method: App sends timezone info - long timezoneOffset = contents["timezone_offset"]; - long dstOffset = contents["dst_offset"]; - String timezoneName = contents["timezone_name"] | "UTC"; - - // Update ConfigManager with new timezone settings - auto& timeConfig = _configManager.getTimeConfig(); - - // Calculate base GMT offset (without DST) - long baseGmtOffset = timezoneOffset - dstOffset; - - // Update timezone configuration - _configManager.updateTimeConfig(baseGmtOffset, dstOffset); - - LOG_INFO(TAG, "Timezone updated: %s (GMT%+ld, DST%+ld)", - timezoneName.c_str(), baseGmtOffset/3600, dstOffset/3600); - - // Apply total offset to timestamp - long totalOffset = timezoneOffset; // App already calculated total - unsigned long localTimestamp = timestamp + totalOffset; - - // Set the RTC time using TimeKeeper with local timestamp - _timeKeeper->setTimeWithLocalTimestamp(localTimestamp); - - // Verify the time was set correctly by reading it back - unsigned long verifyTime = _timeKeeper->getTime(); - if (verifyTime > 0 && abs((long)verifyTime - (long)localTimestamp) < 5) { // Allow 5 second tolerance - sendSuccessResponse("set_rtc_time", - "RTC time and timezone updated successfully", context); - LOG_INFO(TAG, "RTC time set with timezone: UTC %lu + %ld = local %lu", - timestamp, totalOffset, localTimestamp); - } else { - sendErrorResponse("set_rtc_time", "Failed to verify RTC time was set correctly", context); - LOG_ERROR(TAG, "RTC time verification failed - expected: %lu, got: %lu", localTimestamp, verifyTime); - } - } else { - // Legacy method: Use device's existing timezone config - _timeKeeper->setTime(timestamp); - - // Verify the time was set correctly by reading it back - unsigned long verifyTime = _timeKeeper->getTime(); - if (verifyTime > 0 && abs((long)verifyTime - (long)timestamp) < 5) { // Allow 5 second tolerance - sendSuccessResponse("set_rtc_time", "RTC time updated successfully", context); - LOG_INFO(TAG, "RTC time set using device timezone config: %lu", timestamp); - } else { - sendErrorResponse("set_rtc_time", "Failed to verify RTC time was set correctly", context); - LOG_ERROR(TAG, "RTC time verification failed - expected: %lu, got: %lu", timestamp, verifyTime); - } - } -} - -void CommandHandler::handleSetPhysicalClockTimeCommand(JsonVariant contents, const MessageContext& context) { - if (!contents.containsKey("hour") || !contents.containsKey("minute")) { - sendErrorResponse("set_physical_clock_time", "Missing hour or minute parameter", context); - return; - } - - int hour = contents["hour"]; - int minute = contents["minute"]; - - // Validate time parameters - if (hour < 0 || hour > 23) { - sendErrorResponse("set_physical_clock_time", "Hour must be between 0 and 23", context); - return; - } - - if (minute < 0 || minute > 59) { - sendErrorResponse("set_physical_clock_time", "Minute must be between 0 and 59", context); - return; - } - - // Convert 24-hour to 12-hour format for analog clock - int clockHour = hour % 12; - if (clockHour == 0) clockHour = 12; // Midnight/Noon = 12, not 0 - - // Set the physical clock time using ConfigManager - _configManager.setPhysicalClockHour(clockHour); - _configManager.setPhysicalClockMinute(minute); - _configManager.setLastSyncTime(millis() / 1000); - - // Save the updated clock state to SD card - bool saved = _configManager.saveClockState(); - - if (saved) { - sendSuccessResponse("set_physical_clock_time", "Physical clock time updated and saved successfully", context); - LOG_INFO(TAG, "Physical clock time set to %02d:%02d (12h: %02d:%02d) and saved to SD", - hour, minute, clockHour, minute); - } else { - sendErrorResponse("set_physical_clock_time", "Physical clock time updated but failed to save to SD card", context); - LOG_ERROR(TAG, "Physical clock time set to %02d:%02d but failed to save to SD", hour, minute); - } -} - -void CommandHandler::handlePauseClockUpdatesCommand(JsonVariant contents, const MessageContext& context) { - if (!_timeKeeper) { - return; - } - - if (contents["action"] == "pause_clock_updates") { - _timeKeeper->pauseClockUpdates(); - sendSuccessResponse("pause_clock_updates", "Clock updates paused", context); - LOG_DEBUG(TAG, "Clock updates paused"); - return; - } else if (contents["action"] == "resume_clock_updates") { - _timeKeeper->resumeClockUpdates(); - sendSuccessResponse("resume_clock_updates", "Clock updates resumed", context); - LOG_DEBUG(TAG, "Clock updates resumed"); - return; - } -} - -void CommandHandler::handleSetClockEnabledCommand(JsonVariant contents, const MessageContext& context) { - if (!contents.containsKey("enabled")) { - sendErrorResponse("set_clock_enabled", "Missing enabled parameter", context); - return; - } - - bool enabled = contents["enabled"].as(); - - try { - _configManager.setClockEnabled(enabled); - bool saved = _configManager.saveClockConfig(); - - if (saved) { - String status = enabled ? "enabled" : "disabled"; - sendSuccessResponse("set_clock_enabled", "Clock " + status + " and saved successfully", context); - LOG_INFO(TAG, "Clock %s via remote command", status.c_str()); - } else { - sendErrorResponse("set_clock_enabled", "Clock setting updated but failed to save to SD card", context); - LOG_ERROR(TAG, "Failed to save clock enabled setting to SD card"); - } - } catch (...) { - sendErrorResponse("set_clock_enabled", "Failed to update clock enabled setting", context); - LOG_ERROR(TAG, "Exception occurred while updating clock enabled setting"); - } -} - -void CommandHandler::handleGetDeviceTimeCommand(const MessageContext& context) { - StaticJsonDocument<384> response; - response["status"] = "SUCCESS"; - response["type"] = "device_time"; - - if (_timeKeeper) { - // RTC stores LOCAL time (already timezone-adjusted) - unsigned long localTimestamp = _timeKeeper->getTime(); - - // Get timezone offset to calculate UTC - const auto& timeConfig = _configManager.getTimeConfig(); - long totalOffset = timeConfig.gmtOffsetSec + timeConfig.daylightOffsetSec; - unsigned long utcTimestamp = localTimestamp - totalOffset; - - response["payload"]["local_timestamp"] = localTimestamp; - response["payload"]["utc_timestamp"] = utcTimestamp; - response["payload"]["rtc_available"] = true; - - // Convert LOCAL timestamp to readable format using gmtime (no additional offset) - time_t rawTime = (time_t)localTimestamp; - struct tm* timeInfo = gmtime(&rawTime); // Use gmtime to avoid double-offset - response["payload"]["year"] = timeInfo->tm_year + 1900; - response["payload"]["month"] = timeInfo->tm_mon + 1; - response["payload"]["day"] = timeInfo->tm_mday; - response["payload"]["hour"] = timeInfo->tm_hour; - response["payload"]["minute"] = timeInfo->tm_min; - response["payload"]["second"] = timeInfo->tm_sec; - } else { - response["payload"]["local_timestamp"] = millis() / 1000; - response["payload"]["utc_timestamp"] = millis() / 1000; - response["payload"]["rtc_available"] = false; - LOG_WARNING(TAG, "TimeKeeper reference not set for device time request"); - } - - String responseStr; - serializeJson(response, responseStr); - sendResponse(responseStr, context); - - LOG_DEBUG(TAG, "Device time requested"); -} - -void CommandHandler::handleGetClockTimeCommand(const MessageContext& context) { - StaticJsonDocument<256> response; - response["status"] = "SUCCESS"; - response["type"] = "clock_time"; - - // Get physical clock time from ConfigManager - response["payload"]["clock_hour"] = _configManager.getPhysicalClockHour(); - response["payload"]["clock_minute"] = _configManager.getPhysicalClockMinute(); - response["payload"]["clock_available"] = true; - response["payload"]["last_sync_time"] = _configManager.getLastSyncTime(); - response["payload"]["next_output_is_c1"] = _configManager.getNextOutputIsC1(); - - String responseStr; - serializeJson(response, responseStr); - sendResponse(responseStr, context); - - LOG_DEBUG(TAG, "Physical clock time requested: %02d:%02d (last sync: %lu)", - _configManager.getPhysicalClockHour(), - _configManager.getPhysicalClockMinute(), - _configManager.getLastSyncTime()); -} - -// ════════════════════════════════════════════════════════════════════════════ -// FIRMWARE MANAGEMENT IMPLEMENTATION -// ════════════════════════════════════════════════════════════════════════════ - -void CommandHandler::handleCommitFirmwareCommand(const MessageContext& context) { - if (!_firmwareValidator) { - sendErrorResponse("commit_firmware", "FirmwareValidator not available", context); - return; - } - - // Check if firmware is actually in testing mode - if (!_firmwareValidator->isInTestingMode()) { - sendErrorResponse("commit_firmware", "No firmware validation in progress", context); - return; - } - - LOG_INFO(TAG, "💾 Manual firmware commit requested via %s", - context.source == MessageSource::MQTT ? "MQTT" : "WebSocket"); - - try { - _firmwareValidator->commitFirmware(); - sendSuccessResponse("commit_firmware", "Firmware committed successfully", context); - LOG_INFO(TAG, "✅ Firmware manually committed - system is now stable"); - } catch (...) { - sendErrorResponse("commit_firmware", "Failed to commit firmware", context); - LOG_ERROR(TAG, "❌ Failed to commit firmware"); - } -} - -void CommandHandler::handleRollbackFirmwareCommand(const MessageContext& context) { - if (!_firmwareValidator) { - sendErrorResponse("rollback_firmware", "FirmwareValidator not available", context); - return; - } - - LOG_WARNING(TAG, "🔄 Manual firmware rollback requested via %s", - context.source == MessageSource::MQTT ? "MQTT" : "WebSocket"); - - try { - _firmwareValidator->rollbackFirmware(); - sendSuccessResponse("rollback_firmware", "Firmware rollback initiated - device will reboot", context); - LOG_WARNING(TAG, "🔄 Firmware rollback initiated - device should reboot shortly"); - - // Device should reboot automatically, but this response might not be sent - } catch (...) { - sendErrorResponse("rollback_firmware", "Failed to initiate firmware rollback", context); - LOG_ERROR(TAG, "❌ Failed to initiate firmware rollback"); - } -} - -void CommandHandler::handleGetFirmwareStatusCommand(const MessageContext& context) { - if (!_firmwareValidator) { - sendErrorResponse("get_firmware_status", "FirmwareValidator not available", context); - return; - } - - StaticJsonDocument<512> response; - response["status"] = "SUCCESS"; - response["type"] = "firmware_status"; - - // Get firmware validation state - auto validationState = _firmwareValidator->getValidationState(); - auto currentInfo = _firmwareValidator->getCurrentFirmwareInfo(); - auto config = _firmwareValidator->getValidationConfig(); - - // Map enum to string - String stateStr; - switch (validationState) { - case FirmwareValidationState::UNKNOWN: - stateStr = "UNKNOWN"; - break; - case FirmwareValidationState::STARTUP_PENDING: - stateStr = "STARTUP_PENDING"; - break; - case FirmwareValidationState::STARTUP_RUNNING: - stateStr = "STARTUP_RUNNING"; - break; - case FirmwareValidationState::RUNTIME_TESTING: - stateStr = "RUNTIME_TESTING"; - break; - case FirmwareValidationState::VALIDATED: - stateStr = "VALIDATED"; - break; - case FirmwareValidationState::FAILED_STARTUP: - stateStr = "FAILED_STARTUP"; - break; - case FirmwareValidationState::FAILED_RUNTIME: - stateStr = "FAILED_RUNTIME"; - break; - case FirmwareValidationState::ROLLED_BACK: - stateStr = "ROLLED_BACK"; - break; - default: - stateStr = "INVALID"; - break; - } - - response["payload"]["validation_state"] = stateStr; - response["payload"]["current_version"] = currentInfo.version; - response["payload"]["is_testing"] = currentInfo.isTesting; - response["payload"]["is_valid"] = currentInfo.isValid; - response["payload"]["boot_count"] = currentInfo.bootCount; - response["payload"]["build_date"] = currentInfo.buildDate; - - // Calculate remaining validation time if in testing mode - if (_firmwareValidator->isInTestingMode()) { - // This is a simplified calculation - in reality you'd need to track when validation started - response["payload"]["runtime_timeout_ms"] = config.runtimeTimeoutMs; - response["payload"]["can_commit"] = true; - response["payload"]["can_rollback"] = true; - } else { - response["payload"]["runtime_timeout_ms"] = 0; - response["payload"]["can_commit"] = false; - response["payload"]["can_rollback"] = (validationState != FirmwareValidationState::VALIDATED); - } - - String responseStr; - serializeJson(response, responseStr); - sendResponse(responseStr, context); - - LOG_DEBUG(TAG, "Firmware status requested: %s", stateStr.c_str()); -} - -void CommandHandler::handleNetworkInfoCommand(const MessageContext& context) { - StaticJsonDocument<256> response; - response["status"] = "SUCCESS"; - response["type"] = "network_info"; - - JsonObject payload = response.createNestedObject("payload"); - payload["ip"] = WiFi.localIP().toString(); - payload["gateway"] = WiFi.gatewayIP().toString(); - payload["dns"] = WiFi.dnsIP().toString(); - - String responseStr; - serializeJson(response, responseStr); - sendResponse(responseStr, context); -} - -void CommandHandler::handleGetFullSettingsCommand(const MessageContext& context) { - LOG_DEBUG(TAG, "Full settings requested"); - - // Get all settings as JSON string from ConfigManager - String settingsJson = _configManager.getAllSettingsAsJson(); - - // Parse it to embed in our response structure - StaticJsonDocument<512> response; - response["status"] = "SUCCESS"; - response["type"] = "full_settings"; - - // Parse the settings JSON and add as payload - DynamicJsonDocument settingsDoc(4096); - DeserializationError error = deserializeJson(settingsDoc, settingsJson); - - if (error) { - LOG_ERROR(TAG, "Failed to parse settings JSON: %s", error.c_str()); - sendErrorResponse("get_full_settings", "Failed to serialize settings", context); - return; - } - - response["payload"] = settingsDoc.as(); - - String responseStr; - serializeJson(response, responseStr); - sendResponse(responseStr, context); - - LOG_DEBUG(TAG, "Full settings sent (%d bytes)", responseStr.length()); -} - -void CommandHandler::handleSyncTimeToLcdCommand(const MessageContext& context) { - StaticJsonDocument<256> response; - response["status"] = "SUCCESS"; - response["type"] = "sync_time_to_lcd"; - - // Get the local timestamp from TimeKeeper (RTC stores local time) - unsigned long localTimestamp = 0; - if (_timeKeeper) { - localTimestamp = _timeKeeper->getTime(); - } else { - // Fallback to millis if TimeKeeper not available - localTimestamp = millis() / 1000; - LOG_WARNING(TAG, "TimeKeeper not available for LCD time sync"); - } - - // Get timezone offset from ConfigManager (in seconds) - const auto& timeConfig = _configManager.getTimeConfig(); - long totalOffset = timeConfig.gmtOffsetSec + timeConfig.daylightOffsetSec; - - // Calculate UTC timestamp by subtracting the offset from local time - unsigned long utcTimestamp = localTimestamp - totalOffset; - - response["payload"]["timestamp"] = utcTimestamp; - response["payload"]["offset"] = totalOffset; - - String responseStr; - serializeJson(response, responseStr); - sendResponse(responseStr, context); - - LOG_DEBUG(TAG, "LCD time sync: UTC=%lu, offset=%ld", utcTimestamp, totalOffset); -} - -void CommandHandler::handleSetNetworkConfigCommand(JsonVariant contents, const MessageContext& context) { - // Validate that we have at least one parameter to update - bool hasHostname = contents.containsKey("hostname"); - bool hasStaticIPConfig = contents.containsKey("useStaticIP"); - - if (!hasHostname && !hasStaticIPConfig) { - sendErrorResponse("set_network_config", "No network parameters provided", context); - return; - } - - try { - bool needsReboot = false; - bool configChanged = false; - - // Get current network config (read-only reference) - auto& currentConfig = _configManager.getNetworkConfig(); - - // Create new config based on current settings - bool useStaticIP = currentConfig.useStaticIP; - IPAddress ip = currentConfig.ip; - IPAddress gateway = currentConfig.gateway; - IPAddress subnet = currentConfig.subnet; - IPAddress dns1 = currentConfig.dns1; - IPAddress dns2 = currentConfig.dns2; - String hostname = currentConfig.hostname; - - // Update hostname if provided - if (hasHostname) { - String newHostname = contents["hostname"].as(); - if (!newHostname.isEmpty() && newHostname.length() <= 32) { - hostname = newHostname; - configChanged = true; - needsReboot = true; - LOG_INFO(TAG, "Hostname will be updated to: %s", hostname.c_str()); - } else { - sendErrorResponse("set_network_config", "Invalid hostname (must be 1-32 characters)", context); - return; - } - } - - // Update static IP configuration if provided - if (hasStaticIPConfig) { - useStaticIP = contents["useStaticIP"].as(); - configChanged = true; - needsReboot = true; - - if (useStaticIP) { - // Validate and parse required fields for static IP - if (!contents.containsKey("ip") || !contents.containsKey("gateway") || !contents.containsKey("subnet")) { - sendErrorResponse("set_network_config", "Static IP requires: ip, gateway, and subnet", context); - return; - } - - // Parse IP addresses - if (!ip.fromString(contents["ip"].as())) { - sendErrorResponse("set_network_config", "Invalid IP address format", context); - return; - } - if (!gateway.fromString(contents["gateway"].as())) { - sendErrorResponse("set_network_config", "Invalid gateway address format", context); - return; - } - if (!subnet.fromString(contents["subnet"].as())) { - sendErrorResponse("set_network_config", "Invalid subnet mask format", context); - return; - } - - // Parse optional DNS servers - if (contents.containsKey("dns1")) { - dns1.fromString(contents["dns1"].as()); - } - if (contents.containsKey("dns2")) { - dns2.fromString(contents["dns2"].as()); - } - - LOG_INFO(TAG, "Static IP configuration will be applied: %s", ip.toString().c_str()); - } else { - LOG_INFO(TAG, "DHCP mode will be enabled"); - } - } - - - - // If anything changed, update and save configuration - if (configChanged) { - // Update network config (saves to SD internally) - _configManager.updateNetworkConfig(hostname, useStaticIP, ip, gateway, subnet, dns1, dns2); - - bool saved = true; // saveNetworkConfig() already called in updateNetworkConfig() - - if (saved) { - String responseMsg = "Network configuration updated successfully"; - if (needsReboot) { - responseMsg += ". RESTART DEVICE to apply changes"; - } - sendSuccessResponse("set_network_config", responseMsg, context); - LOG_INFO(TAG, "✅ Network configuration saved to SD card"); - } else { - sendErrorResponse("set_network_config", "Configuration updated but failed to save to SD card", context); - LOG_ERROR(TAG, "❌ Failed to save network configuration to SD card"); - } - } else { - sendSuccessResponse("set_network_config", "No changes detected", context); - } - - } catch (const std::exception& e) { - sendErrorResponse("set_network_config", String("Exception: ") + e.what(), context); - LOG_ERROR(TAG, "Exception in handleSetNetworkConfigCommand: %s", e.what()); - } catch (...) { - sendErrorResponse("set_network_config", "Unknown error occurred", context); - LOG_ERROR(TAG, "Unknown exception in handleSetNetworkConfigCommand"); - } -} - -// ════════════════════════════════════════════════════════════════════════════ -// RESET DEFAULTS COMMAND -// ════════════════════════════════════════════════════════════════════════════ - -void CommandHandler::handleResetDefaultsCommand(const MessageContext& context) { - - LOG_WARNING(TAG, "⚠️ Factory reset requested. Proceeding..."); - - try { - // Reset all configurations to defaults - bool resetComplete = _configManager.resetAllToDefaults(); - - if (resetComplete) { - sendSuccessResponse("reset_defaults", "Reset to Defaults completed. Device will Restart to apply changes.", context); - LOG_WARNING(TAG, "✅ Factory reset completed and all configurations saved to SD card"); - } else { - sendErrorResponse("reset_defaults", "Reset to Defaults applied but failed to save some configurations to SD card", context); - LOG_ERROR(TAG, "❌ Reset to Defaults applied but failed to save some configurations to SD card"); - } - } catch (...) { - sendErrorResponse("reset_defaults", "Failed to perform Reset to Defaults", context); - LOG_ERROR(TAG, "❌ Exception occurred during Resetting to Defaults"); - } - -} - - - -// ════════════════════════════════════════════════════════════════════════════ -// SYSTEM COMMAND IMPLEMENTATION -// ════════════════════════════════════════════════════════════════════════════ - -void CommandHandler::handleSystemCommand(JsonVariant contents, const MessageContext& context) { - if (!contents.containsKey("action")) { - sendErrorResponse("system", "Missing action parameter", context); - return; - } - - String action = contents["action"]; - LOG_DEBUG(TAG, "Processing system action: %s", action.c_str()); - - if (action == "status") { - handleStatusCommand(context); - } else if (action == "reset_defaults") { - handleResetDefaultsCommand(context); - } else if (action == "commit_firmware") { - handleCommitFirmwareCommand(context); - } else if (action == "rollback_firmware") { - handleRollbackFirmwareCommand(context); - } else if (action == "get_firmware_status") { - handleGetFirmwareStatusCommand(context); - } else if (action == "set_network_config") { - handleSetNetworkConfigCommand(contents, context); - } else if (action == "set_serial_log_level") { - handleSetSerialLogLevelCommand(contents, context); - } else if (action == "set_sd_log_level") { - handleSetSdLogLevelCommand(contents, context); - } else if (action == "set_mqtt_log_level") { - handleSetMqttLogLevelCommand(contents, context); - } else if (action == "set_mqtt_enabled") { - handleSetMqttEnabledCommand(contents, context); - } else if (action == "restart" || action == "reboot") { - handleRestartCommand(context); - } else if (action == "force_update") { - handleForceUpdateCommand(contents, context); - } else if (action == "custom_update") { - handleCustomUpdateCommand(contents, context); - } else { - LOG_WARNING(TAG, "Unknown system action: %s", action.c_str()); - sendErrorResponse("system", "Unknown action: " + action, context); - } -} - -// ════════════════════════════════════════════════════════════════════════════ -// LOG LEVEL COMMANDS -// ════════════════════════════════════════════════════════════════════════════ - -void CommandHandler::handleSetSerialLogLevelCommand(JsonVariant contents, const MessageContext& context) { - if (!contents.containsKey("level")) { - sendErrorResponse("set_serial_log_level", "Missing level parameter", context); - return; - } - - uint8_t level = contents["level"].as(); - - // Set the level in ConfigManager - if (_configManager.setSerialLogLevel(level)) { - // Apply the level to Logging immediately - Logging::setLevel((Logging::LogLevel)level); - - // Save to SD card - bool saved = _configManager.saveGeneralConfig(); - - if (saved) { - sendSuccessResponse("set_serial_log_level", - "Serial log level set to " + String(level) + " and saved", context); - LOG_INFO(TAG, "Serial log level updated to %d", level); - } else { - sendErrorResponse("set_serial_log_level", - "Log level set but failed to save to SD card", context); - LOG_ERROR(TAG, "Failed to save serial log level to SD card"); - } - } else { - sendErrorResponse("set_serial_log_level", - "Invalid log level (must be 0-5)", context); - } -} - -void CommandHandler::handleSetSdLogLevelCommand(JsonVariant contents, const MessageContext& context) { - if (!contents.containsKey("level")) { - sendErrorResponse("set_sd_log_level", "Missing level parameter", context); - return; - } - - uint8_t level = contents["level"].as(); - - // Set the level in ConfigManager - if (_configManager.setSdLogLevel(level)) { - // Apply immediately - Logging::setSdLevel((Logging::LogLevel)level); - - // Save to SD card - bool saved = _configManager.saveGeneralConfig(); - - if (saved) { - sendSuccessResponse("set_sd_log_level", - "SD log level set to " + String(level) + " and saved", context); - LOG_INFO(TAG, "SD log level updated to %d", level); - } else { - sendErrorResponse("set_sd_log_level", - "Log level set but failed to save to SD card", context); - LOG_ERROR(TAG, "Failed to save SD log level to SD card"); - } - } else { - sendErrorResponse("set_sd_log_level", - "Invalid log level (must be 0-5)", context); - } -} - -void CommandHandler::handleSetMqttLogLevelCommand(JsonVariant contents, const MessageContext& context) { - if (!contents.containsKey("level")) { - sendErrorResponse("set_mqtt_log_level", "Missing level parameter", context); - return; - } - - uint8_t level = contents["level"].as(); - - // Set the level in ConfigManager - if (_configManager.setMqttLogLevel(level)) { - // Apply the level to Logging immediately - Logging::setMqttLogLevel((Logging::LogLevel)level); - - // Save to SD card - bool saved = _configManager.saveGeneralConfig(); - - if (saved) { - sendSuccessResponse("set_mqtt_log_level", - "MQTT log level set to " + String(level) + " and saved", context); - LOG_INFO(TAG, "MQTT log level updated to %d", level); - } else { - sendErrorResponse("set_mqtt_log_level", - "Log level set but failed to save to SD card", context); - LOG_ERROR(TAG, "Failed to save MQTT log level to SD card"); - } - } else { - sendErrorResponse("set_mqtt_log_level", - "Invalid log level (must be 0-5)", context); - } -} - -void CommandHandler::handleSetMqttEnabledCommand(JsonVariant contents, const MessageContext& context) { - if (!contents.containsKey("enabled")) { - sendErrorResponse("set_mqtt_enabled", "Missing enabled parameter", context); - return; - } - - bool enabled = contents["enabled"].as(); - - // Set MQTT enabled state in ConfigManager - _configManager.setMqttEnabled(enabled); - - // Save to SD card - bool saved = _configManager.saveGeneralConfig(); - - if (saved) { - sendSuccessResponse("set_mqtt_enabled", - String("MQTT ") + (enabled ? "enabled" : "disabled") + " and saved", context); - LOG_INFO(TAG, "MQTT %s by user command", enabled ? "enabled" : "disabled"); - - // If disabling, disconnect MQTT immediately - // If enabling, trigger connection attempt - if (_communicationRouter) { - if (!enabled) { - _communicationRouter->getMQTTClient().disconnect(); - } else { - _communicationRouter->getMQTTClient().connect(); - } - } else { - LOG_WARNING(TAG, "CommunicationRouter reference not set - cannot control MQTT"); - } - } else { - sendErrorResponse("set_mqtt_enabled", - "MQTT state changed but failed to save to SD card", context); - LOG_ERROR(TAG, "Failed to save MQTT enabled state to SD card"); - } -} - -// ════════════════════════════════════════════════════════════════════════════ -// RESTART COMMAND -// ════════════════════════════════════════════════════════════════════════════ - -void CommandHandler::handleRestartCommand(const MessageContext& context) { - LOG_WARNING(TAG, "🔄 Device restart requested via command"); - sendSuccessResponse("restart", "Device will restart in 2 seconds", context); - - // Small delay to ensure response is sent - delay(2000); - - // Restart the ESP32 - ESP.restart(); -} - -// ════════════════════════════════════════════════════════════════════════════ -// FORCE UPDATE COMMAND -// ════════════════════════════════════════════════════════════════════════════ - -void CommandHandler::handleForceUpdateCommand(JsonVariant contents, const MessageContext& context) { - LOG_WARNING(TAG, "🔄 Force OTA update requested via command"); - - // Check if player is active - if (_player && _player->isCurrentlyPlaying()) { - sendErrorResponse("force_update", "Cannot update while playback is active", context); - LOG_WARNING(TAG, "Force update rejected - player is active"); - return; - } - - // Get optional channel parameter (defaults to "stable") - String channel = "stable"; - if (contents.containsKey("channel")) { - channel = contents["channel"].as(); - } - - sendSuccessResponse("force_update", - "Starting forced OTA update from channel: " + channel + ". Device may reboot.", context); - - // Small delay to ensure response is sent - delay(1000); - - // Perform the update - bool result = _otaManager.performManualUpdate(channel); - - // Note: If update succeeds, device will reboot and this won't be reached - if (!result) { - LOG_ERROR(TAG, "Force update failed"); - // Error response may not be received if we already restarted - } -} - -// ════════════════════════════════════════════════════════════════════════════ -// CUSTOM UPDATE COMMAND -// ════════════════════════════════════════════════════════════════════════════ - -void CommandHandler::handleCustomUpdateCommand(JsonVariant contents, const MessageContext& context) { - LOG_WARNING(TAG, "🔥 Custom OTA update requested via command"); - - // Validate required parameters - if (!contents.containsKey("firmware_url")) { - sendErrorResponse("custom_update", "Missing firmware_url parameter", context); - return; - } - - String firmwareUrl = contents["firmware_url"].as(); - - // Optional parameters - String checksum = contents.containsKey("checksum") ? - contents["checksum"].as() : ""; - size_t fileSize = contents.containsKey("file_size") ? - contents["file_size"].as() : 0; - uint16_t version = contents.containsKey("version") ? - contents["version"].as() : 0; - - // Check if player is active - if (_player && _player->isCurrentlyPlaying()) { - sendErrorResponse("custom_update", "Cannot update while playback is active", context); - LOG_WARNING(TAG, "Custom update rejected - player is active"); - return; - } - - LOG_INFO(TAG, "Custom update: URL=%s, Checksum=%s, Size=%u, Version=%u", - firmwareUrl.c_str(), - checksum.isEmpty() ? "none" : checksum.c_str(), - fileSize, - version); - - sendSuccessResponse("custom_update", - "Starting custom OTA update. Device may reboot.", context); - - // Small delay to ensure response is sent - delay(1000); - - // Perform the custom update - bool result = _otaManager.performCustomUpdate(firmwareUrl, checksum, fileSize, version); - - // Note: If update succeeds, device will reboot and this won't be reached - if (!result) { - LOG_ERROR(TAG, "Custom update failed"); - // Error response may not be received if we already restarted - } -} - diff --git a/src/Communication/CommandHandler/CommandHandler.hpp b/src/Communication/CommandHandler/CommandHandler.hpp deleted file mode 100644 index 8c41dd1..0000000 --- a/src/Communication/CommandHandler/CommandHandler.hpp +++ /dev/null @@ -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 -#include - -// 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; - - 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); -}; diff --git a/src/Communication/CommunicationRouter/CommunicationRouter.hpp b/src/Communication/CommunicationRouter/CommunicationRouter.hpp index 85f2e47..98878d3 100644 --- a/src/Communication/CommunicationRouter/CommunicationRouter.hpp +++ b/src/Communication/CommunicationRouter/CommunicationRouter.hpp @@ -3,13 +3,12 @@ * * The router is now a thin coordinator: * • 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 * • Registers all domain handlers in registerHandlers() * • 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 - * until Stage 4 is proven stable, then gets deleted. + * The old CommandHandler and HTTPRequestHandler have been deleted. */ #pragma once @@ -19,10 +18,10 @@ #include #include -// Underlying protocol objects (still owned here) -#include "../MQTTAsyncClient/MQTTAsyncClient.hpp" -#include "../WebSocketServer/WebSocketServer.hpp" -#include "../UARTCommandHandler/UARTCommandHandler.hpp" +// Underlying protocol drivers (still owned here) +#include "../Drivers/MQTTDriver/MQTTDriver.hpp" +#include "../Drivers/WebSocketDriver/WebSocketDriver.hpp" +#include "../Drivers/UARTDriver/UARTDriver.hpp" #include "../../ClientManager/ClientManager.hpp" // New architecture @@ -81,8 +80,8 @@ public: bool isHealthy() const; // Legacy accessors used by other subsystems - MQTTAsyncClient& getMQTTClient() { return _mqttClient; } - UARTCommandHandler& getUARTHandler() { return _uartHandler; } + MQTTDriver& getMQTTClient() { return _mqttClient; } + UARTDriver& getUARTHandler() { return _uartHandler; } // Broadcast helpers — called by BellEngine, Player, Telemetry, etc. void broadcastStatus(const String& statusMessage); @@ -121,10 +120,10 @@ private: OutputManager* _outputManager = nullptr; // ── Underlying protocol objects (owned) ───────────────────────────────── - MQTTAsyncClient _mqttClient; + MQTTDriver _mqttClient; ClientManager _clientManager; - WebSocketServer _wsServer; - UARTCommandHandler _uartHandler; + WebSocketDriver _wsServer; + UARTDriver _uartHandler; // ── New architecture (owned) ──────────────────────────────────────────── CommandBus _bus; diff --git a/src/Communication/MQTTAsyncClient/MQTTAsyncClient.cpp b/src/Communication/Drivers/MQTTDriver/MQTTDriver.cpp similarity index 85% rename from src/Communication/MQTTAsyncClient/MQTTAsyncClient.cpp rename to src/Communication/Drivers/MQTTDriver/MQTTDriver.cpp index f960154..10bccf0 100644 --- a/src/Communication/MQTTAsyncClient/MQTTAsyncClient.cpp +++ b/src/Communication/Drivers/MQTTDriver/MQTTDriver.cpp @@ -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" -#include "../../ConfigManager/ConfigManager.hpp" -#include "../../Networking/Networking.hpp" -#include "../../Logging/Logging.hpp" +#include "../../../ConfigManager/ConfigManager.hpp" +#include "../../../Networking/Networking.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) , _networking(networking) , _messageCallback(nullptr) @@ -53,7 +53,7 @@ MQTTAsyncClient::MQTTAsyncClient(ConfigManager& configManager, Networking& netwo } -MQTTAsyncClient::~MQTTAsyncClient() { +MQTTDriver::~MQTTDriver() { if (_mqttReconnectTimer) { xTimerDelete(_mqttReconnectTimer, portMAX_DELAY); } @@ -68,7 +68,7 @@ MQTTAsyncClient::~MQTTAsyncClient() { _mqttClient.disconnect(); } -void MQTTAsyncClient::begin() { +void MQTTDriver::begin() { LOG_INFO(TAG, "Initializing MQTT Async Client"); auto& mqttConfig = _configManager.getMqttConfig(); @@ -116,7 +116,7 @@ void MQTTAsyncClient::begin() { LOG_INFO(TAG, "✅ MQTT Async Client initialized"); } -void MQTTAsyncClient::connect() { +void MQTTDriver::connect() { auto& mqttConfig = _configManager.getMqttConfig(); // 🔥 Check if MQTT is enabled @@ -140,12 +140,12 @@ void MQTTAsyncClient::connect() { LOG_INFO(TAG, "MQTT connect() called - waiting for async connection..."); } -void MQTTAsyncClient::disconnect() { +void MQTTDriver::disconnect() { _mqttClient.disconnect(); 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 if (!_mqttClient.connected()) { // 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; } -void MQTTAsyncClient::setCallback(MessageCallback callback) { +void MQTTDriver::setCallback(MessageCallback callback) { _messageCallback = callback; } -bool MQTTAsyncClient::isConnected() const { +bool MQTTDriver::isConnected() const { return _mqttClient.connected(); } -void MQTTAsyncClient::onNetworkConnected() { +void MQTTDriver::onNetworkConnected() { auto& mqttConfig = _configManager.getMqttConfig(); // 🔥 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"); 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); 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, "🔍 Free heap AFTER MQTT connect: %d bytes", ESP.getFreeHeap()); @@ -225,7 +225,7 @@ void MQTTAsyncClient::onMqttConnect(bool sessionPresent) { startHeartbeat(); } -void MQTTAsyncClient::onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { +void MQTTDriver::onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { auto& mqttConfig = _configManager.getMqttConfig(); 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); } -void MQTTAsyncClient::onMqttUnsubscribe(uint16_t packetId) { +void MQTTDriver::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) { +void MQTTDriver::onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) { // Convert to String String topicStr = String(topic); String payloadStr = String(payload).substring(0, len); @@ -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); } -void MQTTAsyncClient::attemptReconnection() { +void MQTTDriver::attemptReconnection() { // Double-check network is still up if (_networking.isConnected()) { LOG_INFO(TAG, "Attempting MQTT reconnection..."); @@ -318,15 +318,15 @@ void MQTTAsyncClient::attemptReconnection() { } } -void MQTTAsyncClient::mqttReconnectTaskFn(void* param) { - MQTTAsyncClient* client = static_cast(param); +void MQTTDriver::mqttReconnectTaskFn(void* param) { + MQTTDriver* client = static_cast(param); client->attemptReconnection(); vTaskDelete(NULL); } -void MQTTAsyncClient::mqttReconnectTimerCallback(TimerHandle_t xTimer) { - if (MQTTAsyncClient::_instance) { - xTaskCreate(mqttReconnectTaskFn, "mqttRecon", 3072, MQTTAsyncClient::_instance, 5, NULL); +void MQTTDriver::mqttReconnectTimerCallback(TimerHandle_t xTimer) { + if (MQTTDriver::_instance) { + xTaskCreate(mqttReconnectTaskFn, "mqttRecon", 3072, MQTTDriver::_instance, 5, NULL); } } @@ -334,7 +334,7 @@ void MQTTAsyncClient::mqttReconnectTimerCallback(TimerHandle_t xTimer) { // HEARTBEAT FUNCTIONALITY // ═══════════════════════════════════════════════════════════════════════════════════ -void MQTTAsyncClient::startHeartbeat() { +void MQTTDriver::startHeartbeat() { if (_heartbeatTimer) { 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) { xTimerStop(_heartbeatTimer, 0); _heartbeatTaskHandle = nullptr; @@ -354,7 +354,7 @@ void MQTTAsyncClient::stopHeartbeat() { } } -void MQTTAsyncClient::publishHeartbeat() { +void MQTTDriver::publishHeartbeat() { if (!_mqttClient.connected()) { LOG_WARNING(TAG, "⚠️ Cannot publish heartbeat - MQTT not connected"); return; @@ -410,21 +410,21 @@ void MQTTAsyncClient::publishHeartbeat() { } } -void MQTTAsyncClient::mqttHeartbeatTaskFn(void* param) { - MQTTAsyncClient* client = static_cast(param); +void MQTTDriver::mqttHeartbeatTaskFn(void* param) { + MQTTDriver* client = static_cast(param); client->publishHeartbeat(); client->_heartbeatTaskHandle = nullptr; vTaskDelete(NULL); } -void MQTTAsyncClient::heartbeatTimerCallback(TimerHandle_t xTimer) { - if (MQTTAsyncClient::_instance) { +void MQTTDriver::heartbeatTimerCallback(TimerHandle_t xTimer) { + if (MQTTDriver::_instance) { // Guard: skip if previous heartbeat task is still running - if (MQTTAsyncClient::_instance->_heartbeatTaskHandle != nullptr) { + if (MQTTDriver::_instance->_heartbeatTaskHandle != nullptr) { return; } - xTaskCreate(mqttHeartbeatTaskFn, "mqttHB", 3072, MQTTAsyncClient::_instance, 3, - &MQTTAsyncClient::_instance->_heartbeatTaskHandle); + xTaskCreate(mqttHeartbeatTaskFn, "mqttHB", 3072, MQTTDriver::_instance, 3, + &MQTTDriver::_instance->_heartbeatTaskHandle); } } @@ -432,22 +432,22 @@ void MQTTAsyncClient::heartbeatTimerCallback(TimerHandle_t xTimer) { // NETWORK STABILIZATION - NON-BLOCKING TIMER APPROACH // ═══════════════════════════════════════════════════════════════════════════════════ -void MQTTAsyncClient::connectAfterStabilization() { +void MQTTDriver::connectAfterStabilization() { LOG_DEBUG(TAG, "Network stabilization complete - connecting to MQTT"); 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 - MQTTAsyncClient* client = static_cast(param); + MQTTDriver* client = static_cast(param); client->connectAfterStabilization(); vTaskDelete(NULL); } -void MQTTAsyncClient::networkStabilizationTimerCallback(TimerHandle_t xTimer) { - if (MQTTAsyncClient::_instance) { +void MQTTDriver::networkStabilizationTimerCallback(TimerHandle_t xTimer) { + if (MQTTDriver::_instance) { // Defer to a task — timer callbacks run in Tmr Svc (2KB stack), not enough for connect() - xTaskCreate(mqttConnectTaskFn, "mqttConnect", 3072, 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 // ═══════════════════════════════════════════════════════════════════════════════════ -unsigned long MQTTAsyncClient::getReconnectDelay() { +unsigned long MQTTDriver::getReconnectDelay() { // First 3 attempts: Quick retries (5 seconds each) if (_reconnectAttempts <= MQTT_MAX_QUICK_RETRIES) { return MQTT_RECONNECT_BASE_DELAY; diff --git a/src/Communication/MQTTAsyncClient/MQTTAsyncClient.hpp b/src/Communication/Drivers/MQTTDriver/MQTTDriver.hpp similarity index 89% rename from src/Communication/MQTTAsyncClient/MQTTAsyncClient.hpp rename to src/Communication/Drivers/MQTTDriver/MQTTDriver.hpp index 7cd6237..f15d73e 100644 --- a/src/Communication/MQTTAsyncClient/MQTTAsyncClient.hpp +++ b/src/Communication/Drivers/MQTTDriver/MQTTDriver.hpp @@ -1,17 +1,12 @@ /* * ═══════════════════════════════════════════════════════════════════════════════════ - * MQTTASYNCCLIENT.HPP - MQTT Client with AsyncMqttClient + * MQTTDRIVER.HPP - MQTT Protocol Driver * ═══════════════════════════════════════════════════════════════════════════════════ - * - * 🔒 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 - * + * + * Low-level MQTT protocol driver using AsyncMqttClient. + * Handles broker connection, auth, publish/subscribe, reconnect with exponential + * backoff, and heartbeat. Wrapped by MQTTTransport for CommandBus integration. + * * 📋 VERSION: 3.0 (AsyncMqttClient-based) * 📅 DATE: 2025-01-04 * 👨‍💻 AUTHOR: Advanced Bell Systems @@ -26,15 +21,15 @@ class ConfigManager; class Networking; -class MQTTAsyncClient { +class MQTTDriver { public: - static MQTTAsyncClient* _instance; + static MQTTDriver* _instance; // Message callback type using MessageCallback = std::function; - explicit MQTTAsyncClient(ConfigManager& configManager, Networking& networking); - ~MQTTAsyncClient(); + explicit MQTTDriver(ConfigManager& configManager, Networking& networking); + ~MQTTDriver(); /** * @brief Initialize MQTT client diff --git a/src/Communication/UARTCommandHandler/UARTCommandHandler.cpp b/src/Communication/Drivers/UARTDriver/UARTDriver.cpp similarity index 83% rename from src/Communication/UARTCommandHandler/UARTCommandHandler.cpp rename to src/Communication/Drivers/UARTDriver/UARTDriver.cpp index 46a8425..fa20f94 100644 --- a/src/Communication/UARTCommandHandler/UARTCommandHandler.cpp +++ b/src/Communication/Drivers/UARTDriver/UARTDriver.cpp @@ -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" -#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) , _txPin(txPin) , _rxPin(rxPin) @@ -21,11 +21,11 @@ UARTCommandHandler::UARTCommandHandler(uint8_t txPin, uint8_t rxPin, uint32_t ba resetBuffer(); } -UARTCommandHandler::~UARTCommandHandler() { +UARTDriver::~UARTDriver() { _serial.end(); } -void UARTCommandHandler::begin() { +void UARTDriver::begin() { LOG_INFO(TAG, "Initializing UART Command Handler"); LOG_INFO(TAG, " TX Pin: GPIO%d", _txPin); LOG_INFO(TAG, " RX Pin: GPIO%d", _rxPin); @@ -43,7 +43,7 @@ void UARTCommandHandler::begin() { LOG_INFO(TAG, "UART Command Handler ready"); } -void UARTCommandHandler::loop() { +void UARTDriver::loop() { if (!_ready) return; // Process all available bytes @@ -74,11 +74,11 @@ void UARTCommandHandler::loop() { } } -void UARTCommandHandler::setCallback(MessageCallback callback) { +void UARTDriver::setCallback(MessageCallback callback) { _callback = callback; } -void UARTCommandHandler::send(const String& response) { +void UARTDriver::send(const String& response) { if (!_ready) { LOG_ERROR(TAG, "UART not ready, cannot send response"); return; @@ -91,7 +91,7 @@ void UARTCommandHandler::send(const String& response) { 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); // Skip empty lines or whitespace-only @@ -127,7 +127,7 @@ void UARTCommandHandler::processLine(const char* line) { } } -void UARTCommandHandler::resetBuffer() { +void UARTDriver::resetBuffer() { _bufferIndex = 0; memset(_buffer, 0, BUFFER_SIZE); } diff --git a/src/Communication/UARTCommandHandler/UARTCommandHandler.hpp b/src/Communication/Drivers/UARTDriver/UARTDriver.hpp similarity index 83% rename from src/Communication/UARTCommandHandler/UARTCommandHandler.hpp rename to src/Communication/Drivers/UARTDriver/UARTDriver.hpp index dd06080..e4330b9 100644 --- a/src/Communication/UARTCommandHandler/UARTCommandHandler.hpp +++ b/src/Communication/Drivers/UARTDriver/UARTDriver.hpp @@ -1,22 +1,11 @@ /* * ═══════════════════════════════════════════════════════════════════════════════════ - * UARTCOMMANDHANDLER.HPP - UART Command Interface for External Control Devices + * UARTDRIVER.HPP - UART Protocol Driver * ═══════════════════════════════════════════════════════════════════════════════════ * - * 🔌 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 + * Low-level UART protocol driver for external devices (LCD panels, button boards). + * Reads newline-delimited JSON on Serial2 (TX: GPIO12, RX: GPIO13 @ 115200 baud). + * Wrapped by UARTTransport for CommandBus integration. * * 📋 VERSION: 1.0 * 📅 DATE: 2025-01-19 @@ -30,7 +19,7 @@ #include #include -class UARTCommandHandler { +class UARTDriver { public: // Default pin configuration static constexpr uint8_t DEFAULT_TX_PIN = 12; @@ -47,11 +36,11 @@ public: * @param rxPin GPIO pin for RX (default: 13) * @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, uint32_t baudRate = DEFAULT_BAUD_RATE); - ~UARTCommandHandler(); + ~UARTDriver(); /** * @brief Initialize the UART interface diff --git a/src/Communication/WebSocketServer/WebSocketServer.cpp b/src/Communication/Drivers/WebSocketDriver/WebSocketDriver.cpp similarity index 80% rename from src/Communication/WebSocketServer/WebSocketServer.cpp rename to src/Communication/Drivers/WebSocketDriver/WebSocketDriver.cpp index 6c477a2..abbd4a8 100644 --- a/src/Communication/WebSocketServer/WebSocketServer.cpp +++ b/src/Communication/Drivers/WebSocketDriver/WebSocketDriver.cpp @@ -1,17 +1,17 @@ /* - * WEBSOCKETSERVER.CPP - WebSocket Server Implementation + * WEBSOCKETDRIVER.CPP - WebSocket Protocol Driver Implementation */ -#include "WebSocketServer.hpp" +#include "WebSocketDriver.hpp" #define TAG "WebSocket" -#include "../../Logging/Logging.hpp" -#include "../ResponseBuilder/ResponseBuilder.hpp" +#include "../../../Logging/Logging.hpp" +#include "../../ResponseBuilder/ResponseBuilder.hpp" // 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) , _clientManager(clientManager) , _messageCallback(nullptr) { @@ -19,11 +19,11 @@ WebSocketServer::WebSocketServer(AsyncWebSocket& webSocket, ClientManager& clien _instance = this; } -WebSocketServer::~WebSocketServer() { +WebSocketDriver::~WebSocketDriver() { _instance = nullptr; } -void WebSocketServer::begin() { +void WebSocketDriver::begin() { _webSocket.onEvent(onEvent); 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 } -void WebSocketServer::setCallback(MessageCallback callback) { +void WebSocketDriver::setCallback(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); } -void WebSocketServer::broadcastToAll(const String& message) { +void WebSocketDriver::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) { +void WebSocketDriver::broadcastToMaster(const String& message) { _clientManager.sendToMasterClients(message); 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); LOG_DEBUG(TAG, "Broadcast to secondary clients: %s", message.c_str()); } -bool WebSocketServer::hasClients() const { +bool WebSocketDriver::hasClients() const { return _clientManager.hasClients(); } -size_t WebSocketServer::getClientCount() const { +size_t WebSocketDriver::getClientCount() const { 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) { if (!_instance) { - LOG_ERROR(TAG, "WebSocketServer static instance is NULL - callback ignored!"); + LOG_ERROR(TAG, "WebSocketDriver static instance is NULL - callback ignored!"); 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", client->id(), client->remoteIP().toString().c_str()); @@ -105,14 +105,14 @@ void WebSocketServer::onConnect(AsyncWebSocketClient* client) { _clientManager.sendToClient(client->id(), welcomeMsg); } -void WebSocketServer::onDisconnect(AsyncWebSocketClient* client) { +void WebSocketDriver::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) { +void WebSocketDriver::onData(AsyncWebSocketClient* client, void* arg, uint8_t* data, size_t len) { AwsFrameInfo* info = (AwsFrameInfo*)arg; // Only handle complete, single-frame text messages diff --git a/src/Communication/WebSocketServer/WebSocketServer.hpp b/src/Communication/Drivers/WebSocketDriver/WebSocketDriver.hpp similarity index 84% rename from src/Communication/WebSocketServer/WebSocketServer.hpp rename to src/Communication/Drivers/WebSocketDriver/WebSocketDriver.hpp index 3af8085..8402060 100644 --- a/src/Communication/WebSocketServer/WebSocketServer.hpp +++ b/src/Communication/Drivers/WebSocketDriver/WebSocketDriver.hpp @@ -1,16 +1,12 @@ /* * ═══════════════════════════════════════════════════════════════════════════════════ - * WEBSOCKETSERVER.HPP - WebSocket Server Manager + * WEBSOCKETDRIVER.HPP - WebSocket Protocol Driver * ═══════════════════════════════════════════════════════════════════════════════════ - * - * 📡 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 - * + * + * Low-level WebSocket protocol driver. Manages client lifecycle, broadcasts, + * and targeted messaging. Wraps AsyncWebSocket + ClientManager. + * Wrapped by WebSocketTransport for CommandBus integration. + * * 📋 VERSION: 1.0 * 📅 DATE: 2025-10-01 * 👨‍💻 AUTHOR: Advanced Bell Systems @@ -22,15 +18,15 @@ #include #include #include -#include "../../ClientManager/ClientManager.hpp" +#include "../../../ClientManager/ClientManager.hpp" -class WebSocketServer { +class WebSocketDriver { public: // Message callback type using MessageCallback = std::function; - explicit WebSocketServer(AsyncWebSocket& webSocket, ClientManager& clientManager); - ~WebSocketServer(); + explicit WebSocketDriver(AsyncWebSocket& webSocket, ClientManager& clientManager); + ~WebSocketDriver(); /** * @brief Initialize WebSocket server @@ -99,5 +95,5 @@ private: void onData(AsyncWebSocketClient* client, void* arg, uint8_t* data, size_t len); // Static instance for callback routing - static WebSocketServer* _instance; + static WebSocketDriver* _instance; }; diff --git a/src/Communication/HTTPRequestHandler/HTTPRequestHandler.cpp b/src/Communication/HTTPRequestHandler/HTTPRequestHandler.cpp deleted file mode 100644 index a9b53d1..0000000 --- a/src/Communication/HTTPRequestHandler/HTTPRequestHandler.cpp +++ /dev/null @@ -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); -} diff --git a/src/Communication/HTTPRequestHandler/HTTPRequestHandler.hpp b/src/Communication/HTTPRequestHandler/HTTPRequestHandler.hpp deleted file mode 100644 index c252784..0000000 --- a/src/Communication/HTTPRequestHandler/HTTPRequestHandler.hpp +++ /dev/null @@ -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 -#include -#include - -// 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); -}; diff --git a/src/Communication/Handlers/MQTTHandler/MQTTHandler.cpp b/src/Communication/Handlers/MQTTHandler/MQTTHandler.cpp index 1ee694b..13faa22 100644 --- a/src/Communication/Handlers/MQTTHandler/MQTTHandler.cpp +++ b/src/Communication/Handlers/MQTTHandler/MQTTHandler.cpp @@ -1,11 +1,11 @@ #include "MQTTHandler.hpp" #include "../../../ConfigManager/ConfigManager.hpp" -#include "../../../Communication/MQTTAsyncClient/MQTTAsyncClient.hpp" +#include "../../../Communication/Drivers/MQTTDriver/MQTTDriver.hpp" #include "../../../Logging/Logging.hpp" #define TAG "MQTTHandler" -MQTTHandler::MQTTHandler(ConfigManager& configManager, MQTTAsyncClient& mqttClient) +MQTTHandler::MQTTHandler(ConfigManager& configManager, MQTTDriver& mqttClient) : _configManager(configManager), _mqttClient(mqttClient) {} std::vector MQTTHandler::commands() const { diff --git a/src/Communication/Handlers/MQTTHandler/MQTTHandler.hpp b/src/Communication/Handlers/MQTTHandler/MQTTHandler.hpp index aee136f..f5c1e10 100644 --- a/src/Communication/Handlers/MQTTHandler/MQTTHandler.hpp +++ b/src/Communication/Handlers/MQTTHandler/MQTTHandler.hpp @@ -5,18 +5,17 @@ class ConfigManager; -// Forward declare the transport so we don't pull in all of MQTT yet. -// In Stage 3 this will be MQTTTransport; for now it wraps MQTTAsyncClient. -class MQTTAsyncClient; +// Forward declare the driver to avoid pulling in full MQTTDriver header. +class MQTTDriver; class MQTTHandler : public ICommandHandler { public: - MQTTHandler(ConfigManager& configManager, MQTTAsyncClient& mqttClient); + MQTTHandler(ConfigManager& configManager, MQTTDriver& mqttClient); std::vector commands() const override; CommandResult execute(const CommandEnvelope& envelope) override; private: ConfigManager& _configManager; - MQTTAsyncClient& _mqttClient; + MQTTDriver& _mqttClient; }; diff --git a/src/Communication/Transport/MQTTTransport/MQTTTransport.cpp b/src/Communication/Transport/MQTTTransport/MQTTTransport.cpp index 753b16f..ac5b9ea 100644 --- a/src/Communication/Transport/MQTTTransport/MQTTTransport.cpp +++ b/src/Communication/Transport/MQTTTransport/MQTTTransport.cpp @@ -6,7 +6,7 @@ #define TAG "MQTTTransport" #include "../../../Logging/Logging.hpp" -MQTTTransport::MQTTTransport(MQTTAsyncClient& mqttClient, CommandBus& bus) +MQTTTransport::MQTTTransport(MQTTDriver& mqttClient, CommandBus& bus) : _mqtt(mqttClient) , _bus(bus) { } @@ -31,7 +31,7 @@ bool MQTTTransport::isHealthy() const { } void MQTTTransport::broadcast(const String& message) { - _mqtt.publish("", message); // MQTTAsyncClient::publish() routes "" → _dataTopic + _mqtt.publish("", message); // MQTTDriver::publish() routes "" → _dataTopic } void MQTTTransport::onNetworkConnected() { diff --git a/src/Communication/Transport/MQTTTransport/MQTTTransport.hpp b/src/Communication/Transport/MQTTTransport/MQTTTransport.hpp index e8f446b..e6d682e 100644 --- a/src/Communication/Transport/MQTTTransport/MQTTTransport.hpp +++ b/src/Communication/Transport/MQTTTransport/MQTTTransport.hpp @@ -2,29 +2,29 @@ #include #include "../ITransport.hpp" -#include "../../MQTTAsyncClient/MQTTAsyncClient.hpp" +#include "../../Drivers/MQTTDriver/MQTTDriver.hpp" class CommandBus; // --------------------------------------------------------------------------- // MQTTTransport // -// ITransport wrapper around the existing MQTTAsyncClient. +// ITransport wrapper around the existing MQTTDriver. // // Responsibilities: -// - Delegates connection lifecycle to MQTTAsyncClient +// - Delegates connection lifecycle to MQTTDriver // - Parses incoming MQTT JSON messages into CommandEnvelopes // - Injects a reply lambda that publishes the response to the data topic // - Dispatches to the CommandBus // - 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. // --------------------------------------------------------------------------- class MQTTTransport : public ITransport { public: - MQTTTransport(MQTTAsyncClient& mqttClient, CommandBus& bus); + MQTTTransport(MQTTDriver& mqttClient, CommandBus& bus); void begin() override; void loop() override; // no-op — AsyncMqttClient is fully async @@ -40,9 +40,9 @@ public: void onNetworkDisconnected(); private: - MQTTAsyncClient& _mqtt; + MQTTDriver& _mqtt; CommandBus& _bus; - // Invoked by MQTTAsyncClient's message callback + // Invoked by MQTTDriver's message callback void onMessage(const String& topic, const String& payload); }; diff --git a/src/Communication/Transport/UARTTransport/UARTTransport.cpp b/src/Communication/Transport/UARTTransport/UARTTransport.cpp index 003c043..8b48ad3 100644 --- a/src/Communication/Transport/UARTTransport/UARTTransport.cpp +++ b/src/Communication/Transport/UARTTransport/UARTTransport.cpp @@ -23,7 +23,7 @@ const size_t UARTTransport::WHITELIST_SIZE = // --------------------------------------------------------------------------- -UARTTransport::UARTTransport(UARTCommandHandler& uart, CommandBus& bus) +UARTTransport::UARTTransport(UARTDriver& uart, CommandBus& bus) : _uart(uart) , _bus(bus) { } diff --git a/src/Communication/Transport/UARTTransport/UARTTransport.hpp b/src/Communication/Transport/UARTTransport/UARTTransport.hpp index 0337bae..9b08a18 100644 --- a/src/Communication/Transport/UARTTransport/UARTTransport.hpp +++ b/src/Communication/Transport/UARTTransport/UARTTransport.hpp @@ -2,14 +2,14 @@ #include #include "../ITransport.hpp" -#include "../../UARTCommandHandler/UARTCommandHandler.hpp" +#include "../../Drivers/UARTDriver/UARTDriver.hpp" class CommandBus; // --------------------------------------------------------------------------- // 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 // commands are accepted from this transport to prevent feedback loops and @@ -31,10 +31,10 @@ class CommandBus; class UARTTransport : public ITransport { public: - UARTTransport(UARTCommandHandler& uart, CommandBus& bus); + UARTTransport(UARTDriver& uart, CommandBus& bus); void begin() override; - void loop() override; // polls UARTCommandHandler::loop() + void loop() override; // polls UARTDriver::loop() bool isHealthy() const override; String name() const override { return "UART"; } @@ -42,7 +42,7 @@ public: void broadcast(const String& message) override; private: - UARTCommandHandler& _uart; + UARTDriver& _uart; CommandBus& _bus; // Commands the UART slave is allowed to issue @@ -51,6 +51,6 @@ private: bool isWhitelisted(const String& command) const; - // Invoked by UARTCommandHandler's message callback + // Invoked by UARTDriver's message callback void onMessage(JsonDocument& doc); }; diff --git a/src/Communication/Transport/WebSocketTransport/WebSocketTransport.cpp b/src/Communication/Transport/WebSocketTransport/WebSocketTransport.cpp index 4d50e42..f895513 100644 --- a/src/Communication/Transport/WebSocketTransport/WebSocketTransport.cpp +++ b/src/Communication/Transport/WebSocketTransport/WebSocketTransport.cpp @@ -6,7 +6,7 @@ #define TAG "WebSocketTransport" #include "../../../Logging/Logging.hpp" -WebSocketTransport::WebSocketTransport(WebSocketServer& wsServer, CommandBus& bus) +WebSocketTransport::WebSocketTransport(WebSocketDriver& wsServer, CommandBus& bus) : _ws(wsServer) , _bus(bus) { } diff --git a/src/Communication/Transport/WebSocketTransport/WebSocketTransport.hpp b/src/Communication/Transport/WebSocketTransport/WebSocketTransport.hpp index be61e0e..27247af 100644 --- a/src/Communication/Transport/WebSocketTransport/WebSocketTransport.hpp +++ b/src/Communication/Transport/WebSocketTransport/WebSocketTransport.hpp @@ -2,17 +2,17 @@ #include #include "../ITransport.hpp" -#include "../../WebSocketServer/WebSocketServer.hpp" +#include "../../Drivers/WebSocketDriver/WebSocketDriver.hpp" class CommandBus; // --------------------------------------------------------------------------- // WebSocketTransport // -// ITransport wrapper around the existing WebSocketServer. +// ITransport wrapper around the existing WebSocketDriver. // // Responsibilities: -// - Delegates connection lifecycle and client management to WebSocketServer +// - Delegates connection lifecycle and client management to WebSocketDriver // - Parses incoming WebSocket JSON messages into CommandEnvelopes // - Injects a reply lambda that sends the response back to the originating client // - Dispatches to the CommandBus @@ -24,7 +24,7 @@ class CommandBus; class WebSocketTransport : public ITransport { public: - WebSocketTransport(WebSocketServer& wsServer, CommandBus& bus); + WebSocketTransport(WebSocketDriver& wsServer, CommandBus& bus); void begin() override; void loop() override; // no-op — AsyncWebServer is event-driven @@ -45,9 +45,9 @@ public: size_t getClientCount() const; private: - WebSocketServer& _ws; + WebSocketDriver& _ws; CommandBus& _bus; - // Invoked by WebSocketServer's message callback + // Invoked by WebSocketDriver's message callback void onMessage(uint32_t clientId, const JsonDocument& doc); };