From ed1123283bf08c1dc08e2118dc334f91ff9eecd1 Mon Sep 17 00:00:00 2001 From: bonamin Date: Sat, 18 Apr 2026 20:48:26 +0300 Subject: [PATCH] feat: boot-phase OTA, RS485 variant, async melody download, HAL guards MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - bootOtaCheck() runs at top of setup() before any task/timer; streams firmware to flash on update, reboots, otherwise returns immediately - New bespoke-rs485-v1 build env + Rs485OutputManager for Waveshare 16CH Modbus RTU relay; vesper.hpp renamed vesper-std.hpp, env renamed accordingly - Player: permanent melodyDownloadTaskFn task; fast path (built-in/SD) before async download; uid accepted as alias for pid - CommunicationRouter: HAS_UART guards throughout so UART transport compiles out when Serial2 is claimed by Modbus - OTAManager: stack 8KB→16KB, pinned to Core 1, HTTPClient recreated per retry, download timeout 30s→60s - FileManager: heap guard before SSL alloc; watchdog log cleanup - ConfigManager: OTA fallback URLs http (no TLS for firmware servers) - agnus.hpp: HAS_UART 1 added - provisioning/nvs_agnus_lab_device.csv added - Version bumped to v2.0.1 Co-Authored-By: Claude Sonnet 4.6 --- docs/dev/features-scratch.md | 2 + platformio.ini | 48 +++- provisioning/nvs_agnus_lab_device.csv | 5 + .../CommunicationRouter.cpp | 10 + .../CommunicationRouter.hpp | 10 + src/ConfigManager/ConfigManager.hpp | 4 +- src/FileManager/FileManager.cpp | 16 +- src/FileManager/FileManager.hpp | 1 - src/OTAManager/OTAManager.cpp | 77 +++-- src/OTAManager/OTAManager.hpp | 1 + src/Player/Player.cpp | 70 ++++- src/Player/Player.hpp | 6 + src/Rs485OutputManager/Rs485OutputManager.cpp | 237 ++++++++++++++++ src/Rs485OutputManager/Rs485OutputManager.hpp | 121 ++++++++ src/Version.hpp | 3 +- src/main.cpp | 268 +++++++++++++++++- variants/agnus.hpp | 3 + variants/bespoke_rs485.hpp | 58 ++++ variants/{vesper.hpp => vesper-std.hpp} | 3 + 19 files changed, 871 insertions(+), 72 deletions(-) create mode 100644 provisioning/nvs_agnus_lab_device.csv create mode 100644 src/Rs485OutputManager/Rs485OutputManager.cpp create mode 100644 src/Rs485OutputManager/Rs485OutputManager.hpp create mode 100644 variants/bespoke_rs485.hpp rename variants/{vesper.hpp => vesper-std.hpp} (92%) diff --git a/docs/dev/features-scratch.md b/docs/dev/features-scratch.md index 823c5b8..560a6a9 100644 --- a/docs/dev/features-scratch.md +++ b/docs/dev/features-scratch.md @@ -7,7 +7,9 @@ vesper//kiosk/event // Kiosk Mode Events vesper//kiosk/info // Kiosk Mode General Info // WiFi Local AP + BellSystemsInfra + v3sp3r_8998! diff --git a/platformio.ini b/platformio.ini index a6e1363..c39b477 100644 --- a/platformio.ini +++ b/platformio.ini @@ -54,16 +54,19 @@ lib_deps = ; RF remote receiver (433MHz, RCSwitch protocol) sui77/rc-switch @ ^2.6.4 + ; Modbus RTU master (used by Rs485OutputManager for bespoke-rs485 build) + 4-20ma/ModbusMaster @ ^2.0.1 + build_flags_common = -std=gnu++14 -DCORE_DEBUG_LEVEL=0 -DCONFIG_ASYNC_TCP_RUNNING_CORE=0 ; ─────────────────────────────────────────────────────────────────────────────── -; VESPER v1 — Kincony KC868-A6 (ESP32-D0WD-V3, 4MB Flash) +; VESPER Standard v1 — Kincony KC868-A6 (ESP32-D0WD-V3, 4MB Flash) ; Current production board ; ─────────────────────────────────────────────────────────────────────────────── -[env:vesper-v1] +[env:vesper-std-v1] platform = ${common.platform} framework = ${common.framework} board = esp32dev @@ -95,8 +98,8 @@ board_build.cmake_extra_args = -DCONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=4096 build_flags = ${common.build_flags_common} -DPSRAM_ENABLED=0 - -DMQTT_SECRET=\"change-me-in-platformio-ini\" - -include variants/vesper.hpp + -DMQTT_SECRET=\"deea8b2dbf21872bff8b4639ca16d0348358945ccd4c1cb6c5934ba510de1dce\" + -include variants/vesper-std.hpp lib_deps = ${common.lib_deps} @@ -122,7 +125,7 @@ board_build.cmake_extra_args = -DCONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=4096 build_flags = ${common.build_flags_common} -DPSRAM_ENABLED=0 - -DMQTT_SECRET=\"change-me-in-platformio-ini\" + -DMQTT_SECRET=\"deea8b2dbf21872bff8b4639ca16d0348358945ccd4c1cb6c5934ba510de1dce\" -include variants/agnus.hpp lib_deps = ${common.lib_deps} @@ -149,12 +152,45 @@ board_build.cmake_extra_args = -DCONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=4096 build_flags = ${common.build_flags_common} -DPSRAM_ENABLED=0 - -DMQTT_SECRET=\"change-me-in-platformio-ini\" + -DMQTT_SECRET=\"deea8b2dbf21872bff8b4639ca16d0348358945ccd4c1cb6c5934ba510de1dce\" -include variants/agnus.hpp lib_deps = ${common.lib_deps} +; ─────────────────────────────────────────────────────────────────────────────── +; BESPOKE RS485 v1 — Vesper base board + Waveshare 16CH RS485 Modbus RTU relay +; +; One-off build for a single client requiring 16 outputs. The internal PCF8574 +; relays on the KC868-A6 are NOT used. All outputs go through the Waveshare board +; via UART2 RS485 (GPIO27 TX, GPIO14 RX, MAX13487EESA auto-direction transceiver). +; +; OTA updates for this device must be built from THIS environment only. +; Other environments are unaffected — Rs485OutputManager is dead code for them +; since FEATURE_RS485 is not set. +; ─────────────────────────────────────────────────────────────────────────────── +[env:bespoke-rs485-v1] +platform = ${common.platform} +framework = ${common.framework} +board = esp32dev + +monitor_speed = ${common.monitor_speed} +upload_speed = 921600 +upload_protocol = esptool + +board_build.partitions = min_spiffs.csv +build_unflags = -std=gnu++11 +board_build.cmake_extra_args = -DCONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=4096 + +build_flags = + ${common.build_flags_common} + -DPSRAM_ENABLED=0 + -DMQTT_SECRET=\"deea8b2dbf21872bff8b4639ca16d0348358945ccd4c1cb6c5934ba510de1dce\" + -include variants/bespoke_rs485.hpp + +lib_deps = ${common.lib_deps} + + ; ─────────────────────────────────────────────────────────────────────────────── ; VESPER+ v1 — Future: adds RF remote support ; ─────────────────────────────────────────────────────────────────────────────── diff --git a/provisioning/nvs_agnus_lab_device.csv b/provisioning/nvs_agnus_lab_device.csv new file mode 100644 index 0000000..5a33aa2 --- /dev/null +++ b/provisioning/nvs_agnus_lab_device.csv @@ -0,0 +1,5 @@ +key,type,encoding,value +device_id,namespace,, +serial,data,string,AG000000000000 +hw_family,data,string,agnus +hw_revision,data,string,01 diff --git a/src/Communication/CommunicationRouter/CommunicationRouter.cpp b/src/Communication/CommunicationRouter/CommunicationRouter.cpp index 7147fc1..1b10dd9 100644 --- a/src/Communication/CommunicationRouter/CommunicationRouter.cpp +++ b/src/Communication/CommunicationRouter/CommunicationRouter.cpp @@ -60,13 +60,17 @@ CommunicationRouter::CommunicationRouter(ConfigManager& configManager, , _mqttClient(configManager, networking) , _clientManager() , _wsServer(webSocket, _clientManager) +#if HAS_UART , _uartHandler() +#endif // New architecture — transports reference the bus , _bus() , _mqttTransport(_mqttClient, _bus) , _wsTransport(_wsServer, _bus) , _httpTransport(server, _bus, configManager) +#if HAS_UART , _uartTransport(_uartHandler, _bus) +#endif , _webServerTransport(server, _bus, configManager, networking) {} @@ -122,15 +126,19 @@ void CommunicationRouter::begin() { LOG_INFO(TAG, "WebServer transport initialised (/settings)"); // ── UART ───────────────────────────────────────────────────────────────── +#if HAS_UART LOG_INFO(TAG, "Setting up UART transport..."); _uartTransport.begin(); LOG_INFO(TAG, "UART transport initialised"); +#endif // ── Register transports with the bus ───────────────────────────────────── _bus.addTransport(&_mqttTransport); _bus.addTransport(&_wsTransport); _bus.addTransport(&_httpTransport); +#if HAS_UART _bus.addTransport(&_uartTransport); +#endif _bus.addTransport(&_webServerTransport); // ── Register all domain handlers ───────────────────────────────────────── @@ -154,7 +162,9 @@ void CommunicationRouter::begin() { // ───────────────────────────────────────────────────────────────────────────── void CommunicationRouter::loop() { +#if HAS_UART _uartTransport.loop(); +#endif } // ───────────────────────────────────────────────────────────────────────────── diff --git a/src/Communication/CommunicationRouter/CommunicationRouter.hpp b/src/Communication/CommunicationRouter/CommunicationRouter.hpp index 796ad52..75af7d0 100644 --- a/src/Communication/CommunicationRouter/CommunicationRouter.hpp +++ b/src/Communication/CommunicationRouter/CommunicationRouter.hpp @@ -21,7 +21,9 @@ // Underlying protocol drivers (still owned here) #include "../Drivers/MQTTDriver/MQTTDriver.hpp" #include "../Drivers/WebSocketDriver/WebSocketDriver.hpp" +#if HAS_UART #include "../Drivers/UARTDriver/UARTDriver.hpp" +#endif #include "../../ClientManager/ClientManager.hpp" // New architecture @@ -29,7 +31,9 @@ #include "../Transport/MQTTTransport/MQTTTransport.hpp" #include "../Transport/WebSocketTransport/WebSocketTransport.hpp" #include "../Transport/HTTPTransport/HTTPTransport.hpp" +#if HAS_UART #include "../Transport/UARTTransport/UARTTransport.hpp" +#endif #include "../Transport/WebServerTransport/WebServerTransport.hpp" // Forward declarations — resolved in .cpp @@ -91,7 +95,9 @@ public: // Legacy accessors used by other subsystems MQTTDriver& getMQTTClient() { return _mqttClient; } +#if HAS_UART UARTDriver& getUARTHandler() { return _uartHandler; } +#endif // Broadcast helpers — called by BellEngine, Player, Telemetry, etc. void broadcastStatus(const String& statusMessage); @@ -158,14 +164,18 @@ private: MQTTDriver _mqttClient; ClientManager _clientManager; WebSocketDriver _wsServer; +#if HAS_UART UARTDriver _uartHandler; +#endif // ── New architecture (owned) ──────────────────────────────────────────── CommandBus _bus; MQTTTransport _mqttTransport; WebSocketTransport _wsTransport; HTTPTransport _httpTransport; +#if HAS_UART UARTTransport _uartTransport; +#endif WebServerTransport _webServerTransport; // Register all domain handlers onto the bus. diff --git a/src/ConfigManager/ConfigManager.hpp b/src/ConfigManager/ConfigManager.hpp index ac38f06..e4dd476 100644 --- a/src/ConfigManager/ConfigManager.hpp +++ b/src/ConfigManager/ConfigManager.hpp @@ -134,8 +134,8 @@ public: */ struct UpdateConfig { String fallbackServerUrls[2] = { - "https://firmware.bellsystems.net", // 🥇 Primary fallback - "https://firmware.bonamin.space" // 🥈 Secondary fallback + "http://firmware.bellsystems.net", // 🥇 Primary fallback + "http://firmware.bonamin.space" // 🥈 Secondary fallback }; int timeout = 10000; // ⏱️ Universal timeout - OK as is int retries = 3; // 🔄 Universal retries - OK as is diff --git a/src/FileManager/FileManager.cpp b/src/FileManager/FileManager.cpp index 2be2df2..d80530c 100644 --- a/src/FileManager/FileManager.cpp +++ b/src/FileManager/FileManager.cpp @@ -1,4 +1,5 @@ #include "FileManager.hpp" +#include #define TAG "FileManager" #include "../BuiltInMelodies/BuiltInMelodies.hpp" @@ -75,6 +76,12 @@ bool FileManager::downloadFile(const String& url, const String& directory, const // Configure HTTP client based on protocol if (isHttps) { + size_t largestBlock = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT); + LOG_DEBUG(TAG, "Largest free heap block before SSL alloc: %u bytes", largestBlock); + if (largestBlock < 40000) { + LOG_ERROR(TAG, "Insufficient contiguous heap for SSL context (%u bytes free, need ~40KB)", largestBlock); + return false; + } secureClient = new WiFiClientSecure(); secureClient->setInsecure(); // Skip certificate validation for Firebase secureClient->setTimeout(15); // 15 second timeout for TLS operations @@ -88,17 +95,12 @@ bool FileManager::downloadFile(const String& url, const String& directory, const http.setTimeout(30000); // 30 second timeout for large files http.setFollowRedirects(HTTPC_FORCE_FOLLOW_REDIRECTS); // Follow redirects automatically - // Disable task watchdog for current task during blocking HTTPS operation - // The TLS handshake can take several seconds and would trigger watchdog - LOG_DEBUG(TAG, "Disabling watchdog for download..."); + // Remove this task from the WDT while the TLS handshake blocks. + // The handshake can take several seconds and would otherwise starve async_tcp. esp_task_wdt_delete(NULL); - LOG_DEBUG(TAG, "Sending HTTP GET request..."); int httpCode = http.GET(); - - // Re-enable task watchdog after HTTP request completes esp_task_wdt_add(NULL); - LOG_DEBUG(TAG, "Watchdog re-enabled after HTTP request"); if (httpCode != HTTP_CODE_OK && httpCode != HTTP_CODE_MOVED_PERMANENTLY && httpCode != HTTP_CODE_FOUND) { LOG_ERROR(TAG, "HTTP GET failed, code: %d, error: %s", httpCode, http.errorToString(httpCode).c_str()); diff --git a/src/FileManager/FileManager.hpp b/src/FileManager/FileManager.hpp index 07b794c..ab0339f 100644 --- a/src/FileManager/FileManager.hpp +++ b/src/FileManager/FileManager.hpp @@ -24,7 +24,6 @@ #include #include #include -#include #include "../Logging/Logging.hpp" #include "../ConfigManager/ConfigManager.hpp" diff --git a/src/OTAManager/OTAManager.cpp b/src/OTAManager/OTAManager.cpp index 97b13fb..b5712a8 100644 --- a/src/OTAManager/OTAManager.cpp +++ b/src/OTAManager/OTAManager.cpp @@ -70,15 +70,17 @@ void OTAManager::begin() { return; } - // Create dedicated worker task with 8KB stack (prevents timer task overflow) + // Create dedicated worker task with 16KB stack. + // Update.write() + HTTPClient + TLS frames + call depth during flash requires ~12-14KB; + // 8KB was silently overflowing during the stream-write phase. BaseType_t taskCreated = xTaskCreatePinnedToCore( otaWorkerTaskFunction, "OTA_Worker", - 8192, // 8KB stack - plenty for HTTP and JSON operations + 16384, // 16KB stack - required for Update.write() + HTTP during flash this, // Pass OTAManager instance 2, // Priority 2 (lower than critical tasks) &_otaWorkerTask, - 0 // Core 0 + 1 // Core 1 — TLS/HTTPS requires Core 1; lwip runs on Core 0 and deadlocks blocking TLS on the same core ); if (taskCreated != pdPASS) { @@ -88,7 +90,7 @@ void OTAManager::begin() { return; } - LOG_INFO(TAG, "OTA worker task created with 8KB stack on Core 0"); + LOG_INFO(TAG, "OTA worker task created with 16KB stack on Core 1"); // Create timer for scheduled checks (checks every minute if it's 3:00 AM) _scheduledCheckTimer = xTimerCreate( @@ -215,15 +217,15 @@ void OTAManager::checkForUpdates(const String& channel) { LOG_WARNING(TAG, "OTA check already in progress"); return; } - + // 🔥 CRITICAL: Check network connectivity before attempting HTTP requests if (WiFi.status() != WL_CONNECTED) { // ETHERNET DISABLED - WiFi only LOG_WARNING(TAG, "OTA check skipped - no network connectivity"); return; } - + setStatus(Status::CHECKING_VERSION); - LOG_INFO(TAG, "Checking for firmware updates in %s channel for %s...", + LOG_INFO(TAG, "Checking for firmware updates in %s channel for %s...", channel.c_str(), _configManager.getHardwareVariant().c_str()); if (checkVersion(channel)) { @@ -319,27 +321,37 @@ bool OTAManager::checkVersion(const String& channel) { LOG_INFO(TAG, "OTA: Trying server %d/%d: %s", serverIndex + 1, servers.size(), metadataUrl.c_str()); - HTTPClient http; - http.setTimeout(updateConfig.timeout); - http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS); - http.begin(metadataUrl.c_str()); - - int retryCount = 0; + String jsonStr; int httpCode = -1; - while (retryCount < updateConfig.retries && httpCode != HTTP_CODE_OK) { + for (int retryCount = 0; retryCount < updateConfig.retries; retryCount++) { if (retryCount > 0) { LOG_INFO(TAG, "OTA: Retry %d/%d for server %d", retryCount + 1, updateConfig.retries, serverIndex + 1); delay(1000 * retryCount); // Exponential backoff } - httpCode = http.GET(); - retryCount++; - } - if (httpCode == HTTP_CODE_OK) { - String jsonStr = http.getString(); + HTTPClient http; + http.setTimeout(updateConfig.timeout); + http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS); + http.begin(metadataUrl); + + httpCode = http.GET(); + + if (httpCode == HTTP_CODE_OK) { + jsonStr = http.getString(); + } http.end(); + if (httpCode == HTTP_CODE_OK) break; + } + + if (httpCode != HTTP_CODE_OK) { + LOG_ERROR(TAG, "OTA: Server %d failed after %d retries. HTTP code: %d", + serverIndex + 1, updateConfig.retries, httpCode); + continue; + } + + { DynamicJsonDocument doc(1024); DeserializationError error = deserializeJson(doc, jsonStr); if (error) { @@ -358,19 +370,16 @@ bool OTAManager::checkVersion(const String& channel) { const char* minVersionStr = doc["min_fw_version"] | ""; _minVersion = (strlen(minVersionStr) > 0) ? SemVer::parse(String(minVersionStr)) : SemVer{0, 0, 0}; - _availableChecksum = doc["sha256"] | ""; - _expectedFileSize = doc["size"] | (size_t)0; + _availableChecksum = doc["sha256"] | ""; + _expectedFileSize = doc["size"] | (size_t)0; _availableDownloadPath = doc["download_url"] | ""; // update_type: "optional" | "mandatory" | "emergency" - // This is the urgency of the release — completely separate from the channel. - // The server derives mandatory/emergency booleans from this for us. - _isMandatory = doc["mandatory"] | false; - _isEmergency = doc["emergency"] | false; - _updateChannel = channel; // channel is what we requested + _isMandatory = doc["mandatory"] | false; + _isEmergency = doc["emergency"] | false; + _updateChannel = channel; // Validate the server actually responded for the channel we asked for. - // The response includes a "channel" field (e.g. "stable", "beta") — use that. const char* serverChannel = doc["channel"] | ""; if (strlen(serverChannel) > 0 && String(serverChannel) != channel) { LOG_ERROR(TAG, "OTA: Channel mismatch! Requested: %s, Got: %s", channel.c_str(), serverChannel); @@ -378,21 +387,16 @@ bool OTAManager::checkVersion(const String& channel) { continue; } - // Validate version parsed correctly if (_availableVersion.isZero()) { LOG_ERROR(TAG, "OTA: Invalid version string '%s' from server %d", versionStr, serverIndex + 1); continue; } - // Validate checksum is a 64-char SHA256 hex string if (_availableChecksum.length() != 64) { LOG_ERROR(TAG, "OTA: Invalid sha256 length (%d) from server %d", _availableChecksum.length(), serverIndex + 1); continue; } - // min_fw_version is informational only — the server already resolved the correct - // next hop for our current_version, so we trust the version it returned. - // We still log it for visibility. SemVer currentVersion = getCurrentVersion(); if (!_minVersion.isZero() && currentVersion < _minVersion) { LOG_WARNING(TAG, "OTA: Server returned version %s with min_fw_version %s — server is handling upgrade chain", @@ -403,11 +407,6 @@ bool OTAManager::checkVersion(const String& channel) { serverIndex + 1, versionStr, _expectedFileSize, _isMandatory ? "YES" : "NO", _isEmergency ? "YES" : "NO"); return true; - - } else { - LOG_ERROR(TAG, "OTA: Server %d failed after %d retries. HTTP code: %d", - serverIndex + 1, updateConfig.retries, httpCode); - http.end(); } } @@ -457,8 +456,8 @@ bool OTAManager::downloadDirectToFlash(const String& url, size_t expectedSize, c HTTPClient http; http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS); - http.begin(url.c_str()); - http.setTimeout(30000); // 30 seconds + http.begin(url); // Let HTTPClient manage TLS internally (same as bootOtaCheck) + http.setTimeout(60000); // 60 seconds for a ~1.4MB binary int httpCode = http.GET(); diff --git a/src/OTAManager/OTAManager.hpp b/src/OTAManager/OTAManager.hpp index 6da83e0..069d449 100644 --- a/src/OTAManager/OTAManager.hpp +++ b/src/OTAManager/OTAManager.hpp @@ -18,6 +18,7 @@ #include #include +#include #include #include #include diff --git a/src/Player/Player.cpp b/src/Player/Player.cpp index 09e8710..fe00412 100644 --- a/src/Player/Player.cpp +++ b/src/Player/Player.cpp @@ -114,6 +114,10 @@ void Player::begin() { // Dedicated task handles deferred stop/pause/resume triggered by the timer callback. // Timer callbacks run on Tmr Svc (tiny stack) so we must not do MQTT/WS work there. xTaskCreate(playerControlTaskFn, "PlayerCtrl", 4096, this, 2, NULL); + + // Permanent download task — created once at boot so its stack is allocated while heap + // is fresh and contiguous. Sleeps until signalled by xTaskNotifyGive(). + xTaskCreate(melodyDownloadTaskFn, "MelodyDL", 8192, this, 3, &_downloadTaskHandle); } void Player::play() { @@ -215,11 +219,45 @@ bool Player::command(JsonVariant data) { setMelodyAttributes(data); if (action == "play") { - if (!loadMelodyInRAM()) { - LOG_WARNING(TAG, "Play command aborted — melody '%s' could not be loaded", pid.c_str()); + String pidStr = String(pid.c_str()); + + // Fast path: melody is already in a built-in or on SD — load and play synchronously + if (!pidStr.isEmpty()) { + _melodySteps.clear(); + bool builtIn = BuiltInMelodies::loadBuiltInMelody(pidStr, _melodySteps); + if (!builtIn) { + String filePath = "/melodies/" + pidStr; + File f = SD.open(filePath.c_str(), FILE_READ); + if (f) { + f.close(); + // File is present — loadMelodyInRAM() will open it properly + _melodySteps.clear(); + if (!loadMelodyInRAM()) { + LOG_WARNING(TAG, "Play command aborted — melody '%s' could not be loaded", pid.c_str()); + return false; + } + play(); + return true; + } + } else { + // Built-in was loaded by the probe above — hand off to play() + play(); + return true; + } + } + + // Slow path: melody needs downloading — offload to a task so we don't block async_tcp + if (pid.empty() || pid == "-") { + LOG_WARNING(TAG, "Play command aborted — PID is empty or invalid"); return false; } - play(); + if (url.empty() || url == "-") { + LOG_WARNING(TAG, "Play command aborted — melody '%s' not found and no download URL", pid.c_str()); + return false; + } + + LOG_INFO(TAG, "Melody '%s' needs download — signalling download task", pid.c_str()); + xTaskNotifyGive(_downloadTaskHandle); return true; } @@ -233,6 +271,8 @@ void Player::setMelodyAttributes(JsonVariant doc) { } if (doc.containsKey("pid")) { pid = doc["pid"].as(); + } else if (doc.containsKey("uid")) { + pid = doc["uid"].as(); } if (doc.containsKey("url")) { url = doc["url"].as(); @@ -283,6 +323,11 @@ bool Player::loadMelodyInRAM() { _melodySteps.clear(); // Always start clean — never play stale data from a previous command String pidStr = String(pid.c_str()); + if (pidStr.isEmpty()) { + LOG_ERROR(TAG, "Cannot load melody: PID is empty"); + return false; + } + // 🎵 PRIORITY 1: Check built-in library by PID (exact match, no prefix required) if (BuiltInMelodies::loadBuiltInMelody(pidStr, _melodySteps)) { LOG_INFO(TAG, "Built-in melody loaded: %s (%d steps)", pidStr.c_str(), _melodySteps.size()); @@ -391,6 +436,25 @@ void Player::playerControlTaskFn(void* pvParameters) { } } +// Permanent download task — sleeps until signalled by xTaskNotifyGive(). +// Created once at boot so its 8KB stack is allocated while heap is still +// fresh, avoiding fragmentation at download time. +void Player::melodyDownloadTaskFn(void* pvParameters) { + Player* player = static_cast(pvParameters); + for (;;) { + ulTaskNotifyTake(pdTRUE, portMAX_DELAY); // sleep until notified + + LOG_INFO(TAG, "Download task: starting download for '%s'", player->pid.c_str()); + + if (player->loadMelodyInRAM()) { + LOG_INFO(TAG, "Download task: success, starting playback of '%s'", player->pid.c_str()); + player->play(); + } else { + LOG_ERROR(TAG, "Download task: failed to load melody '%s'", player->pid.c_str()); + } + } +} + // Check if it's time to stop playback bool Player::timeToStop(unsigned long now) { if (isPlaying && !infinite_play && total_duration > 0) { diff --git a/src/Player/Player.hpp b/src/Player/Player.hpp index fa34a45..44a4e7a 100644 --- a/src/Player/Player.hpp +++ b/src/Player/Player.hpp @@ -219,6 +219,9 @@ public: /** @brief Static task function for deferred playback control */ static void playerControlTaskFn(void* pvParameters); + + /** @brief Static task function for async melody download + play */ + static void melodyDownloadTaskFn(void* pvParameters); // ═════════════════════════════════════════════════════════════════════════════════ // STATUS QUERY METHODS @@ -276,6 +279,9 @@ private: const char* _pendingStopReason = nullptr; const char* _pendingPauseReason = nullptr; const char* _pendingResumeReason = nullptr; + + // Async download — permanent task signalled via task notification + TaskHandle_t _downloadTaskHandle = nullptr; // ═══════════════════════════════════════════════════════════════════════════════ // PRIVATE HELPER METHODS diff --git a/src/Rs485OutputManager/Rs485OutputManager.cpp b/src/Rs485OutputManager/Rs485OutputManager.cpp new file mode 100644 index 0000000..c6427a5 --- /dev/null +++ b/src/Rs485OutputManager/Rs485OutputManager.cpp @@ -0,0 +1,237 @@ +// ═══════════════════════════════════════════════════════════════════════════════ +// Rs485OutputManager.cpp +// ═══════════════════════════════════════════════════════════════════════════════ + +#if FEATURE_RS485 + +#include "Rs485OutputManager.hpp" +#include "../Logging/Logging.hpp" + +#define TAG "Rs485Output" + +// Waveshare baud-rate register and codes +static constexpr uint16_t REG_BAUD = 0x2000; +static constexpr uint16_t BAUD_CODE_9600 = 0x01; +static constexpr uint16_t BAUD_CODE_115200 = 0x05; +static constexpr uint32_t BAUD_DEFAULT = 9600; + +// FC05 coil values +static constexpr uint16_t COIL_ON = 0xFF00; +static constexpr uint16_t COIL_OFF = 0x0000; + +// Coil address for "all relays" (FC05 shortcut — Waveshare-specific) +static constexpr uint16_t COIL_ALL = 0x00FF; + + +// ── Construction ────────────────────────────────────────────────────────────── + +Rs485OutputManager::Rs485OutputManager(uint8_t txPin, uint8_t rxPin, + uint32_t baud, uint8_t addr) + : _txPin(txPin) + , _rxPin(rxPin) + , _baud(baud) + , _modbusAddr(addr) + , _rs485Serial(2) // ESP32 UART2 +{ +} + +Rs485OutputManager::~Rs485OutputManager() { + emergencyShutdown(); + _rs485Serial.end(); +} + + +// ── initialize() ───────────────────────────────────────────────────────────── + +bool Rs485OutputManager::initialize() { + LOG_INFO(TAG, "Initializing Waveshare 16CH RS485 output manager"); + LOG_INFO(TAG, "UART2: TX=GPIO%d RX=GPIO%d target baud=%lu slave=0x%02X", + _txPin, _rxPin, _baud, _modbusAddr); + + // Upgrade the Waveshare board to operating baud (idempotent, safe on every boot). + upgradeBaud(); + + // Sanity-check comms by clearing all relays. + if (!writeMask(0x0000)) { + LOG_ERROR(TAG, "RS485 comms check FAILED — verify wiring and shared GND"); + return false; + } + + _currentMask = 0x0000; + startDurationTask(); // base-class duration management task + _initialized = true; + + LOG_INFO(TAG, "RS485 output manager ready — 16 outputs via Modbus RTU at %lu baud", _baud); + return true; +} + + +// ── Single-relay control ────────────────────────────────────────────────────── + +void Rs485OutputManager::fireOutput(uint8_t outputIndex) { + if (!_initialized || !isValidOutput(outputIndex)) return; + if (writeCoil(outputIndex, true)) { + _currentMask |= (1u << outputIndex); + LOG_DEBUG(TAG, "FIRE output %d mask=0x%04X", outputIndex, _currentMask); + } else { + LOG_WARNING(TAG, "FC05 ON failed for output %d", outputIndex); + } +} + +void Rs485OutputManager::extinguishOutput(uint8_t outputIndex) { + if (!_initialized || !isValidOutput(outputIndex)) return; + if (writeCoil(outputIndex, false)) { + _currentMask &= ~(1u << outputIndex); + LOG_DEBUG(TAG, "EXTINGUISH output %d mask=0x%04X", outputIndex, _currentMask); + } else { + LOG_WARNING(TAG, "FC05 OFF failed for output %d", outputIndex); + } +} + +void Rs485OutputManager::firePhysicalOutput(uint8_t physicalOutput, bool state) { + if (!_initialized || !isValidOutput(physicalOutput)) return; + writeCoil(physicalOutput, state); +} + + +// ── Emergency shutdown ──────────────────────────────────────────────────────── + +void Rs485OutputManager::emergencyShutdown() { + LOG_WARNING(TAG, "EMERGENCY SHUTDOWN — all relays OFF (FC0F mask=0x0000)"); + + // Clear the duration queue first so the duration task doesn't fire anything further. + portENTER_CRITICAL(&_outputMutex); + _activeOutputs.clear(); + portEXIT_CRITICAL(&_outputMutex); + + writeMask(0x0000); + _currentMask = 0x0000; +} + + +// ── Timed single output ─────────────────────────────────────────────────────── + +void Rs485OutputManager::fireOutputForDuration(uint8_t outputIndex, uint16_t durationMs) { + if (!_initialized || !isValidOutput(outputIndex)) return; + fireOutput(outputIndex); + uint64_t now = getMicros(); + portENTER_CRITICAL(&_outputMutex); + _activeOutputs.push_back({outputIndex, now, durationMs}); + portEXIT_CRITICAL(&_outputMutex); +} + + +// ── Batch operations ────────────────────────────────────────────────────────── + +void Rs485OutputManager::fireOutputsBatch(const std::vector& outputIndices) { + if (!_initialized || outputIndices.empty()) return; + + uint16_t mask = buildMask(outputIndices); + if (mask == 0) return; + + // Preserve any already-active relays — OR the new ones in. + uint16_t newMask = _currentMask | mask; + if (writeMask(newMask)) { + _currentMask = newMask; + LOG_DEBUG(TAG, "BATCH FIRE %d outputs mask=0x%04X", (int)outputIndices.size(), _currentMask); + } else { + LOG_WARNING(TAG, "FC0F batch fire failed (mask=0x%04X)", mask); + } +} + +void Rs485OutputManager::extinguishOutputsBatch(const std::vector& outputIndices) { + if (!_initialized || outputIndices.empty()) return; + + uint16_t mask = buildMask(outputIndices); + if (mask == 0) return; + + uint16_t newMask = _currentMask & ~mask; + if (writeMask(newMask)) { + _currentMask = newMask; + LOG_DEBUG(TAG, "BATCH EXTINGUISH %d outputs mask=0x%04X", (int)outputIndices.size(), _currentMask); + } else { + LOG_WARNING(TAG, "FC0F batch extinguish failed"); + } +} + +void Rs485OutputManager::fireOutputsBatchForDuration( + const std::vector>& outputDurations) +{ + if (!_initialized || outputDurations.empty()) return; + + // Build index list for the batch fire and register each in the duration tracker. + std::vector indices; + indices.reserve(outputDurations.size()); + uint64_t now = getMicros(); + + portENTER_CRITICAL(&_outputMutex); + for (const auto& [outputIndex, durationMs] : outputDurations) { + if (isValidOutput(outputIndex)) { + indices.push_back(outputIndex); + _activeOutputs.push_back({outputIndex, now, durationMs}); + } + } + portEXIT_CRITICAL(&_outputMutex); + + // Single FC0F frame fires all relays simultaneously. + fireOutputsBatch(indices); +} + + +// ── Health check ────────────────────────────────────────────────────────────── + +bool Rs485OutputManager::isHealthy() const { + if (!_initialized) return false; + if (_durationTaskHandle == nullptr) return false; + return true; +} + + +// ── Private: baud upgrade ───────────────────────────────────────────────────── + +void Rs485OutputManager::upgradeBaud() { + LOG_INFO(TAG, "Connecting at 9600 to upgrade Waveshare board baud..."); + _rs485Serial.begin(BAUD_DEFAULT, SERIAL_8N1, _rxPin, _txPin); + _node.begin(_modbusAddr, _rs485Serial); + delay(100); + + uint8_t result = _node.writeSingleRegister(REG_BAUD, BAUD_CODE_115200); + if (result == ModbusMaster::ku8MBSuccess) { + LOG_INFO(TAG, "Board baud upgraded to 115200"); + } else { + // 0xE2 = timeout — expected if board is already at 115200 + LOG_INFO(TAG, "Baud write returned 0x%02X — board likely already at operating baud", result); + } + + delay(200); // board needs time to switch its UART and settle + _rs485Serial.end(); + + LOG_INFO(TAG, "Reconnecting at %lu baud...", _baud); + _rs485Serial.begin(_baud, SERIAL_8N1, _rxPin, _txPin); + _node.begin(_modbusAddr, _rs485Serial); + delay(100); +} + + +// ── Private: Modbus helpers ─────────────────────────────────────────────────── + +bool Rs485OutputManager::writeCoil(uint8_t channel, bool on) { + // FC05: coil address = channel index (0x0000 for CH1 ... 0x000F for CH16) + return _node.writeSingleCoil(channel, on) == ModbusMaster::ku8MBSuccess; +} + +bool Rs485OutputManager::writeMask(uint16_t mask) { + // FC0F: pre-load mask into tx buffer slot 0, then write 16 coils from address 0x0000. + _node.setTransmitBuffer(0, mask); + return _node.writeMultipleCoils(0x0000, 16) == ModbusMaster::ku8MBSuccess; +} + +uint16_t Rs485OutputManager::buildMask(const std::vector& indices) { + uint16_t mask = 0; + for (uint8_t idx : indices) { + if (idx < 16) mask |= (1u << idx); + } + return mask; +} + +#endif // FEATURE_RS485 diff --git a/src/Rs485OutputManager/Rs485OutputManager.hpp b/src/Rs485OutputManager/Rs485OutputManager.hpp new file mode 100644 index 0000000..80a6dfa --- /dev/null +++ b/src/Rs485OutputManager/Rs485OutputManager.hpp @@ -0,0 +1,121 @@ +// ═══════════════════════════════════════════════════════════════════════════════ +// Rs485OutputManager.hpp — OutputManager implementation for Waveshare 16CH RS485 +// ═══════════════════════════════════════════════════════════════════════════════ +// +// Drop-in replacement for PCF8574OutputManager when FEATURE_RS485=1. +// The rest of the firmware (BellEngine, Timekeeper, etc.) sees the same +// OutputManager interface and is completely unaware of the hardware change. +// +// Hardware path: +// ESP32 UART2 → MAX13487EESA (auto-direction RS485) → Waveshare 16CH Modbus RTU +// +// Protocol: +// FC05 writeSingleCoil() — single relay ON/OFF (~1.4ms round-trip at 115200) +// FC0F writeMultipleCoils() — all 16 relays in one frame (~1.6ms round-trip) +// +// Duration management: +// Inherited from OutputManager base class. The base-class duration task calls +// extinguishOutput() for each relay as its dwell expires. This results in one +// FC05 frame per relay-off event, which is ~1.4ms — well within tolerance for +// the 70–150ms dwell times used in this project. +// +// Timing notes (from validated test project): +// - ON command (FC05): ~1.4ms round-trip. Timer starts AFTER ACK. +// - OFF command (FC05): ~1.4ms. Actual dwell = configured_ms + ~1.4ms. +// - Batch ON (FC0F): ~1.6ms for all 16 relays simultaneously. +// - The built-in Waveshare flash timer (100ms resolution) is NOT used — +// ESP32-side duration management gives much finer control. +// +// IMPORTANT: extinguishOutput() must NOT be called from inside a FreeRTOS +// critical section (portENTER_CRITICAL), because it does UART I/O. +// The base class already handles this correctly — it exits the critical +// section before calling extinguishOutput(). +// ═══════════════════════════════════════════════════════════════════════════════ + +#pragma once + +#if FEATURE_RS485 + +#include "../OutputManager/OutputManager.hpp" +#include +#include + +class Rs485OutputManager : public OutputManager { +public: + // ── Construction ───────────────────────────────────────────────────────── + + /** + * @param txPin GPIO for UART2 TX (default: RS485_TX_PIN from variant header) + * @param rxPin GPIO for UART2 RX (default: RS485_RX_PIN from variant header) + * @param baud Operating baud rate (default: RS485_BAUD from variant header) + * @param addr Modbus slave address (default: RS485_MODBUS_ADDR) + */ + Rs485OutputManager(uint8_t txPin = RS485_TX_PIN, + uint8_t rxPin = RS485_RX_PIN, + uint32_t baud = RS485_BAUD, + uint8_t addr = RS485_MODBUS_ADDR); + + virtual ~Rs485OutputManager(); + + // ── OutputManager interface ─────────────────────────────────────────────── + + bool initialize() override; + + // Single-relay control via FC05 + void fireOutput(uint8_t outputIndex) override; + void extinguishOutput(uint8_t outputIndex) override; + + // Emergency: all relays OFF in one FC0F frame + void emergencyShutdown() override; + + // Timed activation — fires relay and enqueues it in the base-class duration tracker + void fireOutputForDuration(uint8_t outputIndex, uint16_t durationMs) override; + + // Batch fire: build a bitmask and send ONE FC0F frame for all relays simultaneously. + // This is the primary path used by BellEngine for chord/note firing. + void fireOutputsBatch(const std::vector& outputIndices) override; + void extinguishOutputsBatch(const std::vector& outputIndices) override; + void fireOutputsBatchForDuration(const std::vector>& outputDurations) override; + + bool isInitialized() const override { return _initialized; } + uint8_t getMaxOutputs() const override { return 16; } + const char* getHardwareType() const override { return "Waveshare 16CH RS485 Modbus RTU"; } + bool isHealthy() const override; + +protected: + // Required by base class — direct physical output state change. + // For RS485 this is identical to fireOutput/extinguishOutput routing. + void firePhysicalOutput(uint8_t physicalOutput, bool state) override; + +private: + uint8_t _txPin; + uint8_t _rxPin; + uint32_t _baud; + uint8_t _modbusAddr; + + HardwareSerial _rs485Serial; + ModbusMaster _node; + + // Tracks the last known relay bitmask so emergencyShutdown can verify. + uint16_t _currentMask = 0x0000; + + // ── Internal helpers ────────────────────────────────────────────────────── + + // Ensure board is at operating baud. Idempotent — safe on every boot. + // Connects at 9600 (factory default), writes BAUD_CODE_115200, reconnects at _baud. + void upgradeBaud(); + + // Send a single-coil write (FC05). Returns true on ACK. + bool writeCoil(uint8_t channel, bool on); + + // Send a 16-coil write (FC0F). Returns true on ACK. + bool writeMask(uint16_t mask); + + // Build a 16-bit bitmask from a list of 0-based output indices. + static uint16_t buildMask(const std::vector& indices); + + // Validate output index (0–15). + bool isValidOutput(uint8_t outputIndex) const { return outputIndex < 16; } +}; + +#endif // FEATURE_RS485 diff --git a/src/Version.hpp b/src/Version.hpp index c951d39..fcd54c9 100644 --- a/src/Version.hpp +++ b/src/Version.hpp @@ -11,8 +11,9 @@ // VERSION HISTORY: // v154 (legacy integer) - Last integer-versioned release // v2.0.0 - First SemVer release +// v2.0.1 - Adds Safemode-OTA during boot. // ═══════════════════════════════════════════════════════════════════════ -#define FW_VERSION "2.0.0" +#define FW_VERSION "2.0.1" // ═══════════════════════════════════════════════════════════════════════ // SemVer — lightweight 3-part version struct diff --git a/src/main.cpp b/src/main.cpp index e117392..9590d37 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -120,6 +120,9 @@ #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" @@ -155,10 +158,17 @@ RFRemote rfRemote; #endif -// 🔥 OUTPUT SYSTEM - PCF8574/PCF8575 I2C Expanders Configuration -// Choose one of the following configurations (with active output counts): +// 🔥 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; -// Option 1: Single PCF8574 (6 active outputs out of 8 max) +#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) @@ -169,14 +179,7 @@ PCF8574OutputManager outputManager(0x24, ChipType::PCF8574, 6); // Option 4: Dual PCF8575 (8 + 8 = 16 total virtual outputs) //PCF8574OutputManager outputManager(0x24, ChipType::PCF8575, 8, 0x21, ChipType::PCF8575, 8); - -// Virtual Output Mapping Examples: -// Option 1: Virtual outputs 0-5 → PCF8574[0x20] pins 0-5 -// Option 3: Virtual outputs 0-5 → PCF8574[0x20] pins 0-5, Virtual outputs 6-13 → PCF8575[0x21] pins 0-7 -// Option 4: Virtual outputs 0-7 → PCF8575[0x20] pins 0-7, Virtual outputs 8-15 → PCF8575[0x21] pins 0-7 - -// Legacy backward-compatible (defaults to 8 active outputs): -//PCF8574OutputManager outputManager(0x20, ChipType::PCF8574); // 8/8 active outputs +#endif BellEngine bellEngine(player, configManager, telemetry, outputManager); // 🔥 THE ULTIMATE BEAST! @@ -188,6 +191,237 @@ TimerHandle_t ntpSyncTimer; // Non-blocking delayed NTP sync timer +// ═══════════════════════════════════════════════════════════════════════════════════ +// 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"); +} + void handleFactoryReset() { if (configManager.resetAllToDefaults()) { delay(3000); @@ -242,12 +476,20 @@ void setup() // 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(); + // ───────────────────────────────────────────────────────────────────────────── + // Apply log level from config (loaded from SD) uint8_t logLevel = configManager.getGeneralConfig().serialLogLevel; Logging::setLevel((Logging::LogLevel)logLevel); LOG_INFO(TAG, "Log level set to %d from configuration", logLevel); - + inputManager.begin(); inputManager.setFactoryResetLongPressCallback(handleFactoryReset); diff --git a/variants/agnus.hpp b/variants/agnus.hpp index 8489271..45d92b6 100644 --- a/variants/agnus.hpp +++ b/variants/agnus.hpp @@ -36,5 +36,8 @@ // (Agnus Mini limit is enforced via app/NVS, // not in firmware) +// ── UART command transport ──────────────────────────────────────────────────── +#define HAS_UART 1 // UARTDriver on Serial2 (GPIO12 TX, GPIO13 RX) + // ── RTC ────────────────────────────────────────────────────────────────────── #define HAS_RTC 0 // No RTC on Agnus diff --git a/variants/bespoke_rs485.hpp b/variants/bespoke_rs485.hpp new file mode 100644 index 0000000..0af03c5 --- /dev/null +++ b/variants/bespoke_rs485.hpp @@ -0,0 +1,58 @@ +// ═══════════════════════════════════════════════════════════════════════════════ +// variants/bespoke_rs485.hpp — Hardware capability definitions for the +// Waveshare 16CH RS485 relay addon build +// ═══════════════════════════════════════════════════════════════════════════════ +// +// This file is auto-included for [env:bespoke-rs485-v1] builds via platformio.ini. +// DO NOT include manually. +// +// Hardware: Kincony KC868-A6 (same base board as Vesper) + +// Waveshare Modbus RTU Relay 16CH connected via KC868-A6's RS485 port. +// +// The internal PCF8574 relays on the KC868-A6 are NOT used in this build. +// All 16 outputs are driven via RS485/Modbus through Rs485OutputManager. +// +// RS485 port on KC868-A6: +// UART2 TX → GPIO27 +// UART2 RX → GPIO14 +// Transceiver: MAX13487EESA (auto-direction, no DE/RE pin needed) +// +// Waveshare board: +// Default slave address : 0x01 +// Operating baud rate : 115200 (upgraded from 9600 on first boot, persisted) +// ═══════════════════════════════════════════════════════════════════════════════ + +#pragma once + +// ── Identity ───────────────────────────────────────────────────────────────── +#define HW_FAMILY "vesper" // Same family as Vesper — uses same OTA channel + // Backend differentiates via NVS hw_type (set at provisioning) + +// ── Storage ────────────────────────────────────────────────────────────────── +#define HAS_SD_CARD 1 // SD card present — configs stored on SD +#define HAS_SPIFFS 0 + +// ── Connectivity ───────────────────────────────────────────────────────────── +#define HAS_ETHERNET 0 +#define HAS_RF 0 // No RF on this build (GPIO22 is free but not used) +#define HAS_LCD 0 + +// ── Output hardware ────────────────────────────────────────────────────────── +#define HAS_PCF8574 0 // Internal PCF8574 relays NOT used in this build +#define FEATURE_RS485 1 // Waveshare 16CH RS485 relay board +#define OUTPUT_COUNT_MAX 16 // 16 outputs via Waveshare board + +// RS485 / Modbus configuration +#define RS485_TX_PIN 27 // KC868-A6 UART2 TX +#define RS485_RX_PIN 14 // KC868-A6 UART2 RX +#define RS485_BAUD 115200 // Operating baud (board is upgraded to this on boot) +#define RS485_MODBUS_ADDR 0x01 // Waveshare slave address (factory default) + +// ── UART command transport ──────────────────────────────────────────────────── +// DISABLED: UART2 (Serial2) is claimed by Rs485OutputManager for Modbus RTU. +// UARTDriver uses the same peripheral (Serial2, GPIO12/13 by default but same +// HardwareSerial instance), which conflicts with RS485 on GPIO27/14. +#define HAS_UART 0 + +// ── RTC ────────────────────────────────────────────────────────────────────── +#define HAS_RTC 1 // DS3231 RTC present (same base board) diff --git a/variants/vesper.hpp b/variants/vesper-std.hpp similarity index 92% rename from variants/vesper.hpp rename to variants/vesper-std.hpp index 679d6f9..010ebf5 100644 --- a/variants/vesper.hpp +++ b/variants/vesper-std.hpp @@ -34,5 +34,8 @@ #define HAS_PCF8574 1 // PCF8574 I2C GPIO expanders for relay control #define OUTPUT_COUNT_MAX 16 // Maximum physical outputs on this board +// ── UART command transport ──────────────────────────────────────────────────── +#define HAS_UART 1 // UARTDriver on Serial2 (GPIO12 TX, GPIO13 RX) + // ── RTC ────────────────────────────────────────────────────────────────────── #define HAS_RTC 1 // DS3231 RTC present