feat: semver versioning, FastAPI OTA integration, health alerts via MQTT

- Version.hpp: extract FW_VERSION from main.cpp into shared header
- OTAManager: replace uint16_t version with SemVer struct; update API URLs
  to new FastAPI backend (/api/firmware/{hw_type}/{channel}/latest);
  add postDownloadTelemetry() and postFlashTelemetry() for fleet visibility
- ConfigManager: remove fwVersion from DeviceConfig (always read from
  FW_VERSION constant); saveDeviceConfig/loadDeviceConfig are now no-ops;
  fallbackServerUrl replaced with fallbackServerUrls[2] array
- HealthMonitor: add AlertCallback + setAlertCallback() firing on state
  transitions (including CLEARED on recovery)
- CommunicationRouter: wire HealthMonitor alert callback on begin();
  add publishAlert() and publishInfo() for MQTT status topics
- MQTTDriver: add _alertsTopic + _infoTopic; add publishDirect() for
  absolute topic publishing; migrate heartbeat to JsonDocument
- ResponseBuilder, ClientManager, BellEngine: StaticJsonDocument /
  DynamicJsonDocument → JsonDocument; remove dead notifyBellsFired()
- docs: reorganise into architecture/, dev/, features/, reference/

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-14 22:15:27 +02:00
co-authored by Claude Sonnet 4.6
parent c3dc0a79bc
commit d4bd990e53
33 changed files with 1874 additions and 301 deletions
+188 -123
View File
@@ -17,8 +17,8 @@ OTAManager::OTAManager(ConfigManager& configManager)
, _telemetry(nullptr)
, _status(Status::IDLE)
, _lastError(ErrorCode::NONE)
, _availableVersion(0.0f)
, _minVersion(0.0f)
, _availableVersion({0, 0, 0})
, _minVersion({0, 0, 0})
, _expectedFileSize(0)
, _updateAvailable(false)
, _availableChecksum("")
@@ -222,10 +222,10 @@ void OTAManager::checkForUpdates(const String& channel) {
channel.c_str(), _configManager.getHardwareVariant().c_str());
if (checkVersion(channel)) {
uint16_t currentVersion = getCurrentVersion();
LOG_INFO(TAG, "Current version: %u, Available version: %u (Channel: %s)",
currentVersion, _availableVersion, channel.c_str());
SemVer currentVersion = getCurrentVersion();
LOG_INFO(TAG, "Current version: %s, Available version: %s (Channel: %s)",
currentVersion.toString().c_str(), _availableVersion.toString().c_str(), channel.c_str());
if (_availableVersion > currentVersion) {
_updateAvailable = true;
LOG_INFO(TAG, "New version available! Mandatory: %s, Emergency: %s",
@@ -276,10 +276,8 @@ void OTAManager::update(const String& channel) {
}
}
uint16_t OTAManager::getCurrentVersion() const {
String fwVersionStr = _configManager.getFwVersion();
// Parse integer directly: "130" -> 130
return fwVersionStr.toInt();
SemVer OTAManager::getCurrentVersion() const {
return SemVer::parse(FW_VERSION);
}
void OTAManager::setStatus(Status status, ErrorCode error) {
@@ -297,139 +295,140 @@ void OTAManager::notifyProgress(size_t current, size_t total) {
}
}
// ✅ ENHANCED: Version checking with full validation
// Version checking against new FastAPI backend
// API: GET {baseUrl}/api/firmware/{hw_type}/{channel}/latest
// Response: { "version": "1.2.3", "min_fw_version": "1.0.0", "sha256": "abc...",
// "size": 123456, "update_type": "stable", "mandatory": true, "emergency": false }
bool OTAManager::checkVersion(const String& channel) {
std::vector<String> servers = _configManager.getUpdateServers();
auto& updateConfig = _configManager.getUpdateConfig();
String hwType = _configManager.getHardwareVariant();
for (size_t serverIndex = 0; serverIndex < servers.size(); serverIndex++) {
String baseUrl = servers[serverIndex];
String metadataUrl = baseUrl + "/ota/" + _configManager.getHardwareVariant() + "/" + channel + "/metadata.json";
LOG_INFO(TAG, "OTA: Trying server %d/%d: %s", serverIndex + 1, servers.size(), baseUrl.c_str());
String metadataUrl = buildLatestUrl(baseUrl, hwType, channel);
LOG_INFO(TAG, "OTA: Trying server %d/%d: %s", serverIndex + 1, servers.size(), metadataUrl.c_str());
HTTPClient http;
http.setTimeout(updateConfig.timeout);
http.begin(metadataUrl.c_str());
int retryCount = 0;
int httpCode = -1;
// Retry logic for current server
while (retryCount < updateConfig.retries && httpCode != HTTP_CODE_OK) {
if (retryCount > 0) {
LOG_INFO(TAG, "OTA: Retry %d/%d for %s", retryCount + 1, updateConfig.retries, baseUrl.c_str());
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();
http.end();
// Parse JSON metadata
DynamicJsonDocument doc(1024);
DeserializationError error = deserializeJson(doc, jsonStr);
if (error) {
LOG_ERROR(TAG, "OTA: Failed to parse metadata JSON from %s: %s",
baseUrl.c_str(), error.c_str());
continue; // Try next server
LOG_ERROR(TAG, "OTA: Failed to parse metadata JSON from server %d: %s", serverIndex + 1, error.c_str());
continue;
}
// Extract metadata - all integers now
_availableVersion = doc["version"].as<uint16_t>();
_availableChecksum = doc["checksum"].as<String>();
_updateChannel = doc["channel"].as<String>();
_isMandatory = doc["mandatory"].as<bool>();
_isEmergency = doc["emergency"].as<bool>();
_minVersion = doc["minVersion"].as<uint16_t>();
_expectedFileSize = doc["fileSize"].as<size_t>();
// ✅ NEW: Validate channel matches requested
if (_updateChannel != channel) {
LOG_ERROR(TAG, "OTA: Channel mismatch! Requested: %s, Got: %s",
channel.c_str(), _updateChannel.c_str());
// FastAPI response fields
const char* versionStr = doc["version"] | "";
if (strlen(versionStr) == 0) {
LOG_ERROR(TAG, "OTA: Missing 'version' field in metadata from server %d", serverIndex + 1);
continue;
}
_availableVersion = SemVer::parse(String(versionStr));
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;
_isMandatory = doc["mandatory"] | false;
_isEmergency = doc["emergency"] | false;
_updateChannel = channel; // channel is what we requested — server returns update_type
// Validate channel matches what server says
const char* serverUpdateType = doc["update_type"] | "";
if (strlen(serverUpdateType) > 0 && String(serverUpdateType) != channel) {
LOG_ERROR(TAG, "OTA: Channel mismatch! Requested: %s, Got: %s", channel.c_str(), serverUpdateType);
_lastError = ErrorCode::CHANNEL_MISMATCH;
continue; // Try next server
continue;
}
// Validate hardware variant matches
String hwVariant = doc["hardwareVariant"].as<String>();
String ourHardwareVariant = _configManager.getHardwareVariant();
if (!hwVariant.isEmpty() && hwVariant != ourHardwareVariant) {
LOG_ERROR(TAG, "OTA: Hardware variant mismatch! Expected: %s, Got: %s",
ourHardwareVariant.c_str(), hwVariant.c_str());
continue; // Try next server
// Validate version parsed correctly
if (_availableVersion.isZero()) {
LOG_ERROR(TAG, "OTA: Invalid version string '%s' from server %d", versionStr, serverIndex + 1);
continue;
}
// ✅ NEW: Check minVersion compatibility
uint16_t currentVersion = getCurrentVersion();
if (_minVersion > 0 && currentVersion < _minVersion) {
LOG_ERROR(TAG, "OTA: Current version %u is below minimum required %u",
currentVersion, _minVersion);
LOG_ERROR(TAG, "OTA: Intermediate update required first - cannot proceed");
_lastError = ErrorCode::VERSION_TOO_LOW;
continue; // Try next server
// 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;
}
if (_availableVersion == 0) {
LOG_ERROR(TAG, "OTA: Invalid version in metadata from %s", baseUrl.c_str());
continue; // Try next server
// 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",
versionStr, _minVersion.toString().c_str());
}
if (_availableChecksum.length() != 64) { // SHA256 is 64 hex characters
LOG_ERROR(TAG, "OTA: Invalid checksum in metadata from %s", baseUrl.c_str());
continue; // Try next server
}
LOG_INFO(TAG, "OTA: Successfully got metadata from %s", baseUrl.c_str());
LOG_INFO(TAG, "OTA: Expected file size: %u bytes, Min version: %u",
_expectedFileSize, _minVersion);
return true; // Success!
LOG_INFO(TAG, "OTA: Metadata OK from server %d — version=%s, size=%u, mandatory=%s, emergency=%s",
serverIndex + 1, versionStr, _expectedFileSize,
_isMandatory ? "YES" : "NO", _isEmergency ? "YES" : "NO");
return true;
} else {
LOG_ERROR(TAG, "OTA: Server %s failed after %d retries. HTTP error: %d",
baseUrl.c_str(), updateConfig.retries, httpCode);
LOG_ERROR(TAG, "OTA: Server %d failed after %d retries. HTTP code: %d",
serverIndex + 1, updateConfig.retries, httpCode);
http.end();
}
}
// All servers failed
LOG_ERROR(TAG, "OTA: All %d servers failed to provide metadata", servers.size());
_lastError = ErrorCode::HTTP_ERROR;
return false;
}
// ✅ ENHANCED: Download and install with size validation
// Download and install firmware from new FastAPI backend
// API: GET {baseUrl}/api/firmware/{hw_type}/{channel}/{version}/firmware.bin
bool OTAManager::downloadAndInstall(const String& channel) {
std::vector<String> servers = _configManager.getUpdateServers();
String hwType = _configManager.getHardwareVariant();
String toVersion = _availableVersion.toString();
for (size_t serverIndex = 0; serverIndex < servers.size(); serverIndex++) {
String baseUrl = servers[serverIndex];
String firmwareUrl = baseUrl + "/ota/" + _configManager.getHardwareVariant() + "/" + channel + "/firmware.bin";
String baseUrl = servers[serverIndex];
String firmwareUrl = buildFirmwareUrl(baseUrl, hwType, channel, toVersion);
LOG_INFO(TAG, "OTA: Trying firmware download from server %d/%d: %s",
serverIndex + 1, servers.size(), baseUrl.c_str());
serverIndex + 1, servers.size(), firmwareUrl.c_str());
// 🔥 Download directly to flash (bypassing problematic SD card writes)
if (downloadDirectToFlash(firmwareUrl, _expectedFileSize)) {
LOG_INFO(TAG, "✅ OTA update successful!");
String fromVersion = getCurrentVersion().toString();
if (downloadDirectToFlash(firmwareUrl, _expectedFileSize, fromVersion, toVersion, channel)) {
LOG_INFO(TAG, "OTA: Firmware download and flash successful from server %d", serverIndex + 1);
return true;
} else {
LOG_WARNING(TAG, "OTA: Firmware download failed from %s, trying next server", baseUrl.c_str());
LOG_WARNING(TAG, "OTA: Firmware download failed from server %d, trying next", serverIndex + 1);
}
}
// All servers failed
LOG_ERROR(TAG, "OTA: All %d servers failed to provide firmware", servers.size());
return false;
}
// 🔥 NEW: Download directly to flash memory, bypassing SD card
bool OTAManager::downloadDirectToFlash(const String& url, size_t expectedSize) {
bool OTAManager::downloadDirectToFlash(const String& url, size_t expectedSize, const String& fromVersion, const String& toVersion, const String& channel) {
LOG_INFO(TAG, "OTA: Starting direct-to-flash download (bypassing SD card)");
HTTPClient http;
@@ -570,16 +569,16 @@ bool OTAManager::downloadDirectToFlash(const String& url, size_t expectedSize) {
return false;
}
// Binary is fully written to the staged partition — report download event
postDownloadTelemetry(fromVersion, toVersion, channel);
if (Update.end(true)) { // true = set new boot partition
LOG_INFO(TAG, "OTA: Update complete!");
if (Update.isFinished()) {
setStatus(Status::SUCCESS);
// Partition committed — report flash event before reboot
postFlashTelemetry(fromVersion, toVersion, channel);
LOG_INFO(TAG, "OTA: Firmware update successful. Rebooting...");
// Update version in config
_configManager.setFwVersion(String(_availableVersion));
_configManager.saveDeviceConfig();
delay(1000);
ESP.restart();
return true;
@@ -998,10 +997,6 @@ bool OTAManager::installFromSD(const String& filePath) {
}
delay(1000);
// Version is already an integer - just convert to string: 130 -> "130"
_configManager.setFwVersion(String(_availableVersion));
_configManager.saveDeviceConfig();
delay(500);
ESP.restart();
return true;
} else {
@@ -1088,7 +1083,7 @@ bool OTAManager::performManualUpdate(const String& channel) {
// CUSTOM FIRMWARE UPDATE
// ════════════════════════════════════════════════════════════════════════════
bool OTAManager::performCustomUpdate(const String& firmwareUrl, const String& checksum, size_t fileSize, uint16_t version) {
bool OTAManager::performCustomUpdate(const String& firmwareUrl, const String& checksum, size_t fileSize, const String& version) {
if (_status != Status::IDLE) {
LOG_WARNING(TAG, "OTA update already in progress");
return false;
@@ -1109,25 +1104,15 @@ bool OTAManager::performCustomUpdate(const String& firmwareUrl, const String& ch
LOG_INFO(TAG, " Checksum: %s (NOTE: ESP32 will validate after flash)", checksum.c_str());
}
if (version > 0) {
LOG_INFO(TAG, " Target Version: %u", version);
if (!version.isEmpty()) {
LOG_INFO(TAG, " Target Version: %s", version.c_str());
}
setStatus(Status::DOWNLOADING);
// Download directly to flash
bool result = downloadDirectToFlash(firmwareUrl, fileSize);
if (result) {
// Update version in config if provided
if (version > 0) {
_configManager.setFwVersion(String(version));
_configManager.saveDeviceConfig();
LOG_INFO(TAG, "✅ Custom firmware version %u saved to NVS", version);
} else {
LOG_WARNING(TAG, "⚠️ No version provided - NVS version unchanged");
}
LOG_INFO(TAG, "🚀 Custom firmware installed - device will reboot");
} else {
LOG_ERROR(TAG, "❌ Custom firmware installation failed");
@@ -1145,20 +1130,101 @@ void OTAManager::setHardwareVariant(const String& variant) {
LOG_WARNING(TAG, "OTAManager::setHardwareVariant is deprecated. Use ConfigManager::setHardwareVariant instead");
}
// URL builders for multi-channel architecture
String OTAManager::buildChannelUrl(const String& channel) const {
auto& updateConfig = _configManager.getUpdateConfig();
String baseUrl = updateConfig.fallbackServerUrl;
return baseUrl + "/" + _configManager.getHardwareVariant() + "/" + channel + "/";
// URL builders for FastAPI backend
// GET /api/firmware/{hw_type}/{channel}/latest?current_version={semver}
// Passing current_version lets the server resolve upgrade chains and return the
// correct next hop instead of the absolute latest.
String OTAManager::buildLatestUrl(const String& baseUrl, const String& hwType, const String& channel) const {
String currentVersion = getCurrentVersion().toString();
return baseUrl + "/api/firmware/" + hwType + "/" + channel + "/latest?current_version=" + currentVersion;
}
String OTAManager::buildMetadataUrl(const String& channel) const {
return buildChannelUrl(channel) + "metadata.json";
// GET /api/firmware/{hw_type}/{channel}/{version}/info
String OTAManager::buildVersionInfoUrl(const String& baseUrl, const String& hwType, const String& channel, const String& version) const {
return baseUrl + "/api/firmware/" + hwType + "/" + channel + "/" + version + "/info";
}
String OTAManager::buildFirmwareUrl(const String& channel) const {
return buildChannelUrl(channel) + "firmware.bin";
// GET /api/firmware/{hw_type}/{channel}/{version}/firmware.bin
String OTAManager::buildFirmwareUrl(const String& baseUrl, const String& hwType, const String& channel, const String& version) const {
return baseUrl + "/api/firmware/" + hwType + "/" + channel + "/" + version + "/firmware.bin";
}
// ═════════════════════════════════════════════════════════════════════════════
// OTA TELEMETRY - POST events to backend for fleet visibility
// ═════════════════════════════════════════════════════════════════════════════
// Called after the firmware binary has been fully downloaded and written to flash,
// but BEFORE Update.end() is called (i.e. the new partition is staged but not yet active).
// POST /api/ota/events/download
void OTAManager::postDownloadTelemetry(const String& fromVersion, const String& toVersion, const String& channel) {
if (WiFi.status() != WL_CONNECTED) return;
std::vector<String> servers = _configManager.getUpdateServers();
if (servers.empty()) return;
// Use primary server only — this is best-effort, not critical path
String url = servers[0] + "/api/ota/events/download";
DynamicJsonDocument doc(256);
doc["device_uid"] = _configManager.getDeviceUID();
doc["hw_type"] = _configManager.getHardwareVariant();
doc["hw_version"] = _configManager.getHwVersion();
doc["from_version"] = fromVersion;
doc["to_version"] = toVersion;
doc["channel"] = channel;
String body;
serializeJson(doc, body);
HTTPClient http;
http.begin(url.c_str());
http.addHeader("Content-Type", "application/json");
http.setTimeout(5000);
int code = http.POST(body);
if (code == HTTP_CODE_OK || code == HTTP_CODE_CREATED || code == 204) {
LOG_INFO(TAG, "OTA: Download event reported to backend (HTTP %d)", code);
} else {
LOG_WARNING(TAG, "OTA: Download event POST failed (HTTP %d) — non-critical, continuing", code);
}
http.end();
}
// Called immediately after Update.end() succeeds — the new firmware is committed
// to the boot partition and the device is about to restart.
// POST /api/ota/events/flash
void OTAManager::postFlashTelemetry(const String& fromVersion, const String& toVersion, const String& channel) {
if (WiFi.status() != WL_CONNECTED) return;
std::vector<String> servers = _configManager.getUpdateServers();
if (servers.empty()) return;
String url = servers[0] + "/api/ota/events/flash";
DynamicJsonDocument doc(256);
doc["device_uid"] = _configManager.getDeviceUID();
doc["hw_type"] = _configManager.getHardwareVariant();
doc["hw_version"] = _configManager.getHwVersion();
doc["from_version"] = fromVersion;
doc["to_version"] = toVersion;
doc["channel"] = channel;
doc["sha256"] = _availableChecksum;
String body;
serializeJson(doc, body);
HTTPClient http;
http.begin(url.c_str());
http.addHeader("Content-Type", "application/json");
http.setTimeout(5000);
int code = http.POST(body);
if (code == HTTP_CODE_OK || code == HTTP_CODE_CREATED || code == 204) {
LOG_INFO(TAG, "OTA: Flash event reported to backend (HTTP %d)", code);
} else {
LOG_WARNING(TAG, "OTA: Flash event POST failed (HTTP %d) — non-critical, continuing", code);
}
http.end();
}
// ✅ NEW: Check if player is currently active
@@ -1226,9 +1292,8 @@ bool OTAManager::isHealthy() const {
return false;
}
String fwVersion = _configManager.getFwVersion();
if (fwVersion.isEmpty() || fwVersion == "0") {
LOG_DEBUG(TAG, "OTAManager: Unhealthy - Invalid firmware version: %s", fwVersion.c_str());
if (getCurrentVersion().isZero()) {
LOG_DEBUG(TAG, "OTAManager: Unhealthy - Firmware version is 0.0.0");
return false;
}
+17 -10
View File
@@ -28,6 +28,7 @@
#include "../FileManager/FileManager.hpp"
#include "../Telemetry/Telemetry.hpp"
#include "../TimeKeeper/TimeKeeper.hpp"
#include "../Version.hpp"
class ConfigManager; // Forward declaration
class Player; // Forward declaration for idle check
@@ -83,7 +84,7 @@ public:
void checkFirmwareUpdateFromSD(); // Check SD for firmware update
bool performManualUpdate(); // Manual update triggered by app
bool performManualUpdate(const String& channel); // Manual update from specific channel
bool performCustomUpdate(const String& firmwareUrl, const String& checksum = "", size_t fileSize = 0, uint16_t version = 0); // Custom firmware update
bool performCustomUpdate(const String& firmwareUrl, const String& checksum = "", size_t fileSize = 0, const String& version = ""); // Custom firmware update
// Hardware identification
String getHardwareVariant() const;
@@ -92,8 +93,8 @@ public:
// Status and info
Status getStatus() const { return _status; }
ErrorCode getLastError() const { return _lastError; }
uint16_t getCurrentVersion() const;
uint16_t getAvailableVersion() const { return _availableVersion; }
SemVer getCurrentVersion() const;
SemVer getAvailableVersion() const { return _availableVersion; }
bool isUpdateAvailable() const { return _updateAvailable; }
// Callbacks
@@ -115,8 +116,8 @@ private:
Telemetry* _telemetry; // Telemetry reference for freeze mode
Status _status;
ErrorCode _lastError;
uint16_t _availableVersion;
uint16_t _minVersion; // NEW: Minimum required version
SemVer _availableVersion;
SemVer _minVersion;
size_t _expectedFileSize; // NEW: Expected firmware file size
bool _updateAvailable;
String _availableChecksum;
@@ -156,14 +157,20 @@ private:
bool checkChannelsMetadata();
bool downloadAndInstall();
bool downloadAndInstall(const String& channel);
bool downloadDirectToFlash(const String& url, size_t expectedSize); // NEW: Direct to flash (bypasses SD)
bool downloadToSD(const String& url, const String& expectedChecksum, size_t expectedSize); // OLD: Via SD card
bool downloadDirectToFlash(const String& url, size_t expectedSize, const String& fromVersion, const String& toVersion, const String& channel);
bool downloadToSD(const String& url, const String& expectedChecksum, size_t expectedSize);
bool verifyChecksum(const String& filePath, const String& expectedChecksum);
String calculateSHA256(const String& filePath);
bool installFromSD(const String& filePath);
String buildChannelUrl(const String& channel) const;
String buildMetadataUrl(const String& channel) const;
String buildFirmwareUrl(const String& channel) const;
// FastAPI URL builders
String buildLatestUrl(const String& baseUrl, const String& hwType, const String& channel) const;
String buildVersionInfoUrl(const String& baseUrl, const String& hwType, const String& channel, const String& version) const;
String buildFirmwareUrl(const String& baseUrl, const String& hwType, const String& channel, const String& version) const;
// OTA telemetry — best-effort POSTs, never block or fail the update
void postDownloadTelemetry(const String& fromVersion, const String& toVersion, const String& channel);
void postFlashTelemetry(const String& fromVersion, const String& toVersion, const String& channel);
// NEW: Helper methods
bool isPlayerActive() const;