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:
+255
-13
@@ -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¤t_version=Y
|
||||
String url = servers[i] + "/api/firmware/" + hwType + "/" + channel +
|
||||
"/latest?hw_version=" + hwVersion +
|
||||
"¤t_version=" + currentVersionStr;
|
||||
|
||||
Serial.printf("[BootOTA] Trying server %d/%d: %s\n", i + 1, servers.size(), url.c_str());
|
||||
|
||||
HTTPClient http;
|
||||
http.setTimeout(8000); // 8s — tight but enough for a small JSON response
|
||||
http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
|
||||
http.begin(url);
|
||||
|
||||
int code = http.GET();
|
||||
if (code != HTTP_CODE_OK) {
|
||||
Serial.printf("[BootOTA] Server %d returned HTTP %d — trying next\n", i + 1, code);
|
||||
http.end();
|
||||
continue;
|
||||
}
|
||||
|
||||
String body = http.getString();
|
||||
http.end();
|
||||
|
||||
DynamicJsonDocument doc(1024);
|
||||
if (deserializeJson(doc, body) != DeserializationError::Ok) {
|
||||
Serial.printf("[BootOTA] Server %d: JSON parse failed — trying next\n", i + 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
const char* versionStr = doc["version"] | "";
|
||||
if (strlen(versionStr) == 0) {
|
||||
Serial.printf("[BootOTA] Server %d: missing 'version' field — trying next\n", i + 1);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Validate checksum field is present and well-formed (64-char SHA256 hex)
|
||||
const char* sha256 = doc["sha256"] | "";
|
||||
if (strlen(sha256) != 64) {
|
||||
Serial.printf("[BootOTA] Server %d: invalid sha256 length %d — trying next\n", i + 1, strlen(sha256));
|
||||
continue;
|
||||
}
|
||||
|
||||
availableVersionStr = String(versionStr);
|
||||
expectedSize = doc["size"] | (size_t)0;
|
||||
firmwareDownloadPath = doc["download_url"] | String("");
|
||||
metadataOk = true;
|
||||
|
||||
Serial.printf("[BootOTA] Server %d: metadata OK — available=%s current=%s\n",
|
||||
i + 1, availableVersionStr.c_str(), currentVersionStr.c_str());
|
||||
}
|
||||
|
||||
if (!metadataOk) {
|
||||
Serial.println("[BootOTA] All servers failed to return metadata — skipping");
|
||||
return;
|
||||
}
|
||||
|
||||
// ── 3. Compare versions ───────────────────────────────────────────────────────
|
||||
SemVer availableVersion = SemVer::parse(availableVersionStr);
|
||||
if (!(availableVersion > currentVersion)) {
|
||||
Serial.println("[BootOTA] Firmware is up to date — continuing normal boot");
|
||||
return;
|
||||
}
|
||||
|
||||
Serial.printf("[BootOTA] Update available: %s → %s — starting flash\n",
|
||||
currentVersionStr.c_str(), availableVersionStr.c_str());
|
||||
|
||||
// ── 4. Stream firmware directly to flash ──────────────────────────────────────
|
||||
// Try each server in order until one succeeds.
|
||||
for (size_t i = 0; i < servers.size(); i++) {
|
||||
String firmwareUrl;
|
||||
if (firmwareDownloadPath.length() > 0) {
|
||||
firmwareUrl = servers[i] + firmwareDownloadPath;
|
||||
} else {
|
||||
firmwareUrl = servers[i] + "/api/firmware/" + hwType + "/" + channel +
|
||||
"/" + availableVersionStr + "/firmware.bin";
|
||||
}
|
||||
|
||||
Serial.printf("[BootOTA] Downloading from server %d/%d: %s\n",
|
||||
i + 1, servers.size(), firmwareUrl.c_str());
|
||||
|
||||
HTTPClient http;
|
||||
http.setTimeout(60000); // 60s for a ~1.4MB binary
|
||||
http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
|
||||
http.begin(firmwareUrl);
|
||||
|
||||
int code = http.GET();
|
||||
if (code != HTTP_CODE_OK) {
|
||||
Serial.printf("[BootOTA] Server %d firmware download HTTP %d — trying next\n", i + 1, code);
|
||||
http.end();
|
||||
continue;
|
||||
}
|
||||
|
||||
int contentLength = http.getSize();
|
||||
if (contentLength <= 0) {
|
||||
Serial.println("[BootOTA] Invalid content-length — trying next server");
|
||||
http.end();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (expectedSize > 0 && (size_t)contentLength != expectedSize) {
|
||||
Serial.printf("[BootOTA] Size mismatch: expected %u got %d — trying next\n",
|
||||
expectedSize, contentLength);
|
||||
http.end();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!Update.begin(contentLength)) {
|
||||
Serial.println("[BootOTA] Update.begin() failed — not enough space");
|
||||
http.end();
|
||||
return; // Partition problem — no point trying other servers
|
||||
}
|
||||
|
||||
Serial.printf("[BootOTA] Writing %d bytes to flash...\n", contentLength);
|
||||
|
||||
WiFiClient* stream = http.getStreamPtr();
|
||||
static uint8_t buf[4096]; // static: off the stack
|
||||
size_t written = 0;
|
||||
size_t lastLoggedPct = 0;
|
||||
|
||||
while (http.connected() && written < (size_t)contentLength) {
|
||||
size_t avail = stream->available();
|
||||
if (avail) {
|
||||
size_t toRead = min(avail, sizeof(buf));
|
||||
size_t bytesRead = stream->readBytes(buf, toRead);
|
||||
if (bytesRead > 0) {
|
||||
if (Update.write(buf, bytesRead) != bytesRead) {
|
||||
Serial.println("[BootOTA] Flash write error — aborting");
|
||||
Update.abort();
|
||||
http.end();
|
||||
goto nextServer; // try next server
|
||||
}
|
||||
written += bytesRead;
|
||||
|
||||
size_t pct = (written * 100) / contentLength;
|
||||
if (pct >= lastLoggedPct + 20) {
|
||||
Serial.printf("[BootOTA] Progress: %u%% (%u / %d bytes)\n",
|
||||
pct, written, contentLength);
|
||||
lastLoggedPct = pct;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
delay(1);
|
||||
}
|
||||
}
|
||||
|
||||
http.end();
|
||||
|
||||
if (written != (size_t)contentLength) {
|
||||
Serial.printf("[BootOTA] Incomplete write: %u / %d bytes — trying next\n",
|
||||
written, contentLength);
|
||||
Update.abort();
|
||||
goto nextServer;
|
||||
}
|
||||
|
||||
if (Update.end(true) && Update.isFinished()) {
|
||||
Serial.println("[BootOTA] Flash complete. Rebooting...");
|
||||
delay(500);
|
||||
ESP.restart();
|
||||
return; // unreachable
|
||||
} else {
|
||||
Serial.printf("[BootOTA] Update.end() failed: %s\n", Update.errorString());
|
||||
goto nextServer;
|
||||
}
|
||||
|
||||
nextServer:;
|
||||
}
|
||||
|
||||
// All servers failed during flash — log and continue normal boot.
|
||||
// The device is still running the old firmware; OTAManager will retry later.
|
||||
Serial.println("[BootOTA] All servers failed during flash — continuing normal boot");
|
||||
}
|
||||
|
||||
void handleFactoryReset() {
|
||||
if (configManager.resetAllToDefaults()) {
|
||||
delay(3000);
|
||||
@@ -242,12 +476,20 @@ void setup()
|
||||
|
||||
// Initialize Configuration (loads factory identity from NVS + user settings from SD)
|
||||
configManager.begin();
|
||||
|
||||
|
||||
// ── BOOT-PHASE OTA CHECK ─────────────────────────────────────────────────────
|
||||
// Must run before any subsystem, task, or timer is created so the full heap
|
||||
// is available and there is zero FreeRTOS contention during the flash write.
|
||||
// If an update is applied this call never returns (device reboots).
|
||||
// If WiFi is unavailable or the server is unreachable it returns immediately.
|
||||
bootOtaCheck();
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
// Apply log level from config (loaded from SD)
|
||||
uint8_t logLevel = configManager.getGeneralConfig().serialLogLevel;
|
||||
Logging::setLevel((Logging::LogLevel)logLevel);
|
||||
LOG_INFO(TAG, "Log level set to %d from configuration", logLevel);
|
||||
|
||||
|
||||
inputManager.begin();
|
||||
inputManager.setFactoryResetLongPressCallback(handleFactoryReset);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user