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:
@@ -316,10 +316,6 @@ void BellEngine::activateNote(uint16_t note) {
|
||||
if (!bellDurations.empty()) {
|
||||
_outputManager.fireOutputsBatchForDuration(bellDurations);
|
||||
LOG_VERBOSE(TAG, "BellEngine - 🔥 Batch Fired %d bells Simultaneously !", bellDurations.size());
|
||||
|
||||
// 🔔 NOTIFY WEBSOCKET CLIENTS OF BELL DINGS!
|
||||
// * deactivated currently, since unstable and causes performance issues *
|
||||
// notifyBellsFired(firedBellIndices);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -345,34 +341,6 @@ void BellEngine::emergencyShutdown() {
|
||||
_outputManager.emergencyShutdown();
|
||||
}
|
||||
|
||||
void BellEngine::notifyBellsFired(const std::vector<uint8_t>& bellIndices) {
|
||||
if (!_communicationManager || bellIndices.empty()) {
|
||||
|
||||
return; // No communication manager or no bells fired
|
||||
}
|
||||
|
||||
try {
|
||||
// Create notification message
|
||||
StaticJsonDocument<256> dingMsg;
|
||||
dingMsg["status"] = "INFO";
|
||||
dingMsg["type"] = "ding";
|
||||
|
||||
// Create payload array with fired bell numbers (1-indexed for display)
|
||||
JsonArray bellsArray = dingMsg["payload"].to<JsonArray>();
|
||||
for (uint8_t bellIndex : bellIndices) {
|
||||
bellsArray.add(bellIndex); // Already converted to 1-indexed in activateNote
|
||||
}
|
||||
|
||||
// Send notification to WebSocket clients only (not MQTT)
|
||||
_communicationManager->broadcastToAllWebSocketClients(dingMsg);
|
||||
|
||||
LOG_DEBUG(TAG, "BellEngine - 🔔 DING notification sent for %d bells", bellIndices.size());
|
||||
|
||||
} catch (...) {
|
||||
LOG_WARNING(TAG, "BellEngine - ❌ Failed to send ding notification");
|
||||
}
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
// HEALTH CHECK IMPLEMENTATION
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -357,13 +357,6 @@ private:
|
||||
*/
|
||||
void checkAndNotifyOverloads();
|
||||
|
||||
/**
|
||||
* @brief Notify WebSocket clients of fired bells
|
||||
* @param bellIndices Vector of bell indices that were fired (1-indexed)
|
||||
*
|
||||
* Sends INFO/ding message to WebSocket clients only (not MQTT)
|
||||
*/
|
||||
void notifyBellsFired(const std::vector<uint8_t>& bellIndices);
|
||||
};
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -134,11 +134,11 @@ void ClientManager::cleanupDisconnectedClients() {
|
||||
}
|
||||
|
||||
String ClientManager::getClientListJson() const {
|
||||
StaticJsonDocument<512> doc;
|
||||
JsonArray clients = doc.createNestedArray("clients");
|
||||
|
||||
JsonDocument doc;
|
||||
JsonArray clients = doc["clients"].to<JsonArray>();
|
||||
|
||||
for (const auto& pair : _clients) {
|
||||
JsonObject client = clients.createNestedObject();
|
||||
JsonObject client = clients.add<JsonObject>();
|
||||
client["id"] = pair.first;
|
||||
client["type"] = deviceTypeToString(pair.second.deviceType);
|
||||
client["connected"] = isValidClient(pair.second.client);
|
||||
|
||||
@@ -129,6 +129,16 @@ void CommunicationRouter::begin() {
|
||||
// ── Register all domain handlers ─────────────────────────────────────────
|
||||
registerHandlers();
|
||||
|
||||
// ── Wire HealthMonitor alert callback ────────────────────────────────────
|
||||
if (_healthMonitor) {
|
||||
_healthMonitor->setAlertCallback(
|
||||
[this](const String& subsystem, const String& newState, const String& message) {
|
||||
publishAlert(subsystem, newState, message);
|
||||
}
|
||||
);
|
||||
LOG_INFO(TAG, "HealthMonitor alert callback registered");
|
||||
}
|
||||
|
||||
LOG_INFO(TAG, "Communication Router ready — CommandBus active");
|
||||
}
|
||||
|
||||
@@ -263,7 +273,7 @@ void CommunicationRouter::setupUdpDiscovery() {
|
||||
if (msg.indexOf("discover") >= 0) {
|
||||
shouldReply = true;
|
||||
} else {
|
||||
StaticJsonDocument<128> req;
|
||||
JsonDocument req;
|
||||
if (!deserializeJson(req, msg)) {
|
||||
shouldReply = (req["op"] == "discover");
|
||||
}
|
||||
@@ -271,7 +281,7 @@ void CommunicationRouter::setupUdpDiscovery() {
|
||||
|
||||
if (!shouldReply) return;
|
||||
|
||||
StaticJsonDocument<256> doc;
|
||||
JsonDocument doc;
|
||||
doc["op"] = "discover_reply";
|
||||
doc["svc"] = "vesper";
|
||||
doc["ver"] = 1;
|
||||
@@ -381,7 +391,7 @@ void CommunicationRouter::sendBellOverloadNotification(
|
||||
const std::vector<uint16_t>& bellLoads,
|
||||
const String& severity) {
|
||||
|
||||
StaticJsonDocument<512> doc;
|
||||
JsonDocument doc;
|
||||
doc["status"] = "INFO";
|
||||
doc["type"] = "bell_overload";
|
||||
|
||||
@@ -399,6 +409,41 @@ void CommunicationRouter::sendBellOverloadNotification(
|
||||
bellNumbers.size(), severity.c_str());
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Alert / Info publishing
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
void CommunicationRouter::publishAlert(const String& subsystem, const String& newState, const String& message) {
|
||||
if (!_mqttClient.isConnected()) return;
|
||||
|
||||
JsonDocument doc;
|
||||
doc["subsystem"] = subsystem;
|
||||
doc["state"] = newState;
|
||||
if (!message.isEmpty()) {
|
||||
doc["msg"] = message;
|
||||
}
|
||||
|
||||
String out;
|
||||
serializeJson(doc, out);
|
||||
_mqttClient.publishDirect(_mqttClient.getAlertsTopic(), out, 1, false);
|
||||
LOG_DEBUG(TAG, "Alert published: %s → %s", subsystem.c_str(), newState.c_str());
|
||||
}
|
||||
|
||||
void CommunicationRouter::publishInfo(const String& type, const JsonDocument& payload) {
|
||||
if (!_mqttClient.isConnected()) return;
|
||||
|
||||
JsonDocument doc;
|
||||
doc["type"] = type;
|
||||
if (!payload.isNull()) {
|
||||
doc["payload"] = payload;
|
||||
}
|
||||
|
||||
String out;
|
||||
serializeJson(doc, out);
|
||||
_mqttClient.publishDirect(_mqttClient.getInfoTopic(), out, 0, false);
|
||||
LOG_DEBUG(TAG, "Info published: %s", type.c_str());
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Network state callbacks
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -97,6 +97,26 @@ public:
|
||||
const std::vector<uint16_t>& bellLoads,
|
||||
const String& severity);
|
||||
|
||||
/**
|
||||
* @brief Publish a subsystem alert to vesper/{id}/status/alerts.
|
||||
* Called by HealthMonitor when a subsystem state changes.
|
||||
* Only publishes on actual state change; no-ops if MQTT not connected.
|
||||
*
|
||||
* @param subsystem Subsystem name e.g. "BellEngine"
|
||||
* @param newState New state string: "HEALTHY" | "WARNING" | "CRITICAL" | "FAILED"
|
||||
* @param message Human-readable description (empty string on CLEARED)
|
||||
*/
|
||||
void publishAlert(const String& subsystem, const String& newState, const String& message = "");
|
||||
|
||||
/**
|
||||
* @brief Publish a general device info event to vesper/{id}/status/info.
|
||||
* Used for state changes such as playback start/stop, reboot reason, etc.
|
||||
*
|
||||
* @param type Event type string e.g. "playback_started"
|
||||
* @param payload JSON object with event-specific fields (pass an empty doc for no payload)
|
||||
*/
|
||||
void publishInfo(const String& type, const JsonDocument& payload);
|
||||
|
||||
// Network state callbacks (called by Networking)
|
||||
void onNetworkConnected();
|
||||
void onNetworkDisconnected();
|
||||
|
||||
@@ -76,10 +76,14 @@ void MQTTDriver::begin() {
|
||||
// Build topic strings (cache for performance)
|
||||
String deviceUID = _configManager.getDeviceUID();
|
||||
_controlTopic = "vesper/" + deviceUID + "/control";
|
||||
_dataTopic = "vesper/" + deviceUID + "/data";
|
||||
_clientId = "vesper-" + deviceUID;
|
||||
|
||||
LOG_INFO(TAG, "MQTT Topics: control=%s, data=%s", _controlTopic.c_str(), _dataTopic.c_str());
|
||||
_dataTopic = "vesper/" + deviceUID + "/data";
|
||||
_alertsTopic = "vesper/" + deviceUID + "/status/alerts";
|
||||
_infoTopic = "vesper/" + deviceUID + "/status/info";
|
||||
_clientId = "vesper-" + deviceUID;
|
||||
|
||||
LOG_INFO(TAG, "MQTT Topics: control=%s, data=%s, alerts=%s, info=%s",
|
||||
_controlTopic.c_str(), _dataTopic.c_str(),
|
||||
_alertsTopic.c_str(), _infoTopic.c_str());
|
||||
|
||||
// Setup event handlers
|
||||
_mqttClient.onConnect([this](bool sessionPresent) {
|
||||
@@ -165,6 +169,17 @@ uint16_t MQTTDriver::publish(const String& topic, const String& payload, int qos
|
||||
return packetId;
|
||||
}
|
||||
|
||||
uint16_t MQTTDriver::publishDirect(const String& fullTopic, const String& payload, int qos, bool retain) {
|
||||
if (!_mqttClient.connected()) {
|
||||
return 0;
|
||||
}
|
||||
uint16_t packetId = _mqttClient.publish(fullTopic.c_str(), qos, retain, payload.c_str());
|
||||
if (packetId > 0) {
|
||||
LOG_DEBUG(TAG, "Published to %s (packetId=%d)", fullTopic.c_str(), packetId);
|
||||
}
|
||||
return packetId;
|
||||
}
|
||||
|
||||
void MQTTDriver::setCallback(MessageCallback callback) {
|
||||
_messageCallback = callback;
|
||||
}
|
||||
@@ -361,11 +376,11 @@ void MQTTDriver::publishHeartbeat() {
|
||||
}
|
||||
|
||||
// Build heartbeat JSON message
|
||||
StaticJsonDocument<512> doc;
|
||||
JsonDocument doc;
|
||||
doc["status"] = "INFO";
|
||||
doc["type"] = "heartbeat";
|
||||
|
||||
JsonObject payload = doc.createNestedObject("payload");
|
||||
|
||||
JsonObject payload = doc["payload"].to<JsonObject>();
|
||||
|
||||
// Device ID from NVS
|
||||
payload["device_id"] = _configManager.getDeviceUID();
|
||||
|
||||
@@ -49,6 +49,7 @@ public:
|
||||
/**
|
||||
* @brief Publish message to MQTT
|
||||
* @param topic Topic to publish to (relative, will prepend "vesper/{deviceID}/")
|
||||
* If empty string — publishes to the data topic.
|
||||
* @param payload Message payload
|
||||
* @param qos QoS level (0, 1, or 2)
|
||||
* @param retain Retain flag
|
||||
@@ -56,6 +57,16 @@ public:
|
||||
*/
|
||||
uint16_t publish(const String& topic, const String& payload, int qos = 0, bool retain = false);
|
||||
|
||||
/**
|
||||
* @brief Publish to an absolute, fully-qualified topic (no prefix applied).
|
||||
* @param fullTopic Complete topic string
|
||||
* @param payload Message payload
|
||||
* @param qos QoS level (0, 1, or 2)
|
||||
* @param retain Retain flag
|
||||
* @return Packet ID (0 if failed)
|
||||
*/
|
||||
uint16_t publishDirect(const String& fullTopic, const String& payload, int qos = 0, bool retain = false);
|
||||
|
||||
/**
|
||||
* @brief Set message received callback
|
||||
*/
|
||||
@@ -66,6 +77,10 @@ public:
|
||||
*/
|
||||
bool isConnected() const;
|
||||
|
||||
/** @brief Full topic strings (read-only, available after begin()) */
|
||||
const String& getAlertsTopic() const { return _alertsTopic; }
|
||||
const String& getInfoTopic() const { return _infoTopic; }
|
||||
|
||||
/**
|
||||
* @brief Handle network connection callback
|
||||
*/
|
||||
@@ -86,7 +101,9 @@ private:
|
||||
// Device topic strings (cached for performance)
|
||||
String _controlTopic;
|
||||
String _dataTopic;
|
||||
String _clientId; // Store client ID to keep it alive
|
||||
String _alertsTopic; // vesper/{id}/status/alerts
|
||||
String _infoTopic; // vesper/{id}/status/info
|
||||
String _clientId; // Store client ID to keep it alive
|
||||
|
||||
/**
|
||||
* @brief Subscribe to control topic
|
||||
|
||||
@@ -98,7 +98,7 @@ void UARTDriver::processLine(const char* line) {
|
||||
if (strlen(line) == 0) return;
|
||||
|
||||
// Parse JSON
|
||||
StaticJsonDocument<1024> doc;
|
||||
JsonDocument doc;
|
||||
DeserializationError error = deserializeJson(doc, line);
|
||||
|
||||
if (error) {
|
||||
@@ -106,7 +106,7 @@ void UARTDriver::processLine(const char* line) {
|
||||
_errorCount++;
|
||||
|
||||
// Send error response back
|
||||
StaticJsonDocument<256> errorDoc;
|
||||
JsonDocument errorDoc;
|
||||
errorDoc["status"] = "ERROR";
|
||||
errorDoc["type"] = "parse_error";
|
||||
errorDoc["payload"] = error.c_str();
|
||||
|
||||
@@ -132,7 +132,7 @@ void WebSocketDriver::onData(AsyncWebSocketClient* client, void* arg, uint8_t* d
|
||||
LOG_DEBUG(TAG, "WebSocket client #%u sent: %s", client->id(), payload);
|
||||
|
||||
// Parse JSON
|
||||
StaticJsonDocument<2048> doc;
|
||||
JsonDocument doc;
|
||||
DeserializationError error = deserializeJson(doc, payload);
|
||||
|
||||
if (error) {
|
||||
|
||||
@@ -103,7 +103,7 @@ CommandResult FirmwareHandler::handleOtaCustom(const CommandEnvelope& e) {
|
||||
String url = e.contents["firmware_url"].as<String>();
|
||||
String checksum = e.contents["checksum"] | String("");
|
||||
size_t fileSize = e.contents["file_size"] | 0;
|
||||
uint16_t version = e.contents["version"] | 0;
|
||||
String version = e.contents["version"].as<String>();
|
||||
|
||||
LOG_WARNING(TAG, "Custom OTA update: %s", url.c_str());
|
||||
_otaManager.performCustomUpdate(url, checksum, fileSize, version);
|
||||
|
||||
@@ -21,7 +21,7 @@ String ResponseBuilder::fromResult(const CommandResult& result) {
|
||||
}
|
||||
|
||||
// Static member initialization
|
||||
StaticJsonDocument<512> ResponseBuilder::_responseDoc;
|
||||
JsonDocument ResponseBuilder::_responseDoc;
|
||||
|
||||
String ResponseBuilder::success(const String& type, const String& payload) {
|
||||
return buildResponse(Status::SUCCESS, type, payload);
|
||||
@@ -52,13 +52,13 @@ String ResponseBuilder::pong() {
|
||||
}
|
||||
|
||||
String ResponseBuilder::deviceStatus(PlayerStatus playerStatus, uint32_t timeElapsed, uint64_t projectedRunTime, const uint32_t strikeCounters[16]) {
|
||||
DynamicJsonDocument statusDoc(1024); // Increased size for strikeCounters array
|
||||
JsonDocument statusDoc;
|
||||
|
||||
statusDoc["status"] = "SUCCESS";
|
||||
statusDoc["type"] = "current_status";
|
||||
|
||||
// Create payload object with the exact format expected by Flutter
|
||||
JsonObject payload = statusDoc.createNestedObject("payload");
|
||||
JsonObject payload = statusDoc["payload"].to<JsonObject>();
|
||||
|
||||
// Convert PlayerStatus to string
|
||||
const char* statusStr;
|
||||
@@ -83,7 +83,7 @@ String ResponseBuilder::deviceStatus(PlayerStatus playerStatus, uint32_t timeEla
|
||||
payload["projected_run_time"] = projectedRunTime; // NEW: total projected duration
|
||||
|
||||
// Add strike counters array
|
||||
JsonArray strikeCountersArray = payload.createNestedArray("strike_counters");
|
||||
JsonArray strikeCountersArray = payload["strike_counters"].to<JsonArray>();
|
||||
for (uint8_t i = 0; i < 16; i++) {
|
||||
strikeCountersArray.add(strikeCounters[i]);
|
||||
}
|
||||
|
||||
@@ -90,5 +90,5 @@ public:
|
||||
private:
|
||||
// Internal helper methods
|
||||
static const char* statusToString(Status status);
|
||||
static StaticJsonDocument<512> _responseDoc; // Reusable document for efficiency
|
||||
static JsonDocument _responseDoc; // Reusable document for efficiency
|
||||
};
|
||||
|
||||
@@ -88,7 +88,7 @@ void HTTPTransport::handleCommandRequest(AsyncWebServerRequest* request,
|
||||
envelope.command = cmd;
|
||||
envelope.version = doc["v"] | 2;
|
||||
|
||||
if (doc.containsKey("contents")) {
|
||||
if (doc["contents"].is<JsonVariant>()) {
|
||||
envelope.contents.set(doc["contents"]);
|
||||
}
|
||||
|
||||
|
||||
@@ -256,51 +256,13 @@ bool ConfigManager::saveToSD() {
|
||||
return success;
|
||||
}
|
||||
|
||||
// Device configuration now only handles firmware version (identity is in NVS)
|
||||
// Firmware version is now owned by the binary (FW_VERSION in Version.hpp).
|
||||
// saveDeviceConfig / loadDeviceConfig are no-ops kept for call-site compatibility.
|
||||
bool ConfigManager::saveDeviceConfig() {
|
||||
if (!ensureSDCard()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
StaticJsonDocument<256> doc;
|
||||
doc["fwVersion"] = deviceConfig.fwVersion;
|
||||
|
||||
char buffer[256];
|
||||
size_t len = serializeJson(doc, buffer, sizeof(buffer));
|
||||
|
||||
if (len == 0 || len >= sizeof(buffer)) {
|
||||
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to serialize device config JSON");
|
||||
return false;
|
||||
}
|
||||
|
||||
saveFileToSD("/settings", "deviceConfig.json", buffer);
|
||||
LOG_DEBUG(TAG, "ConfigManager - Device config saved - FwVer: %s", deviceConfig.fwVersion.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ConfigManager::loadDeviceConfig() {
|
||||
if (!ensureSDCard()) return false;
|
||||
|
||||
File file = SD.open("/settings/deviceConfig.json", FILE_READ);
|
||||
if (!file) {
|
||||
LOG_WARNING(TAG, "ConfigManager - ⚠️ Device config file not found - using firmware version default");
|
||||
return false;
|
||||
}
|
||||
|
||||
StaticJsonDocument<512> doc;
|
||||
DeserializationError error = deserializeJson(doc, file);
|
||||
file.close();
|
||||
|
||||
if (error) {
|
||||
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to parse device config from SD: %s", error.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
if (doc.containsKey("fwVersion")) {
|
||||
deviceConfig.fwVersion = doc["fwVersion"].as<String>();
|
||||
LOG_VERBOSE(TAG, "ConfigManager - Firmware version loaded from SD: %s", deviceConfig.fwVersion.c_str());
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -790,7 +752,9 @@ std::vector<String> ConfigManager::getUpdateServers() const {
|
||||
for (const String& server : updateServers) {
|
||||
servers.push_back(server);
|
||||
}
|
||||
servers.push_back(updateConfig.fallbackServerUrl);
|
||||
for (const String& url : updateConfig.fallbackServerUrls) {
|
||||
if (!url.isEmpty()) servers.push_back(url);
|
||||
}
|
||||
return servers;
|
||||
}
|
||||
|
||||
@@ -1138,7 +1102,7 @@ String ConfigManager::getAllSettingsAsJson() const {
|
||||
device["uid"] = deviceConfig.deviceUID;
|
||||
device["hwType"] = deviceConfig.hwType;
|
||||
device["hwVersion"] = deviceConfig.hwVersion;
|
||||
device["fwVersion"] = deviceConfig.fwVersion;
|
||||
device["fwVersion"] = FW_VERSION;
|
||||
|
||||
// Network config
|
||||
JsonObject network = doc.createNestedObject("network");
|
||||
|
||||
@@ -28,6 +28,7 @@
|
||||
#include <vector>
|
||||
#include <nvs_flash.h>
|
||||
#include <nvs.h>
|
||||
#include "../Version.hpp"
|
||||
|
||||
class ConfigManager {
|
||||
public:
|
||||
@@ -38,15 +39,14 @@ public:
|
||||
/**
|
||||
* @struct DeviceConfig
|
||||
* @brief Factory-set device identity (NVS storage)
|
||||
*
|
||||
*
|
||||
* These values are set once during manufacturing and stored in NVS.
|
||||
* fwVersion is updated automatically after OTA updates (SD storage).
|
||||
* fwVersion is NOT stored — it is always read from the compiled FW_VERSION constant.
|
||||
*/
|
||||
struct DeviceConfig {
|
||||
String deviceUID = ""; // 🏷️ Factory-set UID (NVS) - NO DEFAULT
|
||||
String hwType = ""; // 🔧 Factory-set hardware type (NVS) - NO DEFAULT
|
||||
String hwType = ""; // 🔧 Factory-set hardware type (NVS) - NO DEFAULT
|
||||
String hwVersion = ""; // 📐 Factory-set hardware revision (NVS) - NO DEFAULT
|
||||
String fwVersion = "0"; // 📋 Current firmware version (SD) - auto-updated (integer string)
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -133,9 +133,12 @@ public:
|
||||
* Universal defaults for all devices.
|
||||
*/
|
||||
struct UpdateConfig {
|
||||
String fallbackServerUrl = "http://firmware.bonamin.space"; // 🛡️ Universal fallback - OK as is
|
||||
int timeout = 10000; // ⏱️ Universal timeout - OK as is
|
||||
int retries = 3; // 🔄 Universal retries - OK as is
|
||||
String fallbackServerUrls[2] = {
|
||||
"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
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -313,10 +316,10 @@ public:
|
||||
String getDeviceUID() const { return deviceConfig.deviceUID; }
|
||||
String getHwType() const { return deviceConfig.hwType; }
|
||||
String getHwVersion() const { return deviceConfig.hwVersion; }
|
||||
String getFwVersion() const { return deviceConfig.fwVersion; }
|
||||
|
||||
/** @brief Set firmware version (auto-updated after OTA) */
|
||||
void setFwVersion(const String& version) { deviceConfig.fwVersion = version; }
|
||||
// Firmware version is owned by the binary — always returns the compiled-in constant.
|
||||
String getFwVersion() const { return FW_VERSION; }
|
||||
// No-op: version is compiled in, not stored. Kept for call-site compatibility.
|
||||
void setFwVersion(const String&) {}
|
||||
|
||||
// Configuration update methods for app commands
|
||||
void updateTimeConfig(long gmtOffsetSec, int daylightOffsetSec);
|
||||
|
||||
@@ -386,15 +386,27 @@ String HealthMonitor::getHealthSummary() const {
|
||||
|
||||
void HealthMonitor::updateSubsystemHealth(const String& name, HealthStatus status, const String& error) {
|
||||
auto it = _subsystemHealth.find(name);
|
||||
if (it != _subsystemHealth.end()) {
|
||||
it->second.status = status;
|
||||
it->second.lastError = error;
|
||||
it->second.lastCheck = millis();
|
||||
|
||||
LOG_VERBOSE(TAG, "🔍 %s: %s %s",
|
||||
name.c_str(),
|
||||
healthStatusToString(status).c_str(),
|
||||
error.isEmpty() ? "" : ("(" + error + ")").c_str());
|
||||
if (it == _subsystemHealth.end()) return;
|
||||
|
||||
HealthStatus previousStatus = it->second.status;
|
||||
|
||||
it->second.status = status;
|
||||
it->second.lastError = error;
|
||||
it->second.lastCheck = millis();
|
||||
|
||||
LOG_VERBOSE(TAG, "🔍 %s: %s %s",
|
||||
name.c_str(),
|
||||
healthStatusToString(status).c_str(),
|
||||
error.isEmpty() ? "" : ("(" + error + ")").c_str());
|
||||
|
||||
// Fire alert callback only on actual state change
|
||||
if (_alertCallback && status != previousStatus) {
|
||||
if (status == HealthStatus::HEALTHY) {
|
||||
// Transitioning back to healthy — send CLEARED
|
||||
_alertCallback(name, "CLEARED", "");
|
||||
} else {
|
||||
_alertCallback(name, healthStatusToString(status), error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -48,6 +48,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <functional>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
@@ -250,6 +251,17 @@ public:
|
||||
*/
|
||||
void setAutoMonitoring(bool enabled) { _autoMonitoring = enabled; }
|
||||
|
||||
/**
|
||||
* @brief Register a callback invoked whenever a subsystem state changes.
|
||||
* The callback receives: subsystemName, newStateString, errorMessage.
|
||||
* Called with state "CLEARED" (empty message) when transitioning back to HEALTHY.
|
||||
* Safe to call before begin().
|
||||
*/
|
||||
using AlertCallback = std::function<void(const String& subsystem,
|
||||
const String& newState,
|
||||
const String& message)>;
|
||||
void setAlertCallback(AlertCallback cb) { _alertCallback = cb; }
|
||||
|
||||
private:
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// SUBSYSTEM REFERENCES
|
||||
@@ -272,6 +284,7 @@ private:
|
||||
TaskHandle_t _monitoringTaskHandle = nullptr;
|
||||
unsigned long _healthCheckInterval = 300000; // 5 minutes default
|
||||
bool _autoMonitoring = true;
|
||||
AlertCallback _alertCallback = nullptr; // Optional: fires on state change
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// PRIVATE HELPER METHODS
|
||||
|
||||
+188
-123
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
// FIRMWARE VERSION
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
// Format: MAJOR.MINOR.PATCH (e.g. "2.0.0")
|
||||
// This is the single source of truth. It is compiled into the binary
|
||||
// and never stored in NVS — the binary IS the version.
|
||||
//
|
||||
// VERSION HISTORY:
|
||||
// v154 (legacy integer) - Last integer-versioned release
|
||||
// v2.0.0 - First SemVer release
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
#define FW_VERSION "2.0.0"
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
// SemVer — lightweight 3-part version struct
|
||||
// ═══════════════════════════════════════════════════════════════════════
|
||||
struct SemVer {
|
||||
uint8_t major;
|
||||
uint8_t minor;
|
||||
uint8_t patch;
|
||||
|
||||
// Parse "2.0.0" or legacy integer "154" (treated as 0.0.154)
|
||||
static SemVer parse(const String& s) {
|
||||
SemVer v{0, 0, 0};
|
||||
int first = s.indexOf('.');
|
||||
if (first == -1) {
|
||||
// Legacy integer format: "154" -> {0, 0, 154}
|
||||
// Clamp to uint8_t range; values > 255 are stored in minor too
|
||||
uint16_t n = (uint16_t)s.toInt();
|
||||
v.minor = (uint8_t)(n / 100);
|
||||
v.patch = (uint8_t)(n % 100);
|
||||
return v;
|
||||
}
|
||||
int second = s.indexOf('.', first + 1);
|
||||
v.major = (uint8_t)s.substring(0, first).toInt();
|
||||
if (second == -1) {
|
||||
v.minor = (uint8_t)s.substring(first + 1).toInt();
|
||||
} else {
|
||||
v.minor = (uint8_t)s.substring(first + 1, second).toInt();
|
||||
v.patch = (uint8_t)s.substring(second + 1).toInt();
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
bool operator==(const SemVer& o) const {
|
||||
return major == o.major && minor == o.minor && patch == o.patch;
|
||||
}
|
||||
bool operator!=(const SemVer& o) const { return !(*this == o); }
|
||||
bool operator<(const SemVer& o) const {
|
||||
if (major != o.major) return major < o.major;
|
||||
if (minor != o.minor) return minor < o.minor;
|
||||
return patch < o.patch;
|
||||
}
|
||||
bool operator>(const SemVer& o) const { return o < *this; }
|
||||
bool operator<=(const SemVer& o) const { return !(o < *this); }
|
||||
bool operator>=(const SemVer& o) const { return !(*this < o); }
|
||||
|
||||
bool isZero() const { return major == 0 && minor == 0 && patch == 0; }
|
||||
|
||||
String toString() const {
|
||||
return String(major) + "." + String(minor) + "." + String(patch);
|
||||
}
|
||||
};
|
||||
+2
-39
@@ -56,33 +56,7 @@
|
||||
|
||||
|
||||
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════
|
||||
* 📋 VERSION CONFIGURATION
|
||||
* ═══════════════════════════════════════════════════════════════════════════════
|
||||
* 📅 DATE: 2025-10-10
|
||||
* 👨💻 AUTHOR: BellSystems bonamin
|
||||
*/
|
||||
|
||||
#define FW_VERSION "154"
|
||||
|
||||
|
||||
/*
|
||||
* ═══════════════════════════════════════════════════════════════════════════════
|
||||
* 📅 VERSION HISTORY:
|
||||
* NOTE: Versions are now stored as integers (v1.3 = 130)
|
||||
* ═══════════════════════════════════════════════════════════════════════════════
|
||||
* v0.1 (100) - Vesper Launch Beta
|
||||
* v1.2 (120) - Added Log Level Configuration via App/MQTT
|
||||
* v1.3 (130) - Added Telemetry Reports to App, Various Playback Fixes
|
||||
* v137 - Made OTA and MQTT delays Async
|
||||
* v138 - Removed Ethernet, added default WiFi creds (Mikrotik AP) and fixed various Clock issues
|
||||
* v140 - Changed FW Updates to Direct-to-Flash and added manual update functionality with version check
|
||||
* v151 - Fixed Clock Alerts not running properly
|
||||
* v152 - Fix RTC Time Reports, added sync_time_to_LCD functionality
|
||||
* v153 - Fix Infinite Loop Bug and Melody Download crashes.
|
||||
* ═══════════════════════════════════════════════════════════════════════════════
|
||||
*/
|
||||
// Firmware version is defined in Version.hpp (FW_VERSION)
|
||||
|
||||
|
||||
|
||||
@@ -143,6 +117,7 @@
|
||||
#include "HealthMonitor/HealthMonitor.hpp"
|
||||
#include "FirmwareValidator/FirmwareValidator.hpp"
|
||||
#include "InputManager/InputManager.hpp"
|
||||
#include "Version.hpp"
|
||||
|
||||
#define TAG "Main"
|
||||
|
||||
@@ -257,18 +232,6 @@ void setup()
|
||||
|
||||
// Update firmware version (this is the ONLY identity field that can be set)
|
||||
|
||||
// 🔥 MIGRATION: Convert old float-style version to integer format
|
||||
String currentVersion = configManager.getFwVersion();
|
||||
if (currentVersion.indexOf('.') != -1) {
|
||||
// Old format detected (e.g., "1.3"), convert to integer ("130")
|
||||
float versionFloat = currentVersion.toFloat();
|
||||
uint16_t versionInt = (uint16_t)(versionFloat * 100.0f);
|
||||
configManager.setFwVersion(String(versionInt));
|
||||
configManager.saveDeviceConfig();
|
||||
LOG_INFO(TAG, "⚠️ Migrated version format: %s -> %u", currentVersion.c_str(), versionInt);
|
||||
}
|
||||
|
||||
configManager.setFwVersion(FW_VERSION);
|
||||
LOG_INFO(TAG, "Firmware version: %s", FW_VERSION);
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user