feat: boot-phase OTA, RS485 variant, async melody download, HAL guards
- 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 <noreply@anthropic.com>
This commit is contained in:
@@ -7,7 +7,9 @@ vesper/<DEVID>/kiosk/event // Kiosk Mode Events
|
|||||||
vesper/<DEVID>/kiosk/info // Kiosk Mode General Info
|
vesper/<DEVID>/kiosk/info // Kiosk Mode General Info
|
||||||
|
|
||||||
// WiFi Local AP
|
// WiFi Local AP
|
||||||
|
|
||||||
BellSystemsInfra
|
BellSystemsInfra
|
||||||
|
|
||||||
v3sp3r_8998!
|
v3sp3r_8998!
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+42
-6
@@ -54,16 +54,19 @@ lib_deps =
|
|||||||
; RF remote receiver (433MHz, RCSwitch protocol)
|
; RF remote receiver (433MHz, RCSwitch protocol)
|
||||||
sui77/rc-switch @ ^2.6.4
|
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 =
|
build_flags_common =
|
||||||
-std=gnu++14
|
-std=gnu++14
|
||||||
-DCORE_DEBUG_LEVEL=0
|
-DCORE_DEBUG_LEVEL=0
|
||||||
-DCONFIG_ASYNC_TCP_RUNNING_CORE=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
|
; Current production board
|
||||||
; ───────────────────────────────────────────────────────────────────────────────
|
; ───────────────────────────────────────────────────────────────────────────────
|
||||||
[env:vesper-v1]
|
[env:vesper-std-v1]
|
||||||
platform = ${common.platform}
|
platform = ${common.platform}
|
||||||
framework = ${common.framework}
|
framework = ${common.framework}
|
||||||
board = esp32dev
|
board = esp32dev
|
||||||
@@ -95,8 +98,8 @@ board_build.cmake_extra_args = -DCONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=4096
|
|||||||
build_flags =
|
build_flags =
|
||||||
${common.build_flags_common}
|
${common.build_flags_common}
|
||||||
-DPSRAM_ENABLED=0
|
-DPSRAM_ENABLED=0
|
||||||
-DMQTT_SECRET=\"change-me-in-platformio-ini\"
|
-DMQTT_SECRET=\"deea8b2dbf21872bff8b4639ca16d0348358945ccd4c1cb6c5934ba510de1dce\"
|
||||||
-include variants/vesper.hpp
|
-include variants/vesper-std.hpp
|
||||||
|
|
||||||
lib_deps = ${common.lib_deps}
|
lib_deps = ${common.lib_deps}
|
||||||
|
|
||||||
@@ -122,7 +125,7 @@ board_build.cmake_extra_args = -DCONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=4096
|
|||||||
build_flags =
|
build_flags =
|
||||||
${common.build_flags_common}
|
${common.build_flags_common}
|
||||||
-DPSRAM_ENABLED=0
|
-DPSRAM_ENABLED=0
|
||||||
-DMQTT_SECRET=\"change-me-in-platformio-ini\"
|
-DMQTT_SECRET=\"deea8b2dbf21872bff8b4639ca16d0348358945ccd4c1cb6c5934ba510de1dce\"
|
||||||
-include variants/agnus.hpp
|
-include variants/agnus.hpp
|
||||||
|
|
||||||
lib_deps = ${common.lib_deps}
|
lib_deps = ${common.lib_deps}
|
||||||
@@ -149,12 +152,45 @@ board_build.cmake_extra_args = -DCONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=4096
|
|||||||
build_flags =
|
build_flags =
|
||||||
${common.build_flags_common}
|
${common.build_flags_common}
|
||||||
-DPSRAM_ENABLED=0
|
-DPSRAM_ENABLED=0
|
||||||
-DMQTT_SECRET=\"change-me-in-platformio-ini\"
|
-DMQTT_SECRET=\"deea8b2dbf21872bff8b4639ca16d0348358945ccd4c1cb6c5934ba510de1dce\"
|
||||||
-include variants/agnus.hpp
|
-include variants/agnus.hpp
|
||||||
|
|
||||||
lib_deps = ${common.lib_deps}
|
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
|
; VESPER+ v1 — Future: adds RF remote support
|
||||||
; ───────────────────────────────────────────────────────────────────────────────
|
; ───────────────────────────────────────────────────────────────────────────────
|
||||||
|
|||||||
@@ -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
|
||||||
|
@@ -60,13 +60,17 @@ CommunicationRouter::CommunicationRouter(ConfigManager& configManager,
|
|||||||
, _mqttClient(configManager, networking)
|
, _mqttClient(configManager, networking)
|
||||||
, _clientManager()
|
, _clientManager()
|
||||||
, _wsServer(webSocket, _clientManager)
|
, _wsServer(webSocket, _clientManager)
|
||||||
|
#if HAS_UART
|
||||||
, _uartHandler()
|
, _uartHandler()
|
||||||
|
#endif
|
||||||
// New architecture — transports reference the bus
|
// New architecture — transports reference the bus
|
||||||
, _bus()
|
, _bus()
|
||||||
, _mqttTransport(_mqttClient, _bus)
|
, _mqttTransport(_mqttClient, _bus)
|
||||||
, _wsTransport(_wsServer, _bus)
|
, _wsTransport(_wsServer, _bus)
|
||||||
, _httpTransport(server, _bus, configManager)
|
, _httpTransport(server, _bus, configManager)
|
||||||
|
#if HAS_UART
|
||||||
, _uartTransport(_uartHandler, _bus)
|
, _uartTransport(_uartHandler, _bus)
|
||||||
|
#endif
|
||||||
, _webServerTransport(server, _bus, configManager, networking)
|
, _webServerTransport(server, _bus, configManager, networking)
|
||||||
{}
|
{}
|
||||||
|
|
||||||
@@ -122,15 +126,19 @@ void CommunicationRouter::begin() {
|
|||||||
LOG_INFO(TAG, "WebServer transport initialised (/settings)");
|
LOG_INFO(TAG, "WebServer transport initialised (/settings)");
|
||||||
|
|
||||||
// ── UART ─────────────────────────────────────────────────────────────────
|
// ── UART ─────────────────────────────────────────────────────────────────
|
||||||
|
#if HAS_UART
|
||||||
LOG_INFO(TAG, "Setting up UART transport...");
|
LOG_INFO(TAG, "Setting up UART transport...");
|
||||||
_uartTransport.begin();
|
_uartTransport.begin();
|
||||||
LOG_INFO(TAG, "UART transport initialised");
|
LOG_INFO(TAG, "UART transport initialised");
|
||||||
|
#endif
|
||||||
|
|
||||||
// ── Register transports with the bus ─────────────────────────────────────
|
// ── Register transports with the bus ─────────────────────────────────────
|
||||||
_bus.addTransport(&_mqttTransport);
|
_bus.addTransport(&_mqttTransport);
|
||||||
_bus.addTransport(&_wsTransport);
|
_bus.addTransport(&_wsTransport);
|
||||||
_bus.addTransport(&_httpTransport);
|
_bus.addTransport(&_httpTransport);
|
||||||
|
#if HAS_UART
|
||||||
_bus.addTransport(&_uartTransport);
|
_bus.addTransport(&_uartTransport);
|
||||||
|
#endif
|
||||||
_bus.addTransport(&_webServerTransport);
|
_bus.addTransport(&_webServerTransport);
|
||||||
|
|
||||||
// ── Register all domain handlers ─────────────────────────────────────────
|
// ── Register all domain handlers ─────────────────────────────────────────
|
||||||
@@ -154,7 +162,9 @@ void CommunicationRouter::begin() {
|
|||||||
// ─────────────────────────────────────────────────────────────────────────────
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
void CommunicationRouter::loop() {
|
void CommunicationRouter::loop() {
|
||||||
|
#if HAS_UART
|
||||||
_uartTransport.loop();
|
_uartTransport.loop();
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─────────────────────────────────────────────────────────────────────────────
|
// ─────────────────────────────────────────────────────────────────────────────
|
||||||
|
|||||||
@@ -21,7 +21,9 @@
|
|||||||
// Underlying protocol drivers (still owned here)
|
// Underlying protocol drivers (still owned here)
|
||||||
#include "../Drivers/MQTTDriver/MQTTDriver.hpp"
|
#include "../Drivers/MQTTDriver/MQTTDriver.hpp"
|
||||||
#include "../Drivers/WebSocketDriver/WebSocketDriver.hpp"
|
#include "../Drivers/WebSocketDriver/WebSocketDriver.hpp"
|
||||||
|
#if HAS_UART
|
||||||
#include "../Drivers/UARTDriver/UARTDriver.hpp"
|
#include "../Drivers/UARTDriver/UARTDriver.hpp"
|
||||||
|
#endif
|
||||||
#include "../../ClientManager/ClientManager.hpp"
|
#include "../../ClientManager/ClientManager.hpp"
|
||||||
|
|
||||||
// New architecture
|
// New architecture
|
||||||
@@ -29,7 +31,9 @@
|
|||||||
#include "../Transport/MQTTTransport/MQTTTransport.hpp"
|
#include "../Transport/MQTTTransport/MQTTTransport.hpp"
|
||||||
#include "../Transport/WebSocketTransport/WebSocketTransport.hpp"
|
#include "../Transport/WebSocketTransport/WebSocketTransport.hpp"
|
||||||
#include "../Transport/HTTPTransport/HTTPTransport.hpp"
|
#include "../Transport/HTTPTransport/HTTPTransport.hpp"
|
||||||
|
#if HAS_UART
|
||||||
#include "../Transport/UARTTransport/UARTTransport.hpp"
|
#include "../Transport/UARTTransport/UARTTransport.hpp"
|
||||||
|
#endif
|
||||||
#include "../Transport/WebServerTransport/WebServerTransport.hpp"
|
#include "../Transport/WebServerTransport/WebServerTransport.hpp"
|
||||||
|
|
||||||
// Forward declarations — resolved in .cpp
|
// Forward declarations — resolved in .cpp
|
||||||
@@ -91,7 +95,9 @@ public:
|
|||||||
|
|
||||||
// Legacy accessors used by other subsystems
|
// Legacy accessors used by other subsystems
|
||||||
MQTTDriver& getMQTTClient() { return _mqttClient; }
|
MQTTDriver& getMQTTClient() { return _mqttClient; }
|
||||||
|
#if HAS_UART
|
||||||
UARTDriver& getUARTHandler() { return _uartHandler; }
|
UARTDriver& getUARTHandler() { return _uartHandler; }
|
||||||
|
#endif
|
||||||
|
|
||||||
// Broadcast helpers — called by BellEngine, Player, Telemetry, etc.
|
// Broadcast helpers — called by BellEngine, Player, Telemetry, etc.
|
||||||
void broadcastStatus(const String& statusMessage);
|
void broadcastStatus(const String& statusMessage);
|
||||||
@@ -158,14 +164,18 @@ private:
|
|||||||
MQTTDriver _mqttClient;
|
MQTTDriver _mqttClient;
|
||||||
ClientManager _clientManager;
|
ClientManager _clientManager;
|
||||||
WebSocketDriver _wsServer;
|
WebSocketDriver _wsServer;
|
||||||
|
#if HAS_UART
|
||||||
UARTDriver _uartHandler;
|
UARTDriver _uartHandler;
|
||||||
|
#endif
|
||||||
|
|
||||||
// ── New architecture (owned) ────────────────────────────────────────────
|
// ── New architecture (owned) ────────────────────────────────────────────
|
||||||
CommandBus _bus;
|
CommandBus _bus;
|
||||||
MQTTTransport _mqttTransport;
|
MQTTTransport _mqttTransport;
|
||||||
WebSocketTransport _wsTransport;
|
WebSocketTransport _wsTransport;
|
||||||
HTTPTransport _httpTransport;
|
HTTPTransport _httpTransport;
|
||||||
|
#if HAS_UART
|
||||||
UARTTransport _uartTransport;
|
UARTTransport _uartTransport;
|
||||||
|
#endif
|
||||||
WebServerTransport _webServerTransport;
|
WebServerTransport _webServerTransport;
|
||||||
|
|
||||||
// Register all domain handlers onto the bus.
|
// Register all domain handlers onto the bus.
|
||||||
|
|||||||
@@ -134,8 +134,8 @@ public:
|
|||||||
*/
|
*/
|
||||||
struct UpdateConfig {
|
struct UpdateConfig {
|
||||||
String fallbackServerUrls[2] = {
|
String fallbackServerUrls[2] = {
|
||||||
"https://firmware.bellsystems.net", // 🥇 Primary fallback
|
"http://firmware.bellsystems.net", // 🥇 Primary fallback
|
||||||
"https://firmware.bonamin.space" // 🥈 Secondary fallback
|
"http://firmware.bonamin.space" // 🥈 Secondary fallback
|
||||||
};
|
};
|
||||||
int timeout = 10000; // ⏱️ Universal timeout - OK as is
|
int timeout = 10000; // ⏱️ Universal timeout - OK as is
|
||||||
int retries = 3; // 🔄 Universal retries - OK as is
|
int retries = 3; // 🔄 Universal retries - OK as is
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
#include "FileManager.hpp"
|
#include "FileManager.hpp"
|
||||||
|
#include <esp_task_wdt.h>
|
||||||
|
|
||||||
#define TAG "FileManager"
|
#define TAG "FileManager"
|
||||||
#include "../BuiltInMelodies/BuiltInMelodies.hpp"
|
#include "../BuiltInMelodies/BuiltInMelodies.hpp"
|
||||||
@@ -75,6 +76,12 @@ bool FileManager::downloadFile(const String& url, const String& directory, const
|
|||||||
|
|
||||||
// Configure HTTP client based on protocol
|
// Configure HTTP client based on protocol
|
||||||
if (isHttps) {
|
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 = new WiFiClientSecure();
|
||||||
secureClient->setInsecure(); // Skip certificate validation for Firebase
|
secureClient->setInsecure(); // Skip certificate validation for Firebase
|
||||||
secureClient->setTimeout(15); // 15 second timeout for TLS operations
|
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.setTimeout(30000); // 30 second timeout for large files
|
||||||
http.setFollowRedirects(HTTPC_FORCE_FOLLOW_REDIRECTS); // Follow redirects automatically
|
http.setFollowRedirects(HTTPC_FORCE_FOLLOW_REDIRECTS); // Follow redirects automatically
|
||||||
|
|
||||||
// Disable task watchdog for current task during blocking HTTPS operation
|
// Remove this task from the WDT while the TLS handshake blocks.
|
||||||
// The TLS handshake can take several seconds and would trigger watchdog
|
// The handshake can take several seconds and would otherwise starve async_tcp.
|
||||||
LOG_DEBUG(TAG, "Disabling watchdog for download...");
|
|
||||||
esp_task_wdt_delete(NULL);
|
esp_task_wdt_delete(NULL);
|
||||||
|
|
||||||
LOG_DEBUG(TAG, "Sending HTTP GET request...");
|
LOG_DEBUG(TAG, "Sending HTTP GET request...");
|
||||||
int httpCode = http.GET();
|
int httpCode = http.GET();
|
||||||
|
|
||||||
// Re-enable task watchdog after HTTP request completes
|
|
||||||
esp_task_wdt_add(NULL);
|
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) {
|
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());
|
LOG_ERROR(TAG, "HTTP GET failed, code: %d, error: %s", httpCode, http.errorToString(httpCode).c_str());
|
||||||
|
|||||||
@@ -24,7 +24,6 @@
|
|||||||
#include <WiFiClient.h>
|
#include <WiFiClient.h>
|
||||||
#include <WiFiClientSecure.h>
|
#include <WiFiClientSecure.h>
|
||||||
#include <ArduinoJson.h>
|
#include <ArduinoJson.h>
|
||||||
#include <esp_task_wdt.h>
|
|
||||||
#include "../Logging/Logging.hpp"
|
#include "../Logging/Logging.hpp"
|
||||||
#include "../ConfigManager/ConfigManager.hpp"
|
#include "../ConfigManager/ConfigManager.hpp"
|
||||||
|
|
||||||
|
|||||||
@@ -70,15 +70,17 @@ void OTAManager::begin() {
|
|||||||
return;
|
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(
|
BaseType_t taskCreated = xTaskCreatePinnedToCore(
|
||||||
otaWorkerTaskFunction,
|
otaWorkerTaskFunction,
|
||||||
"OTA_Worker",
|
"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
|
this, // Pass OTAManager instance
|
||||||
2, // Priority 2 (lower than critical tasks)
|
2, // Priority 2 (lower than critical tasks)
|
||||||
&_otaWorkerTask,
|
&_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) {
|
if (taskCreated != pdPASS) {
|
||||||
@@ -88,7 +90,7 @@ void OTAManager::begin() {
|
|||||||
return;
|
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)
|
// Create timer for scheduled checks (checks every minute if it's 3:00 AM)
|
||||||
_scheduledCheckTimer = xTimerCreate(
|
_scheduledCheckTimer = xTimerCreate(
|
||||||
@@ -215,15 +217,15 @@ void OTAManager::checkForUpdates(const String& channel) {
|
|||||||
LOG_WARNING(TAG, "OTA check already in progress");
|
LOG_WARNING(TAG, "OTA check already in progress");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 🔥 CRITICAL: Check network connectivity before attempting HTTP requests
|
// 🔥 CRITICAL: Check network connectivity before attempting HTTP requests
|
||||||
if (WiFi.status() != WL_CONNECTED) { // ETHERNET DISABLED - WiFi only
|
if (WiFi.status() != WL_CONNECTED) { // ETHERNET DISABLED - WiFi only
|
||||||
LOG_WARNING(TAG, "OTA check skipped - no network connectivity");
|
LOG_WARNING(TAG, "OTA check skipped - no network connectivity");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
setStatus(Status::CHECKING_VERSION);
|
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());
|
channel.c_str(), _configManager.getHardwareVariant().c_str());
|
||||||
|
|
||||||
if (checkVersion(channel)) {
|
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());
|
LOG_INFO(TAG, "OTA: Trying server %d/%d: %s", serverIndex + 1, servers.size(), metadataUrl.c_str());
|
||||||
|
|
||||||
HTTPClient http;
|
String jsonStr;
|
||||||
http.setTimeout(updateConfig.timeout);
|
|
||||||
http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
|
|
||||||
http.begin(metadataUrl.c_str());
|
|
||||||
|
|
||||||
int retryCount = 0;
|
|
||||||
int httpCode = -1;
|
int httpCode = -1;
|
||||||
|
|
||||||
while (retryCount < updateConfig.retries && httpCode != HTTP_CODE_OK) {
|
for (int retryCount = 0; retryCount < updateConfig.retries; retryCount++) {
|
||||||
if (retryCount > 0) {
|
if (retryCount > 0) {
|
||||||
LOG_INFO(TAG, "OTA: Retry %d/%d for server %d", retryCount + 1, updateConfig.retries, serverIndex + 1);
|
LOG_INFO(TAG, "OTA: Retry %d/%d for server %d", retryCount + 1, updateConfig.retries, serverIndex + 1);
|
||||||
delay(1000 * retryCount); // Exponential backoff
|
delay(1000 * retryCount); // Exponential backoff
|
||||||
}
|
}
|
||||||
httpCode = http.GET();
|
|
||||||
retryCount++;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (httpCode == HTTP_CODE_OK) {
|
HTTPClient http;
|
||||||
String jsonStr = http.getString();
|
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();
|
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);
|
DynamicJsonDocument doc(1024);
|
||||||
DeserializationError error = deserializeJson(doc, jsonStr);
|
DeserializationError error = deserializeJson(doc, jsonStr);
|
||||||
if (error) {
|
if (error) {
|
||||||
@@ -358,19 +370,16 @@ bool OTAManager::checkVersion(const String& channel) {
|
|||||||
const char* minVersionStr = doc["min_fw_version"] | "";
|
const char* minVersionStr = doc["min_fw_version"] | "";
|
||||||
_minVersion = (strlen(minVersionStr) > 0) ? SemVer::parse(String(minVersionStr)) : SemVer{0, 0, 0};
|
_minVersion = (strlen(minVersionStr) > 0) ? SemVer::parse(String(minVersionStr)) : SemVer{0, 0, 0};
|
||||||
|
|
||||||
_availableChecksum = doc["sha256"] | "";
|
_availableChecksum = doc["sha256"] | "";
|
||||||
_expectedFileSize = doc["size"] | (size_t)0;
|
_expectedFileSize = doc["size"] | (size_t)0;
|
||||||
_availableDownloadPath = doc["download_url"] | "";
|
_availableDownloadPath = doc["download_url"] | "";
|
||||||
|
|
||||||
// update_type: "optional" | "mandatory" | "emergency"
|
// update_type: "optional" | "mandatory" | "emergency"
|
||||||
// This is the urgency of the release — completely separate from the channel.
|
_isMandatory = doc["mandatory"] | false;
|
||||||
// The server derives mandatory/emergency booleans from this for us.
|
_isEmergency = doc["emergency"] | false;
|
||||||
_isMandatory = doc["mandatory"] | false;
|
_updateChannel = channel;
|
||||||
_isEmergency = doc["emergency"] | false;
|
|
||||||
_updateChannel = channel; // channel is what we requested
|
|
||||||
|
|
||||||
// Validate the server actually responded for the channel we asked for.
|
// 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"] | "";
|
const char* serverChannel = doc["channel"] | "";
|
||||||
if (strlen(serverChannel) > 0 && String(serverChannel) != channel) {
|
if (strlen(serverChannel) > 0 && String(serverChannel) != channel) {
|
||||||
LOG_ERROR(TAG, "OTA: Channel mismatch! Requested: %s, Got: %s", channel.c_str(), serverChannel);
|
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;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate version parsed correctly
|
|
||||||
if (_availableVersion.isZero()) {
|
if (_availableVersion.isZero()) {
|
||||||
LOG_ERROR(TAG, "OTA: Invalid version string '%s' from server %d", versionStr, serverIndex + 1);
|
LOG_ERROR(TAG, "OTA: Invalid version string '%s' from server %d", versionStr, serverIndex + 1);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate checksum is a 64-char SHA256 hex string
|
|
||||||
if (_availableChecksum.length() != 64) {
|
if (_availableChecksum.length() != 64) {
|
||||||
LOG_ERROR(TAG, "OTA: Invalid sha256 length (%d) from server %d", _availableChecksum.length(), serverIndex + 1);
|
LOG_ERROR(TAG, "OTA: Invalid sha256 length (%d) from server %d", _availableChecksum.length(), serverIndex + 1);
|
||||||
continue;
|
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();
|
SemVer currentVersion = getCurrentVersion();
|
||||||
if (!_minVersion.isZero() && currentVersion < _minVersion) {
|
if (!_minVersion.isZero() && currentVersion < _minVersion) {
|
||||||
LOG_WARNING(TAG, "OTA: Server returned version %s with min_fw_version %s — server is handling upgrade chain",
|
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,
|
serverIndex + 1, versionStr, _expectedFileSize,
|
||||||
_isMandatory ? "YES" : "NO", _isEmergency ? "YES" : "NO");
|
_isMandatory ? "YES" : "NO", _isEmergency ? "YES" : "NO");
|
||||||
return true;
|
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;
|
HTTPClient http;
|
||||||
http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
|
http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
|
||||||
http.begin(url.c_str());
|
http.begin(url); // Let HTTPClient manage TLS internally (same as bootOtaCheck)
|
||||||
http.setTimeout(30000); // 30 seconds
|
http.setTimeout(60000); // 60 seconds for a ~1.4MB binary
|
||||||
|
|
||||||
int httpCode = http.GET();
|
int httpCode = http.GET();
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,7 @@
|
|||||||
|
|
||||||
#include <Arduino.h>
|
#include <Arduino.h>
|
||||||
#include <HTTPClient.h>
|
#include <HTTPClient.h>
|
||||||
|
#include <WiFiClientSecure.h>
|
||||||
#include <Update.h>
|
#include <Update.h>
|
||||||
#include <WiFi.h>
|
#include <WiFi.h>
|
||||||
#include <SD.h>
|
#include <SD.h>
|
||||||
|
|||||||
+67
-3
@@ -114,6 +114,10 @@ void Player::begin() {
|
|||||||
// Dedicated task handles deferred stop/pause/resume triggered by the timer callback.
|
// 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.
|
// Timer callbacks run on Tmr Svc (tiny stack) so we must not do MQTT/WS work there.
|
||||||
xTaskCreate(playerControlTaskFn, "PlayerCtrl", 4096, this, 2, NULL);
|
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() {
|
void Player::play() {
|
||||||
@@ -215,11 +219,45 @@ bool Player::command(JsonVariant data) {
|
|||||||
setMelodyAttributes(data);
|
setMelodyAttributes(data);
|
||||||
|
|
||||||
if (action == "play") {
|
if (action == "play") {
|
||||||
if (!loadMelodyInRAM()) {
|
String pidStr = String(pid.c_str());
|
||||||
LOG_WARNING(TAG, "Play command aborted — melody '%s' could not be loaded", 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;
|
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;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -233,6 +271,8 @@ void Player::setMelodyAttributes(JsonVariant doc) {
|
|||||||
}
|
}
|
||||||
if (doc.containsKey("pid")) {
|
if (doc.containsKey("pid")) {
|
||||||
pid = doc["pid"].as<const char*>();
|
pid = doc["pid"].as<const char*>();
|
||||||
|
} else if (doc.containsKey("uid")) {
|
||||||
|
pid = doc["uid"].as<const char*>();
|
||||||
}
|
}
|
||||||
if (doc.containsKey("url")) {
|
if (doc.containsKey("url")) {
|
||||||
url = doc["url"].as<const char*>();
|
url = doc["url"].as<const char*>();
|
||||||
@@ -283,6 +323,11 @@ bool Player::loadMelodyInRAM() {
|
|||||||
_melodySteps.clear(); // Always start clean — never play stale data from a previous command
|
_melodySteps.clear(); // Always start clean — never play stale data from a previous command
|
||||||
String pidStr = String(pid.c_str());
|
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)
|
// 🎵 PRIORITY 1: Check built-in library by PID (exact match, no prefix required)
|
||||||
if (BuiltInMelodies::loadBuiltInMelody(pidStr, _melodySteps)) {
|
if (BuiltInMelodies::loadBuiltInMelody(pidStr, _melodySteps)) {
|
||||||
LOG_INFO(TAG, "Built-in melody loaded: %s (%d steps)", pidStr.c_str(), _melodySteps.size());
|
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<Player*>(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
|
// Check if it's time to stop playback
|
||||||
bool Player::timeToStop(unsigned long now) {
|
bool Player::timeToStop(unsigned long now) {
|
||||||
if (isPlaying && !infinite_play && total_duration > 0) {
|
if (isPlaying && !infinite_play && total_duration > 0) {
|
||||||
|
|||||||
@@ -219,6 +219,9 @@ public:
|
|||||||
|
|
||||||
/** @brief Static task function for deferred playback control */
|
/** @brief Static task function for deferred playback control */
|
||||||
static void playerControlTaskFn(void* pvParameters);
|
static void playerControlTaskFn(void* pvParameters);
|
||||||
|
|
||||||
|
/** @brief Static task function for async melody download + play */
|
||||||
|
static void melodyDownloadTaskFn(void* pvParameters);
|
||||||
|
|
||||||
// ═════════════════════════════════════════════════════════════════════════════════
|
// ═════════════════════════════════════════════════════════════════════════════════
|
||||||
// STATUS QUERY METHODS
|
// STATUS QUERY METHODS
|
||||||
@@ -276,6 +279,9 @@ private:
|
|||||||
const char* _pendingStopReason = nullptr;
|
const char* _pendingStopReason = nullptr;
|
||||||
const char* _pendingPauseReason = nullptr;
|
const char* _pendingPauseReason = nullptr;
|
||||||
const char* _pendingResumeReason = nullptr;
|
const char* _pendingResumeReason = nullptr;
|
||||||
|
|
||||||
|
// Async download — permanent task signalled via task notification
|
||||||
|
TaskHandle_t _downloadTaskHandle = nullptr;
|
||||||
|
|
||||||
// ═══════════════════════════════════════════════════════════════════════════════
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
// PRIVATE HELPER METHODS
|
// PRIVATE HELPER METHODS
|
||||||
|
|||||||
@@ -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<uint8_t>& 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<uint8_t>& 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<std::pair<uint8_t, uint16_t>>& outputDurations)
|
||||||
|
{
|
||||||
|
if (!_initialized || outputDurations.empty()) return;
|
||||||
|
|
||||||
|
// Build index list for the batch fire and register each in the duration tracker.
|
||||||
|
std::vector<uint8_t> 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<uint8_t>& indices) {
|
||||||
|
uint16_t mask = 0;
|
||||||
|
for (uint8_t idx : indices) {
|
||||||
|
if (idx < 16) mask |= (1u << idx);
|
||||||
|
}
|
||||||
|
return mask;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif // FEATURE_RS485
|
||||||
@@ -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 <HardwareSerial.h>
|
||||||
|
#include <ModbusMaster.h>
|
||||||
|
|
||||||
|
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<uint8_t>& outputIndices) override;
|
||||||
|
void extinguishOutputsBatch(const std::vector<uint8_t>& outputIndices) override;
|
||||||
|
void fireOutputsBatchForDuration(const std::vector<std::pair<uint8_t, uint16_t>>& 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<uint8_t>& indices);
|
||||||
|
|
||||||
|
// Validate output index (0–15).
|
||||||
|
bool isValidOutput(uint8_t outputIndex) const { return outputIndex < 16; }
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif // FEATURE_RS485
|
||||||
+2
-1
@@ -11,8 +11,9 @@
|
|||||||
// VERSION HISTORY:
|
// VERSION HISTORY:
|
||||||
// v154 (legacy integer) - Last integer-versioned release
|
// v154 (legacy integer) - Last integer-versioned release
|
||||||
// v2.0.0 - First SemVer 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
|
// SemVer — lightweight 3-part version struct
|
||||||
|
|||||||
+255
-13
@@ -120,6 +120,9 @@
|
|||||||
#include "Player/Player.hpp"
|
#include "Player/Player.hpp"
|
||||||
#include "BellEngine/BellEngine.hpp"
|
#include "BellEngine/BellEngine.hpp"
|
||||||
#include "OutputManager/OutputManager.hpp"
|
#include "OutputManager/OutputManager.hpp"
|
||||||
|
#if FEATURE_RS485
|
||||||
|
#include "Rs485OutputManager/Rs485OutputManager.hpp"
|
||||||
|
#endif
|
||||||
#include "HealthMonitor/HealthMonitor.hpp"
|
#include "HealthMonitor/HealthMonitor.hpp"
|
||||||
#include "FirmwareValidator/FirmwareValidator.hpp"
|
#include "FirmwareValidator/FirmwareValidator.hpp"
|
||||||
#include "InputManager/InputManager.hpp"
|
#include "InputManager/InputManager.hpp"
|
||||||
@@ -155,10 +158,17 @@ RFRemote rfRemote;
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
|
||||||
// 🔥 OUTPUT SYSTEM - PCF8574/PCF8575 I2C Expanders Configuration
|
// 🔥 OUTPUT SYSTEM
|
||||||
// Choose one of the following configurations (with active output counts):
|
// 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);
|
PCF8574OutputManager outputManager(0x24, ChipType::PCF8574, 6);
|
||||||
|
|
||||||
// Option 2: Single PCF8575 (8 active outputs out of 16 max)
|
// 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)
|
// Option 4: Dual PCF8575 (8 + 8 = 16 total virtual outputs)
|
||||||
//PCF8574OutputManager outputManager(0x24, ChipType::PCF8575, 8, 0x21, ChipType::PCF8575, 8);
|
//PCF8574OutputManager outputManager(0x24, ChipType::PCF8575, 8, 0x21, ChipType::PCF8575, 8);
|
||||||
|
#endif
|
||||||
// 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
|
|
||||||
|
|
||||||
BellEngine bellEngine(player, configManager, telemetry, outputManager); // 🔥 THE ULTIMATE BEAST!
|
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<String> 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() {
|
void handleFactoryReset() {
|
||||||
if (configManager.resetAllToDefaults()) {
|
if (configManager.resetAllToDefaults()) {
|
||||||
delay(3000);
|
delay(3000);
|
||||||
@@ -242,12 +476,20 @@ void setup()
|
|||||||
|
|
||||||
// Initialize Configuration (loads factory identity from NVS + user settings from SD)
|
// Initialize Configuration (loads factory identity from NVS + user settings from SD)
|
||||||
configManager.begin();
|
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)
|
// Apply log level from config (loaded from SD)
|
||||||
uint8_t logLevel = configManager.getGeneralConfig().serialLogLevel;
|
uint8_t logLevel = configManager.getGeneralConfig().serialLogLevel;
|
||||||
Logging::setLevel((Logging::LogLevel)logLevel);
|
Logging::setLevel((Logging::LogLevel)logLevel);
|
||||||
LOG_INFO(TAG, "Log level set to %d from configuration", logLevel);
|
LOG_INFO(TAG, "Log level set to %d from configuration", logLevel);
|
||||||
|
|
||||||
inputManager.begin();
|
inputManager.begin();
|
||||||
inputManager.setFactoryResetLongPressCallback(handleFactoryReset);
|
inputManager.setFactoryResetLongPressCallback(handleFactoryReset);
|
||||||
|
|
||||||
|
|||||||
@@ -36,5 +36,8 @@
|
|||||||
// (Agnus Mini limit is enforced via app/NVS,
|
// (Agnus Mini limit is enforced via app/NVS,
|
||||||
// not in firmware)
|
// not in firmware)
|
||||||
|
|
||||||
|
// ── UART command transport ────────────────────────────────────────────────────
|
||||||
|
#define HAS_UART 1 // UARTDriver on Serial2 (GPIO12 TX, GPIO13 RX)
|
||||||
|
|
||||||
// ── RTC ──────────────────────────────────────────────────────────────────────
|
// ── RTC ──────────────────────────────────────────────────────────────────────
|
||||||
#define HAS_RTC 0 // No RTC on Agnus
|
#define HAS_RTC 0 // No RTC on Agnus
|
||||||
|
|||||||
@@ -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)
|
||||||
@@ -34,5 +34,8 @@
|
|||||||
#define HAS_PCF8574 1 // PCF8574 I2C GPIO expanders for relay control
|
#define HAS_PCF8574 1 // PCF8574 I2C GPIO expanders for relay control
|
||||||
#define OUTPUT_COUNT_MAX 16 // Maximum physical outputs on this board
|
#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 ──────────────────────────────────────────────────────────────────────
|
// ── RTC ──────────────────────────────────────────────────────────────────────
|
||||||
#define HAS_RTC 1 // DS3231 RTC present
|
#define HAS_RTC 1 // DS3231 RTC present
|
||||||
Reference in New Issue
Block a user