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:
2026-04-18 20:48:26 +03:00
co-authored by Claude Sonnet 4.6
parent a4d071d5d5
commit ed1123283b
19 changed files with 871 additions and 72 deletions
@@ -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
}
// ─────────────────────────────────────────────────────────────────────────────
@@ -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.
+2 -2
View File
@@ -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
+9 -7
View File
@@ -1,4 +1,5 @@
#include "FileManager.hpp"
#include <esp_task_wdt.h>
#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());
-1
View File
@@ -24,7 +24,6 @@
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
#include <esp_task_wdt.h>
#include "../Logging/Logging.hpp"
#include "../ConfigManager/ConfigManager.hpp"
+38 -39
View File
@@ -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();
+1
View File
@@ -18,6 +18,7 @@
#include <Arduino.h>
#include <HTTPClient.h>
#include <WiFiClientSecure.h>
#include <Update.h>
#include <WiFi.h>
#include <SD.h>
+67 -3
View File
@@ -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<const char*>();
} else if (doc.containsKey("uid")) {
pid = doc["uid"].as<const char*>();
}
if (doc.containsKey("url")) {
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
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<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
bool Player::timeToStop(unsigned long now) {
if (isPlaying && !infinite_play && total_duration > 0) {
+6
View File
@@ -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
@@ -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
View File
@@ -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
+255 -13
View File
@@ -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<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&current_version=Y
String url = servers[i] + "/api/firmware/" + hwType + "/" + channel +
"/latest?hw_version=" + hwVersion +
"&current_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);