/* █████ █████ ██████████ █████████ ███████████ ██████████ ███████████ ▒▒███ ▒▒███ ▒▒███▒▒▒▒▒█ ███▒▒▒▒▒███▒▒███▒▒▒▒▒███▒▒███▒▒▒▒▒█▒▒███▒▒▒▒▒███ ▒███ ▒███ ▒███ █ ▒ ▒███ ▒▒▒ ▒███ ▒███ ▒███ █ ▒ ▒███ ▒███ ▒███ ▒███ ▒██████ ▒▒█████████ ▒██████████ ▒██████ ▒██████████ ▒▒███ ███ ▒███▒▒█ ▒▒▒▒▒▒▒▒███ ▒███▒▒▒▒▒▒ ▒███▒▒█ ▒███▒▒▒▒▒███ ▒▒▒█████▒ ▒███ ▒ █ ███ ▒███ ▒███ ▒███ ▒ █ ▒███ ▒███ ▒▒███ ██████████▒▒█████████ █████ ██████████ █████ █████ ▒▒▒ ▒▒▒▒▒▒▒▒▒▒ ▒▒▒▒▒▒▒▒▒ ▒▒▒▒▒ ▒▒▒▒▒▒▒▒▒▒ ▒▒▒▒▒ ▒▒▒▒▒ * ═══════════════════════════════════════════════════════════════════════════════════ * Project VESPER - BELL AUTOMATION SYSTEM - Main Firmware Entry Point * ═══════════════════════════════════════════════════════════════════════════════════ * * 🔔 DESCRIPTION: * High-precision automated bell control system with multi-protocol communication, * real-time telemetry, OTA updates, and modular hardware abstraction. * * 🏗️ ARCHITECTURE: * Clean modular design with dependency injection and proper separation of concerns. * Each major system is encapsulated in its own class with well-defined interfaces. * * 🎯 KEY FEATURES: * ✅ Microsecond-precision bell timing (BellEngine) * ✅ Multi-hardware support (PCF8574, GPIO, Mock) * ✅ Dual network connectivity (Ethernet + WiFi + Permanent AP Mode) * ✅ Multi-protocol communication (MQTT + WebSocket + HTTP REST API) * ✅ Web settings interface for network mode switching * ✅ Real-time telemetry and load monitoring * ✅ Over-the-air firmware updates * ✅ SD card configuration and file management * ✅ NTP time synchronization * ✅ Comprehensive logging system * * 📡 COMMUNICATION PROTOCOLS: * • MQTT (SSL/TLS via AsyncMqttClient on Core 0) * • WebSocket (Real-time web interface) * • HTTP REST API (Command execution via HTTP) * • UDP Discovery (Auto-discovery service) * • HTTP/HTTPS (OTA updates) * * 🔧 HARDWARE ABSTRACTION: * OutputManager provides clean interface for different relay systems: * - PCF8574OutputManager: I2C GPIO expander (8 outputs, 6 on Kincony A6 Board) * - GPIOOutputManager: Direct ESP32 pins (for DIY projects) * - MockOutputManager: Testing without hardware * * ⚡ PERFORMANCE: * High-priority FreeRTOS tasks ensure microsecond timing precision. * Core 1 dedicated to BellEngine for maximum performance. * * ═══════════════════════════════════════════════════════════════════════════════════ */ // Firmware version is defined in Version.hpp (FW_VERSION) // ═══════════════════════════════════════════════════════════════════════════════════ // SYSTEM LIBRARIES - Core ESP32 and Arduino functionality // ═══════════════════════════════════════════════════════════════════════════════════ #include // SD card file system operations #include // File system base class #include // Ethernet connectivity (W5500 support) #include // SPI communication protocol #include // Arduino core framework #include // WiFi connectivity management #include // HTTP client for OTA updates #include // Firmware update utilities #include // I2C communication protocol #include // Task watchdog timer // ═══════════════════════════════════════════════════════════════════════════════════ // NETWORKING LIBRARIES - Advanced networking and communication // ═══════════════════════════════════════════════════════════════════════════════════ #include // WiFi configuration portal #include // Async web server for WebSocket support #include // UDP for discovery service // ═══════════════════════════════════════════════════════════════════════════════════ // DATA PROCESSING LIBRARIES - JSON parsing and data structures // ═══════════════════════════════════════════════════════════════════════════════════ #include // Efficient JSON processing #include // STL string support // ═══════════════════════════════════════════════════════════════════════════════════ // HARDWARE LIBRARIES - Peripheral device control // ═══════════════════════════════════════════════════════════════════════════════════ #include // I2C GPIO expander for relay control #if HAS_RTC #include // Real-time clock functionality #endif // ═══════════════════════════════════════════════════════════════════════════════════ // CUSTOM CLASSES - Include Custom Classes and Functions // ═══════════════════════════════════════════════════════════════════════════════════ #include "SDCardMutex/SDCardMutex.hpp" // ⚠️ MUST be included before any SD-using classes #include "ConfigManager/ConfigManager.hpp" #if HAS_SD_CARD #include "FileManager/FileManager.hpp" #endif #if HAS_RTC #include "TimeKeeper/TimeKeeper.hpp" #endif #include "Logging/Logging.hpp" #include "Telemetry/Telemetry.hpp" #include "OTAManager/OTAManager.hpp" #include "Networking/Networking.hpp" #include "Communication/CommunicationRouter/CommunicationRouter.hpp" #include "ClientManager/ClientManager.hpp" #include "Communication/ResponseBuilder/ResponseBuilder.hpp" #include "Player/Player.hpp" #include "BellEngine/BellEngine.hpp" #include "OutputManager/OutputManager.hpp" #if FEATURE_RS485 #include "Rs485OutputManager/Rs485OutputManager.hpp" #endif #include "HealthMonitor/HealthMonitor.hpp" #include "FirmwareValidator/FirmwareValidator.hpp" #include "InputManager/InputManager.hpp" #include "SettingsWebServer/SettingsWebServer.hpp" #include "Version.hpp" #include "NvsMigration/NvsMigration.hpp" #if HAS_RF #include "RFRemote/RFRemote.hpp" #endif #define TAG "Main" // Class Constructors ConfigManager configManager; #if HAS_SD_CARD FileManager fileManager(&configManager); #endif #if HAS_RTC Timekeeper timekeeper; #endif Telemetry telemetry; OTAManager otaManager(configManager); Player player; AsyncWebServer server(80); AsyncWebSocket ws("/ws"); AsyncUDP udp; Networking networking(configManager); CommunicationRouter communication(configManager, otaManager, networking, server, ws, udp); SettingsWebServer settingsWebServer(server, configManager, networking); HealthMonitor healthMonitor; FirmwareValidator firmwareValidator; InputManager inputManager; #if HAS_RF RFRemote rfRemote; #endif // 🔥 OUTPUT SYSTEM // The concrete OutputManager implementation is selected at compile time via the // variant header. All other code references the base OutputManager& type only. #if FEATURE_RS485 // ── Waveshare 16CH RS485 Modbus RTU (bespoke-rs485 build) ───────────────────── // Pins and baud come from variants/bespoke_rs485.hpp via RS485_TX_PIN etc. Rs485OutputManager outputManager; #else // ── PCF8574/PCF8575 I2C expander (standard Vesper / Agnus builds) ───────────── // Option 1: Single PCF8574 (6 active outputs out of 8 max) — Vesper v1 default PCF8574OutputManager outputManager(0x24, ChipType::PCF8574, 6); // Option 2: Single PCF8575 (8 active outputs out of 16 max) //PCF8574OutputManager outputManager(0x24, ChipType::PCF8575, 8); // Option 3: PCF8574 + PCF8575 (6 + 8 = 14 total virtual outputs) //PCF8574OutputManager outputManager(0x24, ChipType::PCF8574, 6, 0x21, ChipType::PCF8575, 8); // Option 4: Dual PCF8575 (8 + 8 = 16 total virtual outputs) //PCF8574OutputManager outputManager(0x24, ChipType::PCF8575, 8, 0x21, ChipType::PCF8575, 8); #endif BellEngine bellEngine(player, configManager, telemetry, outputManager); // 🔥 THE ULTIMATE BEAST! TaskHandle_t bellEngineHandle = NULL; // Legacy - will be removed #if HAS_RTC TimerHandle_t schedulerTimer; TimerHandle_t ntpSyncTimer; // Non-blocking delayed NTP sync timer #endif // ═══════════════════════════════════════════════════════════════════════════════════ // BOOT-PHASE OTA CHECK // ═══════════════════════════════════════════════════════════════════════════════════ // Runs ONCE at the very start of setup(), before any subsystem, task, or timer is // created. No FreeRTOS contention, maximum heap available, minimum moving parts. // // Flow: // 1. Wait up to 10s for WiFi to associate using saved credentials. // If WiFi never connects → return immediately, boot continues normally. // 2. GET version metadata from each configured server in order. // If all servers fail → return immediately, boot continues normally. // 3. If available version > current version → stream firmware directly to flash // and call ESP.restart(). Never returns on a successful update. // 4. If no update needed → return immediately, boot continues normally. // // The running OTAManager (which starts later) handles runtime checks, manual // MQTT commands, and the 3 AM scheduled check. The two never run concurrently. // ═══════════════════════════════════════════════════════════════════════════════════ static void bootOtaCheck() { Serial.println("[BootOTA] Starting boot-phase OTA check..."); // ── 1. Connect WiFi ────────────────────────────────────────────────────────── if (WiFi.status() != WL_CONNECTED) { // Use saved credentials stored by WiFiManager / Networking subsystem WiFi.mode(WIFI_STA); WiFi.begin(); // resumes last saved SSID+password from flash const unsigned long wifiTimeout = 10000; unsigned long wifiStart = millis(); while (WiFi.status() != WL_CONNECTED && millis() - wifiStart < wifiTimeout) { delay(200); } } if (WiFi.status() != WL_CONNECTED) { Serial.println("[BootOTA] WiFi unavailable — skipping boot OTA check"); return; } Serial.printf("[BootOTA] WiFi connected: %s\n", WiFi.localIP().toString().c_str()); // ── 2. Fetch version metadata ───────────────────────────────────────────────── std::vector servers = configManager.getUpdateServers(); if (servers.empty()) { Serial.println("[BootOTA] No update servers configured — skipping"); return; } String channel = configManager.getOtaChannel(); String hwType = configManager.getHardwareVariant(); String hwVersion = configManager.getHwVersion(); String currentVersionStr = String(FW_VERSION); SemVer currentVersion = SemVer::parse(currentVersionStr); String availableVersionStr; String firmwareDownloadPath; size_t expectedSize = 0; bool metadataOk = false; for (size_t i = 0; i < servers.size() && !metadataOk; i++) { // URL: GET {base}/api/firmware/{hw_type}/{channel}/latest?hw_version=X¤t_version=Y String url = servers[i] + "/api/firmware/" + hwType + "/" + channel + "/latest?hw_version=" + hwVersion + "¤t_version=" + currentVersionStr; Serial.printf("[BootOTA] Trying server %d/%d: %s\n", i + 1, servers.size(), url.c_str()); HTTPClient http; http.setTimeout(8000); // 8s — tight but enough for a small JSON response http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS); http.begin(url); int code = http.GET(); if (code != HTTP_CODE_OK) { Serial.printf("[BootOTA] Server %d returned HTTP %d — trying next\n", i + 1, code); http.end(); continue; } String body = http.getString(); http.end(); DynamicJsonDocument doc(1024); if (deserializeJson(doc, body) != DeserializationError::Ok) { Serial.printf("[BootOTA] Server %d: JSON parse failed — trying next\n", i + 1); continue; } const char* versionStr = doc["version"] | ""; if (strlen(versionStr) == 0) { Serial.printf("[BootOTA] Server %d: missing 'version' field — trying next\n", i + 1); continue; } // Validate checksum field is present and well-formed (64-char SHA256 hex) const char* sha256 = doc["sha256"] | ""; if (strlen(sha256) != 64) { Serial.printf("[BootOTA] Server %d: invalid sha256 length %d — trying next\n", i + 1, strlen(sha256)); continue; } availableVersionStr = String(versionStr); expectedSize = doc["size"] | (size_t)0; firmwareDownloadPath = doc["download_url"] | String(""); metadataOk = true; Serial.printf("[BootOTA] Server %d: metadata OK — available=%s current=%s\n", i + 1, availableVersionStr.c_str(), currentVersionStr.c_str()); } if (!metadataOk) { Serial.println("[BootOTA] All servers failed to return metadata — skipping"); return; } // ── 3. Compare versions ─────────────────────────────────────────────────────── SemVer availableVersion = SemVer::parse(availableVersionStr); if (!(availableVersion > currentVersion)) { Serial.println("[BootOTA] Firmware is up to date — continuing normal boot"); return; } Serial.printf("[BootOTA] Update available: %s → %s — starting flash\n", currentVersionStr.c_str(), availableVersionStr.c_str()); // ── 4. Stream firmware directly to flash ────────────────────────────────────── // Try each server in order until one succeeds. for (size_t i = 0; i < servers.size(); i++) { String firmwareUrl; if (firmwareDownloadPath.length() > 0) { firmwareUrl = servers[i] + firmwareDownloadPath; } else { firmwareUrl = servers[i] + "/api/firmware/" + hwType + "/" + channel + "/" + availableVersionStr + "/firmware.bin"; } Serial.printf("[BootOTA] Downloading from server %d/%d: %s\n", i + 1, servers.size(), firmwareUrl.c_str()); HTTPClient http; http.setTimeout(60000); // 60s for a ~1.4MB binary http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS); http.begin(firmwareUrl); int code = http.GET(); if (code != HTTP_CODE_OK) { Serial.printf("[BootOTA] Server %d firmware download HTTP %d — trying next\n", i + 1, code); http.end(); continue; } int contentLength = http.getSize(); if (contentLength <= 0) { Serial.println("[BootOTA] Invalid content-length — trying next server"); http.end(); continue; } if (expectedSize > 0 && (size_t)contentLength != expectedSize) { Serial.printf("[BootOTA] Size mismatch: expected %u got %d — trying next\n", expectedSize, contentLength); http.end(); continue; } if (!Update.begin(contentLength)) { Serial.println("[BootOTA] Update.begin() failed — not enough space"); http.end(); return; // Partition problem — no point trying other servers } Serial.printf("[BootOTA] Writing %d bytes to flash...\n", contentLength); WiFiClient* stream = http.getStreamPtr(); static uint8_t buf[4096]; // static: off the stack size_t written = 0; size_t lastLoggedPct = 0; while (http.connected() && written < (size_t)contentLength) { size_t avail = stream->available(); if (avail) { size_t toRead = min(avail, sizeof(buf)); size_t bytesRead = stream->readBytes(buf, toRead); if (bytesRead > 0) { if (Update.write(buf, bytesRead) != bytesRead) { Serial.println("[BootOTA] Flash write error — aborting"); Update.abort(); http.end(); goto nextServer; // try next server } written += bytesRead; size_t pct = (written * 100) / contentLength; if (pct >= lastLoggedPct + 20) { Serial.printf("[BootOTA] Progress: %u%% (%u / %d bytes)\n", pct, written, contentLength); lastLoggedPct = pct; } } } else { delay(1); } } http.end(); if (written != (size_t)contentLength) { Serial.printf("[BootOTA] Incomplete write: %u / %d bytes — trying next\n", written, contentLength); Update.abort(); goto nextServer; } if (Update.end(true) && Update.isFinished()) { Serial.println("[BootOTA] Flash complete. Rebooting..."); delay(500); ESP.restart(); return; // unreachable } else { Serial.printf("[BootOTA] Update.end() failed: %s\n", Update.errorString()); goto nextServer; } nextServer:; } // All servers failed during flash — log and continue normal boot. // The device is still running the old firmware; OTAManager will retry later. Serial.println("[BootOTA] All servers failed during flash — continuing normal boot"); } // Called at 5s hold: wipe WiFi credentials only (restart triggered on release) void handleWiFiCredsReset() { LOG_WARNING(TAG, "Factory Reset: WiFi credentials cleared (5s press)"); networking.clearWiFiCredentials(); } // Called on release after 5s but before 10s: restart after WiFi wipe void handleWiFiCredsResetRelease() { LOG_WARNING(TAG, "Factory Reset: Restarting after WiFi credentials wipe"); delay(1000); ESP.restart(); } // Called at 10s hold: WiFi creds were already cleared at 5s, now clear all settings too void handleFactoryReset() { LOG_WARNING(TAG, "Factory Reset: Full reset triggered (10s press)"); configManager.resetAllToDefaults(); delay(1000); ESP.restart(); } #if HAS_RTC // One-shot task to perform NTP sync outside the Tmr Svc context static void ntpSyncTask(void* param) { LOG_DEBUG(TAG, "Network stabilization complete - starting NTP sync"); if (!networking.isInAPMode()) { timekeeper.syncTimeWithNTP(); // Log boot event now that we have a real timestamp telemetry.logBootEvent((uint32_t)timekeeper.getTime()); } vTaskDelete(NULL); } // Non-blocking NTP sync timer callback — defers work to a task (Tmr Svc stack is only 2KB) void ntpSyncTimerCallback(TimerHandle_t xTimer) { // Task creation can fail on a fragmented heap — re-arm the one-shot timer // and retry in 3s instead of silently skipping the sync. if (xTaskCreate(ntpSyncTask, "ntpSync", 5120, NULL, 5, NULL) != pdPASS) { xTimerStart(xTimer, 0); } } #endif void setup() { // Initialize Serial Communications (for debugging) & I2C Bus (for Hardware Control) Serial.begin(115200); Serial.print("BellSystems Firmware Booting - Version "); Serial.println(FW_VERSION); // ── NVS schema migration ───────────────────────────────────────────────── // Must run before ConfigManager::begin() so it sees the new key names. // Safe to run on every boot — exits immediately if schema is already current. // Remove this call (and NvsMigration.*) once all devices have passed through // firmware 1.9.x via the staged OTA upgrade chain. NvsMigration::run(); Wire.begin(4,15); auto& hwConfig = configManager.getHardwareConfig(); SPI.begin(hwConfig.ethSpiSck, hwConfig.ethSpiMiso, hwConfig.ethSpiMosi); delay(50); // 🔒 CRITICAL: Initialize SD Card Mutex BEFORE any SD operations // This prevents concurrent SD access from multiple FreeRTOS tasks if (!SDCardMutex::getInstance().begin()) { Serial.println("❌ FATAL: Failed to initialize SD card mutex!"); Serial.println(" System cannot continue safely - entering infinite loop"); while(1) { delay(1000); } // Halt system - unsafe to proceed } Serial.println("✅ SD card mutex initialized"); // Initialize Configuration (loads factory identity from NVS + user settings from SD) configManager.begin(); // ── BOOT-PHASE OTA CHECK ───────────────────────────────────────────────────── // Must run before any subsystem, task, or timer is created so the full heap // is available and there is zero FreeRTOS contention during the flash write. // If an update is applied this call never returns (device reboots). // If WiFi is unavailable or the server is unreachable it returns immediately. bootOtaCheck(); // ───────────────────────────────────────────────────────────────────────────── // Log levels are applied by CommunicationRouter::begin() once all three channels // (serial, MQTT, SD) and the MQTT callback are properly configured together. inputManager.begin(); inputManager.setFactoryResetMediumPressCallback(handleWiFiCredsReset); inputManager.setFactoryResetMediumPressReleaseCallback(handleWiFiCredsResetRelease); inputManager.setFactoryResetLongPressCallback(handleFactoryReset); // ═══════════════════════════════════════════════════════════════════════════════ // REMOVED: Manual device identity setters // Device identity (UID, hwType, hwVersion) is now READ-ONLY in production firmware // These values are set by factory firmware and stored permanently in NVS // Production firmware loads them once at boot and keeps them in RAM // ═══════════════════════════════════════════════════════════════════════════════ // Update firmware version (this is the ONLY identity field that can be set) LOG_INFO(TAG, "Firmware version: %s", FW_VERSION); // Display device information after configuration is loaded Serial.println("\n=== DEVICE IDENTITY ==="); Serial.printf("Device UID: %s\n", configManager.getDeviceUID().c_str()); Serial.printf("Hardware Type: %s\n", configManager.getHwType().c_str()); Serial.printf("Hardware Version: %s\n", configManager.getHwVersion().c_str()); Serial.printf("Firmware Version: %s\n", configManager.getFwVersion().c_str()); Serial.printf("AP SSID: %s\n", configManager.getAPSSID().c_str()); Serial.println("=====================\n"); // 🔥 CRITICAL: Initialize Health Monitor FIRST (required for firmware validation) healthMonitor.begin(); // Register all subsystems with health monitor for continuous monitoring healthMonitor.setConfigManager(&configManager); #if HAS_SD_CARD healthMonitor.setFileManager(&fileManager); #endif // Initialize Output Manager - 🔥 THE NEW WAY! outputManager.setConfigManager(&configManager); if (!outputManager.initialize()) { LOG_ERROR(TAG, "Failed to initialize OutputManager!"); // Continue anyway for now } // Register OutputManager with health monitor healthMonitor.setOutputManager(&outputManager); // Initialize BellEngine early for health validation bellEngine.begin(); healthMonitor.setBellEngine(&bellEngine); delay(100); // 🔥 BULLETPROOF: Initialize Firmware Validator and perform startup validation firmwareValidator.begin(&healthMonitor, &configManager); delay(100); // 💀 CRITICAL SAFETY CHECK: Perform startup validation // This MUST happen early before initializing other subsystems if (!firmwareValidator.performStartupValidation()) { // If we reach here, startup validation failed and rollback was triggered // The system should reboot automatically to the previous firmware LOG_ERROR(TAG, "💀 STARTUP VALIDATION FAILED - SYSTEM HALTED"); while(1) { delay(1000); } // Should not reach here } LOG_INFO(TAG, "✅ Firmware startup validation PASSED - proceeding with initialization"); // Initialize remaining subsystems... // SD Card initialization is now handled by ConfigManager #if HAS_RTC // Initialize timekeeper with NO clock outputs timekeeper.begin(); // No parameters needed // Connect the timekeeper to dependencies (CLEAN!) timekeeper.setOutputManager(&outputManager); timekeeper.setConfigManager(&configManager); timekeeper.setNetworking(&networking); timekeeper.setPlayer(&player); // 🔥 Connect for playback coordination // Clock outputs now configured via ConfigManager/Communication commands // Register TimeKeeper with health monitor healthMonitor.setTimeKeeper(&timekeeper); #endif // Initialize Telemetry telemetry.setPlayerReference(&player.isPlaying); // 🚑 CRITICAL: Connect force stop callback for overload protection! telemetry.setForceStopCallback([]() { player.forceStop(); }); #if HAS_SD_CARD telemetry.setFileManager(&fileManager); #endif telemetry.begin(); // Register Telemetry with health monitor healthMonitor.setTelemetry(&telemetry); // Initialize Networking (handles everything automatically) networking.begin(); // Register Networking with health monitor healthMonitor.setNetworking(&networking); // Initialize Player player.begin(); // Register Player with health monitor healthMonitor.setPlayer(&player); // BellEngine already initialized and registered earlier for health validation // Initialize Communication Manager // Set all dependency references BEFORE begin() so that registerHandlers() // (called inside begin()) can construct every domain handler. communication.setPlayerReference(&player); #if HAS_SD_CARD communication.setFileManagerReference(&fileManager); #endif #if HAS_RTC communication.setTimeKeeperReference(&timekeeper); #endif communication.setFirmwareValidatorReference(&firmwareValidator); communication.setTelemetryReference(&telemetry); communication.setHealthMonitorReference(&healthMonitor); communication.setOutputManagerReference(&outputManager); #if HAS_RF communication.setRFRemoteReference(&rfRemote); #endif communication.begin(); #if HAS_SD_CARD player.setDependencies(&communication, &fileManager); #else player.setDependencies(&communication, nullptr); #endif player.setBellEngine(&bellEngine); // Connect the beast! player.setTelemetry(&telemetry); #if HAS_RTC player.setTimekeeper(&timekeeper); // 🔥 Connect for alert coordination #endif // Register Communication with health monitor healthMonitor.setCommunication(&communication); // 🔔 CONNECT BELLENGINE TO COMMUNICATION FOR DING NOTIFICATIONS! bellEngine.setCommunicationManager(&communication); // Track if AsyncWebServer has been started to prevent duplicates static bool webServerStarted = false; #if HAS_RTC // Create NTP sync timer (one-shot, 3 second delay for network stabilization) ntpSyncTimer = xTimerCreate( "NTPSync", // Timer name pdMS_TO_TICKS(3000), // 3 second delay (network stabilization) pdFALSE, // One-shot timer (not auto-reload) NULL, // Timer ID (not used) ntpSyncTimerCallback // Callback function ); #endif // Set up network callbacks networking.setNetworkCallbacks( [&webServerStarted]() { communication.onNetworkConnected(); #if HAS_RTC // Schedule non-blocking NTP sync after 3s network stabilization (like MQTT) // Skip NTP sync in AP mode (no internet connection) if (!networking.isInAPMode() && ntpSyncTimer) { LOG_DEBUG(TAG, "Network connected - scheduling NTP sync after 3s stabilization (non-blocking)"); xTimerStart(ntpSyncTimer, 0); } #endif // Start AsyncWebServer when network becomes available (only once!) if (!webServerStarted && networking.getState() != NetworkState::WIFI_PORTAL_MODE) { settingsWebServer.begin(); LOG_INFO(TAG, "🚀 Starting AsyncWebServer on port 80..."); server.begin(); LOG_INFO(TAG, "✅ AsyncWebServer started on http://%s", networking.getLocalIP().c_str()); webServerStarted = true; } }, // onConnected []() { communication.onNetworkDisconnected(); } // onDisconnected ); // If already connected, trigger MQTT connection and setup manually if (networking.isConnected()) { LOG_INFO(TAG, "Network already connected - initializing services"); communication.onNetworkConnected(); #if HAS_RTC // Schedule non-blocking NTP sync after 3s network stabilization (like MQTT) // Skip NTP sync in AP mode (no internet connection) if (!networking.isInAPMode() && ntpSyncTimer) { LOG_DEBUG(TAG, "Network already connected - scheduling NTP sync after 3s stabilization (non-blocking)"); xTimerStart(ntpSyncTimer, 0); } #endif // 🔥 CRITICAL: Start AsyncWebServer ONLY when network is ready // Do NOT start if WiFiManager portal is active (port 80 conflict!) if (!webServerStarted && networking.getState() != NetworkState::WIFI_PORTAL_MODE) { settingsWebServer.begin(); LOG_INFO(TAG, "🚀 Starting AsyncWebServer on port 80..."); server.begin(); LOG_INFO(TAG, "✅ AsyncWebServer started on http://%s", networking.getLocalIP().c_str()); webServerStarted = true; } } else { LOG_WARNING(TAG, "⚠️ Network not ready - services will start after connection"); } // Initialize OTA Manager otaManager.begin(); #if HAS_SD_CARD otaManager.setFileManager(&fileManager); #endif otaManager.setPlayer(&player); // Set player reference for idle check #if HAS_RTC otaManager.setTimeKeeper(&timekeeper); // Set timekeeper reference for freeze mode #endif otaManager.setTelemetry(&telemetry); // Set telemetry reference for freeze mode // 🔥 FIX: OTA check will happen asynchronously via scheduled timer (no blocking delay) // UDP discovery setup can happen immediately without conflicts communication.setupUdpDiscovery(); // Register OTA Manager with health monitor healthMonitor.setOTAManager(&otaManager); #if HAS_RF // Initialize RF remote receiver rfRemote.begin(&player); healthMonitor.setRFRemote(&rfRemote); #endif // Note: AsyncWebServer will be started by network callbacks when connection is ready // This avoids port 80 conflicts with WiFiManager's captive portal // 🔥 START RUNTIME VALIDATION: All subsystems are now initialized // Begin extended runtime validation if we're in testing mode if (firmwareValidator.isInTestingMode()) { LOG_INFO(TAG, "🏃 Starting runtime validation - firmware will be tested for %lu seconds", firmwareValidator.getValidationConfig().runtimeTimeoutMs / 1000); firmwareValidator.startRuntimeValidation(); } else { LOG_INFO(TAG, "✅ Firmware already validated - normal operation mode"); } // ═══════════════════════════════════════════════════════════════════════════════ // INITIALIZATION COMPLETE // ═══════════════════════════════════════════════════════════════════════════════ // ✅ All automatic task creation handled by individual components: // • BellEngine creates high-priority timing task on Core 1 // • Telemetry creates monitoring task for load tracking // • Player creates duration timer for playback control // • Communication creates MQTT task on Core 0 with PubSubClient // • Networking creates connection management timers // ✅ Bell configuration automatically loaded by ConfigManager // ✅ System ready for MQTT commands, WebSocket connections, and UDP discovery } // ███████████████████████████████████████████████████████████████████████████████████ // █ MAIN LOOP █ // ███████████████████████████████████████████████████████████████████████████████████ // The main loop is intentionally kept minimal in this architecture. All critical // functionality runs in dedicated FreeRTOS tasks for optimal performance and timing. // This ensures the main loop doesn't interfere with precision bell timing. /** * @brief Main execution loop - Minimal by design * * In the new modular architecture, all heavy lifting is done by dedicated tasks: * • BellEngine: High-priority task on Core 1 for microsecond timing * • Telemetry: Background monitoring task for system health * • Player: Timer-based duration control for melody playback * • Communication: MQTT task on Core 0 + Event-driven WebSocket * • Networking: Automatic connection management * * The main loop only handles lightweight operations that don't require * precise timing or could benefit from running on Core 0. * * @note This loop runs on Core 0 and should remain lightweight to avoid * interfering with the precision timing on Core 1. */ void loop() { // Feed watchdog only during firmware validation if (firmwareValidator.isInTestingMode()) { esp_task_wdt_reset(); } else { // Remove task from watchdog if validation completed static bool taskRemoved = false; if (!taskRemoved) { esp_task_wdt_delete(NULL); // Remove current task taskRemoved = true; } } // 🔥 CRITICAL: Clean up dead WebSocket connections every 2 seconds // This prevents ghost connections from blocking new clients static unsigned long lastWsCleanup = 0; if (millis() - lastWsCleanup > 2000) { ws.cleanupClients(); lastWsCleanup = millis(); } // Process UART command input from external devices (LCD panel, buttons) communication.loop(); static unsigned long lastLog = 0; if (millis() - lastLog > 10000) { LOG_VERBOSE(TAG, "❤️ Loop alive | Free heap: %d bytes (%.1f KB) | Min free: %d | Largest block: %d", ESP.getFreeHeap(), ESP.getFreeHeap() / 1024.0, ESP.getMinFreeHeap(), ESP.getMaxAllocHeap()); lastLog = millis(); } // Keep the loop responsive but not busy delay(100); // ⏱️ 100ms delay to prevent busy waiting }