feat: HAL variant system, OTA improvements, NVS migration scaffold
- Add variants/vesper.hpp and variants/agnus.hpp with HAS_SD_CARD, HAS_RTC, HAS_PCF8574, OUTPUT_COUNT_MAX, HW_FAMILY capability flags - Add agnus-v1 and agnus-mini-v1 PlatformIO environments with -include injection - Add src/NvsMigration/ scaffold for future NVS schema versioning - FirmwareHandler: OTA flow improvements and header updates - OTAManager: FastAPI integration, semver handling improvements - ConfigManager: refactoring groundwork for NVS-only variant support - CommunicationRouter: minor fix - provisioning/nvs_lab_device.csv: fix hw_type to VS, update device id fields - docs/dev/ota-telemetry-api.md: update API spec Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -228,7 +228,7 @@ void CommunicationRouter::registerHandlers() {
|
||||
// Firmware / OTA
|
||||
if (_firmwareValidator && _player) {
|
||||
_bus.registerHandler(std::make_unique<FirmwareHandler>(
|
||||
*_firmwareValidator, _otaManager, *_player));
|
||||
*_firmwareValidator, _otaManager, *_player, _configManager));
|
||||
}
|
||||
|
||||
// Network — no optional dependencies
|
||||
|
||||
@@ -2,30 +2,37 @@
|
||||
#include "../../../FirmwareValidator/FirmwareValidator.hpp"
|
||||
#include "../../../OTAManager/OTAManager.hpp"
|
||||
#include "../../../Player/Player.hpp"
|
||||
#include "../../../ConfigManager/ConfigManager.hpp"
|
||||
#include "../../../Logging/Logging.hpp"
|
||||
|
||||
#define TAG "FirmwareHandler"
|
||||
|
||||
static const char* VALID_CHANNELS[] = { "stable", "beta", "development" };
|
||||
static const size_t VALID_CHANNEL_COUNT = sizeof(VALID_CHANNELS) / sizeof(VALID_CHANNELS[0]);
|
||||
|
||||
FirmwareHandler::FirmwareHandler(FirmwareValidator& firmwareValidator,
|
||||
OTAManager& otaManager,
|
||||
Player& player)
|
||||
Player& player,
|
||||
ConfigManager& configManager)
|
||||
: _firmwareValidator(firmwareValidator)
|
||||
, _otaManager(otaManager)
|
||||
, _player(player) {}
|
||||
, _player(player)
|
||||
, _configManager(configManager) {}
|
||||
|
||||
std::vector<String> FirmwareHandler::commands() const {
|
||||
return {
|
||||
"firmware.status", "firmware.commit", "firmware.rollback",
|
||||
"ota.update", "ota.custom"
|
||||
"ota.update", "ota.custom", "ota.set_channel"
|
||||
};
|
||||
}
|
||||
|
||||
CommandResult FirmwareHandler::execute(const CommandEnvelope& envelope) {
|
||||
if (envelope.command == "firmware.status") return handleFirmwareStatus(envelope);
|
||||
if (envelope.command == "firmware.commit") return handleCommit(envelope);
|
||||
if (envelope.command == "firmware.status") return handleFirmwareStatus(envelope);
|
||||
if (envelope.command == "firmware.commit") return handleCommit(envelope);
|
||||
if (envelope.command == "firmware.rollback") return handleRollback(envelope);
|
||||
if (envelope.command == "ota.update") return handleOtaUpdate(envelope);
|
||||
if (envelope.command == "ota.custom") return handleOtaCustom(envelope);
|
||||
if (envelope.command == "ota.update") return handleOtaUpdate(envelope);
|
||||
if (envelope.command == "ota.custom") return handleOtaCustom(envelope);
|
||||
if (envelope.command == "ota.set_channel") return handleOtaSetChannel(envelope);
|
||||
return CommandResult::err(envelope.command, "Unknown firmware command");
|
||||
}
|
||||
|
||||
@@ -47,6 +54,7 @@ CommandResult FirmwareHandler::handleFirmwareStatus(const CommandEnvelope& e) {
|
||||
doc["is_valid"] = currentInfo.isValid;
|
||||
doc["boot_count"] = currentInfo.bootCount;
|
||||
doc["build_date"] = currentInfo.buildDate;
|
||||
doc["ota_channel"] = _configManager.getOtaChannel();
|
||||
|
||||
bool inTesting = _firmwareValidator.isInTestingMode();
|
||||
doc["can_commit"] = inTesting;
|
||||
@@ -109,3 +117,28 @@ CommandResult FirmwareHandler::handleOtaCustom(const CommandEnvelope& e) {
|
||||
_otaManager.performCustomUpdate(url, checksum, fileSize, version);
|
||||
return CommandResult::ok("ota.custom", "Custom OTA update started");
|
||||
}
|
||||
|
||||
CommandResult FirmwareHandler::handleOtaSetChannel(const CommandEnvelope& e) {
|
||||
if (!e.contents["channel"].is<const char*>()) {
|
||||
return CommandResult::err("ota.set_channel", "Missing required field: channel");
|
||||
}
|
||||
String channel = e.contents["channel"].as<String>();
|
||||
|
||||
// Validate against allowed channels
|
||||
bool valid = false;
|
||||
for (size_t i = 0; i < VALID_CHANNEL_COUNT; i++) {
|
||||
if (channel == VALID_CHANNELS[i]) { valid = true; break; }
|
||||
}
|
||||
if (!valid) {
|
||||
return CommandResult::err("ota.set_channel",
|
||||
"Invalid channel. Valid values: stable, beta, development");
|
||||
}
|
||||
|
||||
_configManager.setOtaChannel(channel);
|
||||
_configManager.saveGeneralConfig();
|
||||
LOG_INFO(TAG, "OTA channel set to '%s' and persisted to SD", channel.c_str());
|
||||
|
||||
JsonDocument doc;
|
||||
doc["channel"] = channel;
|
||||
return CommandResult::ok("ota.set_channel", doc);
|
||||
}
|
||||
|
||||
@@ -6,10 +6,12 @@
|
||||
class FirmwareValidator;
|
||||
class OTAManager;
|
||||
class Player;
|
||||
class ConfigManager;
|
||||
|
||||
class FirmwareHandler : public ICommandHandler {
|
||||
public:
|
||||
FirmwareHandler(FirmwareValidator& firmwareValidator, OTAManager& otaManager, Player& player);
|
||||
FirmwareHandler(FirmwareValidator& firmwareValidator, OTAManager& otaManager,
|
||||
Player& player, ConfigManager& configManager);
|
||||
|
||||
std::vector<String> commands() const override;
|
||||
CommandResult execute(const CommandEnvelope& envelope) override;
|
||||
@@ -18,10 +20,12 @@ private:
|
||||
FirmwareValidator& _firmwareValidator;
|
||||
OTAManager& _otaManager;
|
||||
Player& _player;
|
||||
ConfigManager& _configManager;
|
||||
|
||||
CommandResult handleFirmwareStatus(const CommandEnvelope& e);
|
||||
CommandResult handleCommit(const CommandEnvelope& e);
|
||||
CommandResult handleRollback(const CommandEnvelope& e);
|
||||
CommandResult handleOtaUpdate(const CommandEnvelope& e);
|
||||
CommandResult handleOtaCustom(const CommandEnvelope& e);
|
||||
CommandResult handleOtaSetChannel(const CommandEnvelope& e);
|
||||
};
|
||||
|
||||
@@ -10,10 +10,12 @@
|
||||
// NVS namespace for device identity storage
|
||||
const char* ConfigManager::NVS_NAMESPACE = "device_id";
|
||||
|
||||
// NVS keys for device identity
|
||||
static const char* NVS_DEVICE_UID_KEY = "device_uid";
|
||||
static const char* NVS_HW_TYPE_KEY = "hw_type";
|
||||
static const char* NVS_HW_VERSION_KEY = "hw_version";
|
||||
// NVS keys for device identity (new schema — written by backend provisioning tool)
|
||||
// Old keys (device_uid, hw_type, hw_version) are migrated to these on first boot
|
||||
// by NvsMigration::run() which runs before ConfigManager::begin().
|
||||
static const char* NVS_SERIAL_KEY = "serial";
|
||||
static const char* NVS_HW_FAMILY_KEY = "hw_family";
|
||||
static const char* NVS_HW_REVISION_KEY = "hw_revision";
|
||||
|
||||
ConfigManager::ConfigManager() {
|
||||
// Initialize with empty defaults - everything will be loaded/generated in begin()
|
||||
@@ -28,12 +30,12 @@ void ConfigManager::initializeCleanDefaults() {
|
||||
generateNetworkIdentifiers();
|
||||
|
||||
// Set MQTT user to deviceUID for unique identification
|
||||
mqttConfig.user = deviceConfig.deviceUID;
|
||||
mqttConfig.user = deviceConfig.serial;
|
||||
|
||||
// Derive MQTT password from deviceUID using HMAC-SHA256
|
||||
// MQTT_SECRET is compiled in via build flag -DMQTT_SECRET="..."
|
||||
// Must match the MQTT_SECRET in the backend .env exactly.
|
||||
mqttConfig.password = computeMqttPassword(deviceConfig.deviceUID);
|
||||
mqttConfig.password = computeMqttPassword(deviceConfig.serial);
|
||||
|
||||
LOG_INFO(TAG, "🔑 MQTT auth — user: %s, password: %s", mqttConfig.user.c_str(), mqttConfig.password.c_str());
|
||||
LOG_INFO(TAG, "🔑 MQTT_SECRET prefix: %.8s...", MQTT_SECRET);
|
||||
@@ -43,8 +45,8 @@ void ConfigManager::initializeCleanDefaults() {
|
||||
|
||||
void ConfigManager::generateNetworkIdentifiers() {
|
||||
|
||||
networkConfig.hostname = "BellSystems-" + deviceConfig.deviceUID;
|
||||
networkConfig.apSsid = "BellSystems-Setup-" + deviceConfig.deviceUID;
|
||||
networkConfig.hostname = "BellSystems-" + deviceConfig.serial;
|
||||
networkConfig.apSsid = "BellSystems-Setup-" + deviceConfig.serial;
|
||||
|
||||
|
||||
LOG_DEBUG(TAG, "ConfigManager - Generated hostname: %s, AP SSID: %s",
|
||||
@@ -66,7 +68,7 @@ bool ConfigManager::begin() {
|
||||
if (!initializeNVS()) {
|
||||
LOG_ERROR(TAG, "ConfigManager - ❌ NVS initialization failed, using empty defaults");
|
||||
} else {
|
||||
// Load device identity from NVS (deviceUID, hwType, hwVersion)
|
||||
// Load device identity from NVS (serial, hwFamily, hwRevision)
|
||||
loadDeviceIdentityFromNVS();
|
||||
}
|
||||
|
||||
@@ -126,8 +128,8 @@ bool ConfigManager::begin() {
|
||||
saveGeneralConfig();
|
||||
}
|
||||
|
||||
LOG_INFO(TAG, "ConfigManager - ✅ Initialization Complete ! UID: %s, Hostname: %s",
|
||||
deviceConfig.deviceUID.c_str(), networkConfig.hostname.c_str());
|
||||
LOG_INFO(TAG, "ConfigManager - ✅ Initialization Complete ! Serial: %s, Hostname: %s",
|
||||
deviceConfig.serial.c_str(), networkConfig.hostname.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -165,12 +167,12 @@ bool ConfigManager::loadDeviceIdentityFromNVS() {
|
||||
}
|
||||
|
||||
// Read factory-set device identity from NVS (READ-ONLY)
|
||||
deviceConfig.deviceUID = readNVSString(NVS_DEVICE_UID_KEY, "");
|
||||
deviceConfig.hwType = readNVSString(NVS_HW_TYPE_KEY, "");
|
||||
deviceConfig.hwVersion = readNVSString(NVS_HW_VERSION_KEY, "");
|
||||
deviceConfig.serial = readNVSString(NVS_SERIAL_KEY, "");
|
||||
deviceConfig.hwFamily = readNVSString(NVS_HW_FAMILY_KEY, "");
|
||||
deviceConfig.hwRevision = readNVSString(NVS_HW_REVISION_KEY, "");
|
||||
|
||||
// Validate that factory identity exists
|
||||
if (deviceConfig.deviceUID.isEmpty() || deviceConfig.hwType.isEmpty() || deviceConfig.hwVersion.isEmpty()) {
|
||||
if (deviceConfig.serial.isEmpty() || deviceConfig.hwFamily.isEmpty() || deviceConfig.hwRevision.isEmpty()) {
|
||||
LOG_ERROR(TAG, "═══════════════════════════════════════════════════════════════════════════");
|
||||
LOG_ERROR(TAG, " ⚠️ CRITICAL: DEVICE IDENTITY NOT FOUND IN NVS");
|
||||
LOG_ERROR(TAG, " ⚠️ This device has NOT been factory-programmed!");
|
||||
@@ -181,9 +183,9 @@ bool ConfigManager::loadDeviceIdentityFromNVS() {
|
||||
|
||||
LOG_INFO(TAG, "═══════════════════════════════════════════════════════════════════════════");
|
||||
LOG_INFO(TAG, " 🏭 FACTORY DEVICE IDENTITY LOADED FROM NVS (READ-ONLY)");
|
||||
LOG_INFO(TAG, " 🆔 Device UID: %s", deviceConfig.deviceUID.c_str());
|
||||
LOG_INFO(TAG, " 🔧 Hardware Type: %s", deviceConfig.hwType.c_str());
|
||||
LOG_INFO(TAG, " 📐 Hardware Version: %s", deviceConfig.hwVersion.c_str());
|
||||
LOG_INFO(TAG, " 🆔 Serial: %s", deviceConfig.serial.c_str());
|
||||
LOG_INFO(TAG, " 🔧 HW Family: %s", deviceConfig.hwFamily.c_str());
|
||||
LOG_INFO(TAG, " 📐 HW Revision: %s", deviceConfig.hwRevision.c_str());
|
||||
LOG_INFO(TAG, " 🔒 These values are PERMANENT and cannot be changed by production firmware");
|
||||
LOG_INFO(TAG, "═══════════════════════════════════════════════════════════════════════════");
|
||||
|
||||
@@ -191,7 +193,7 @@ bool ConfigManager::loadDeviceIdentityFromNVS() {
|
||||
}
|
||||
|
||||
// REMOVED: saveDeviceIdentityToNVS() - Production firmware MUST NOT write device identity
|
||||
// Device identity (UID, hwType, hwVersion) is factory-set ONLY and stored in NVS by factory firmware
|
||||
// Device identity (serial, hwFamily, hwRevision) is factory-set ONLY and stored in NVS by backend provisioning
|
||||
// Production firmware reads these values once at boot and keeps them in RAM
|
||||
|
||||
String ConfigManager::readNVSString(const char* key, const String& defaultValue) {
|
||||
@@ -272,13 +274,13 @@ bool ConfigManager::isHealthy() const {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (deviceConfig.deviceUID.isEmpty()) {
|
||||
LOG_VERBOSE(TAG, "ConfigManager - ⚠️ Unhealthy - Device UID not set (factory configuration required)");
|
||||
if (deviceConfig.serial.isEmpty()) {
|
||||
LOG_VERBOSE(TAG, "ConfigManager - ⚠️ Unhealthy - Serial not set (factory configuration required)");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (deviceConfig.hwType.isEmpty()) {
|
||||
LOG_VERBOSE(TAG, "ConfigManager - ⚠️ Unhealthy - Hardware type not set (factory configuration required)");
|
||||
|
||||
if (deviceConfig.hwFamily.isEmpty()) {
|
||||
LOG_VERBOSE(TAG, "ConfigManager - ⚠️ Unhealthy - HW family not set (factory configuration required)");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1099,9 +1101,9 @@ String ConfigManager::getAllSettingsAsJson() const {
|
||||
|
||||
// Device info
|
||||
JsonObject device = doc.createNestedObject("device");
|
||||
device["uid"] = deviceConfig.deviceUID;
|
||||
device["hwType"] = deviceConfig.hwType;
|
||||
device["hwVersion"] = deviceConfig.hwVersion;
|
||||
device["serial"] = deviceConfig.serial;
|
||||
device["hw_family"] = deviceConfig.hwFamily;
|
||||
device["hw_revision"] = deviceConfig.hwRevision;
|
||||
device["fwVersion"] = FW_VERSION;
|
||||
|
||||
// Network config
|
||||
@@ -1246,10 +1248,13 @@ bool ConfigManager::loadGeneralConfig() {
|
||||
generalConfig.mqttEnabled = doc["mqttEnabled"].as<bool>();
|
||||
mqttConfig.enabled = generalConfig.mqttEnabled; // Sync with mqttConfig
|
||||
}
|
||||
if (doc.containsKey("otaChannel")) {
|
||||
generalConfig.otaChannel = doc["otaChannel"].as<String>();
|
||||
}
|
||||
|
||||
LOG_DEBUG(TAG, "ConfigManager - General config loaded - Serial log level: %d, SD log level: %d, MQTT log level: %d, MQTT enabled: %s",
|
||||
LOG_DEBUG(TAG, "ConfigManager - General config loaded - Serial log level: %d, SD log level: %d, MQTT log level: %d, MQTT enabled: %s, OTA channel: %s",
|
||||
generalConfig.serialLogLevel, generalConfig.sdLogLevel, generalConfig.mqttLogLevel,
|
||||
generalConfig.mqttEnabled ? "true" : "false");
|
||||
generalConfig.mqttEnabled ? "true" : "false", generalConfig.otaChannel.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1261,6 +1266,7 @@ bool ConfigManager::saveGeneralConfig() {
|
||||
doc["sdLogLevel"] = generalConfig.sdLogLevel;
|
||||
doc["mqttLogLevel"] = generalConfig.mqttLogLevel;
|
||||
doc["mqttEnabled"] = generalConfig.mqttEnabled;
|
||||
doc["otaChannel"] = generalConfig.otaChannel;
|
||||
|
||||
char buffer[256];
|
||||
size_t len = serializeJson(doc, buffer, sizeof(buffer));
|
||||
|
||||
@@ -44,9 +44,9 @@ public:
|
||||
* 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 hwVersion = ""; // 📐 Factory-set hardware revision (NVS) - NO DEFAULT
|
||||
String serial = ""; // 🏷️ Factory-set serial number (NVS key: "serial") - NO DEFAULT
|
||||
String hwFamily = ""; // 🔧 Factory-set hardware family (NVS key: "hw_family") - NO DEFAULT e.g. "vesper-standard"
|
||||
String hwRevision = ""; // 📐 Factory-set hw revision (NVS key: "hw_revision") - NO DEFAULT e.g. "1.0"
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -220,7 +220,8 @@ public:
|
||||
uint8_t serialLogLevel = 5;
|
||||
uint8_t sdLogLevel = 0;
|
||||
uint8_t mqttLogLevel = 0;
|
||||
bool mqttEnabled = true; // MQTT enabled by default
|
||||
bool mqttEnabled = true; // MQTT enabled by default
|
||||
String otaChannel = "stable"; // OTA release channel: "stable" | "beta" | "development"
|
||||
};
|
||||
|
||||
private:
|
||||
@@ -313,9 +314,14 @@ public:
|
||||
// Device identity methods (READ-ONLY - factory set via separate factory firmware)
|
||||
// These values are loaded ONCE at boot from NVS and kept in RAM
|
||||
// Production firmware CANNOT modify device identity
|
||||
String getDeviceUID() const { return deviceConfig.deviceUID; }
|
||||
String getHwType() const { return deviceConfig.hwType; }
|
||||
String getHwVersion() const { return deviceConfig.hwVersion; }
|
||||
String getSerial() const { return deviceConfig.serial; }
|
||||
String getHwFamily() const { return deviceConfig.hwFamily; }
|
||||
String getHwRevision() const { return deviceConfig.hwRevision; }
|
||||
// Deprecated aliases — kept temporarily to avoid widespread call-site breakage
|
||||
// TODO: remove these once all callers are updated
|
||||
String getDeviceUID() const { return deviceConfig.serial; }
|
||||
String getHwType() const { return deviceConfig.hwFamily; }
|
||||
String getHwVersion() const { return deviceConfig.hwRevision; }
|
||||
// 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.
|
||||
@@ -418,6 +424,8 @@ public:
|
||||
uint8_t getMqttLogLevel() const { return generalConfig.mqttLogLevel; }
|
||||
void setMqttEnabled(bool enabled) { generalConfig.mqttEnabled = enabled; mqttConfig.enabled = enabled; }
|
||||
bool getMqttEnabled() const { return generalConfig.mqttEnabled; }
|
||||
String getOtaChannel() const { return generalConfig.otaChannel; }
|
||||
void setOtaChannel(const String& channel) { generalConfig.otaChannel = channel; }
|
||||
bool loadGeneralConfig();
|
||||
bool saveGeneralConfig();
|
||||
|
||||
@@ -432,7 +440,7 @@ public:
|
||||
void updateRealTimeFromCommand(JsonVariant doc);
|
||||
void updatePhysicalClockTimeFromCommand(JsonVariant doc);
|
||||
void saveFileToSD(const char* dirPath, const char* filename, const char* data);
|
||||
String getHardwareVariant() const { return deviceConfig.hwType; }
|
||||
String getHardwareVariant() const { return deviceConfig.hwFamily; }
|
||||
bool loadDeviceConfig();
|
||||
bool saveDeviceConfig();
|
||||
bool loadUpdateServers();
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
#include "NvsMigration.hpp"
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <nvs_flash.h>
|
||||
#include <nvs.h>
|
||||
|
||||
#define TAG "NvsMigration"
|
||||
#include "../Logging/Logging.hpp"
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// NVS namespace — same as ConfigManager, must stay in sync
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
static const char* NVS_NAMESPACE = "device_id";
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// OLD key names (pre-2.0 factory firmware)
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
static const char* OLD_KEY_UID = "device_uid";
|
||||
static const char* OLD_KEY_HW_TYPE = "hw_type";
|
||||
static const char* OLD_KEY_HW_VERSION = "hw_version";
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// NEW key names (2.0+ backend provisioning)
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
static const char* NEW_KEY_SERIAL = "serial";
|
||||
static const char* NEW_KEY_HW_FAMILY = "hw_family";
|
||||
static const char* NEW_KEY_HW_REVISION = "hw_revision";
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// hw_type → hw_family lookup table
|
||||
// All values that were ever written by the factory firmware web UI.
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
struct HwFamilyEntry {
|
||||
const char* oldType;
|
||||
const char* newFamily;
|
||||
};
|
||||
|
||||
static const HwFamilyEntry HW_FAMILY_MAP[] = {
|
||||
// Short type codes used by early factory firmware (pre-2.0)
|
||||
{ "VS", "vesper" },
|
||||
{ "VP", "vesper_plus" },
|
||||
{ "VX", "vesper_pro" },
|
||||
// Longer codes used by intermediate factory firmware
|
||||
{ "bell_core", "vesper" },
|
||||
{ "bell_plus", "vesper_plus" },
|
||||
{ "bell_pro", "vesper_pro" },
|
||||
{ "agnus_mini", "agnus_mini" },
|
||||
};
|
||||
static const size_t HW_FAMILY_MAP_SIZE = sizeof(HW_FAMILY_MAP) / sizeof(HW_FAMILY_MAP[0]);
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Helpers
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
static String nvsReadString(nvs_handle_t handle, const char* key) {
|
||||
size_t len = 0;
|
||||
esp_err_t err = nvs_get_str(handle, key, nullptr, &len);
|
||||
if (err != ESP_OK || len == 0) return "";
|
||||
|
||||
char* buf = new char[len];
|
||||
nvs_get_str(handle, key, buf, &len);
|
||||
String result(buf);
|
||||
delete[] buf;
|
||||
return result;
|
||||
}
|
||||
|
||||
static bool nvsKeyExists(nvs_handle_t handle, const char* key) {
|
||||
size_t len = 0;
|
||||
return nvs_get_str(handle, key, nullptr, &len) == ESP_OK;
|
||||
}
|
||||
|
||||
static const char* lookupHwFamily(const String& oldType) {
|
||||
for (size_t i = 0; i < HW_FAMILY_MAP_SIZE; i++) {
|
||||
if (oldType == HW_FAMILY_MAP[i].oldType) {
|
||||
return HW_FAMILY_MAP[i].newFamily;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Migration steps — each step is independent and idempotent
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
// device_uid → serial
|
||||
static void migrateUid(nvs_handle_t handle) {
|
||||
if (!nvsKeyExists(handle, OLD_KEY_UID)) return;
|
||||
if (nvsKeyExists(handle, NEW_KEY_SERIAL)) {
|
||||
// New key already exists — just clean up the old one
|
||||
nvs_erase_key(handle, OLD_KEY_UID);
|
||||
LOG_INFO(TAG, " Cleaned up stale '%s' key", OLD_KEY_UID);
|
||||
return;
|
||||
}
|
||||
|
||||
String value = nvsReadString(handle, OLD_KEY_UID);
|
||||
if (value.isEmpty()) {
|
||||
LOG_WARNING(TAG, " '%s' exists but is empty — skipping", OLD_KEY_UID);
|
||||
return;
|
||||
}
|
||||
|
||||
nvs_set_str(handle, NEW_KEY_SERIAL, value.c_str());
|
||||
nvs_erase_key(handle, OLD_KEY_UID);
|
||||
LOG_INFO(TAG, " '%s' → '%s' = \"%s\"", OLD_KEY_UID, NEW_KEY_SERIAL, value.c_str());
|
||||
}
|
||||
|
||||
// hw_type → hw_family (with value conversion via lookup table)
|
||||
static void migrateHwType(nvs_handle_t handle) {
|
||||
if (!nvsKeyExists(handle, OLD_KEY_HW_TYPE)) return;
|
||||
if (nvsKeyExists(handle, NEW_KEY_HW_FAMILY)) {
|
||||
nvs_erase_key(handle, OLD_KEY_HW_TYPE);
|
||||
LOG_INFO(TAG, " Cleaned up stale '%s' key", OLD_KEY_HW_TYPE);
|
||||
return;
|
||||
}
|
||||
|
||||
String oldValue = nvsReadString(handle, OLD_KEY_HW_TYPE);
|
||||
if (oldValue.isEmpty()) {
|
||||
LOG_WARNING(TAG, " '%s' exists but is empty — skipping", OLD_KEY_HW_TYPE);
|
||||
return;
|
||||
}
|
||||
|
||||
const char* newFamily = lookupHwFamily(oldValue);
|
||||
if (newFamily == nullptr) {
|
||||
// Unknown old value — carry it forward as-is so OTA at least has something
|
||||
LOG_WARNING(TAG, " '%s' = \"%s\" not in lookup table — carrying forward as-is",
|
||||
OLD_KEY_HW_TYPE, oldValue.c_str());
|
||||
nvs_set_str(handle, NEW_KEY_HW_FAMILY, oldValue.c_str());
|
||||
} else {
|
||||
nvs_set_str(handle, NEW_KEY_HW_FAMILY, newFamily);
|
||||
LOG_INFO(TAG, " '%s' (\"%s\") → '%s' = \"%s\"",
|
||||
OLD_KEY_HW_TYPE, oldValue.c_str(), NEW_KEY_HW_FAMILY, newFamily);
|
||||
}
|
||||
|
||||
nvs_erase_key(handle, OLD_KEY_HW_TYPE);
|
||||
}
|
||||
|
||||
// hw_version → hw_revision (value unchanged)
|
||||
static void migrateHwVersion(nvs_handle_t handle) {
|
||||
if (!nvsKeyExists(handle, OLD_KEY_HW_VERSION)) return;
|
||||
if (nvsKeyExists(handle, NEW_KEY_HW_REVISION)) {
|
||||
nvs_erase_key(handle, OLD_KEY_HW_VERSION);
|
||||
LOG_INFO(TAG, " Cleaned up stale '%s' key", OLD_KEY_HW_VERSION);
|
||||
return;
|
||||
}
|
||||
|
||||
String value = nvsReadString(handle, OLD_KEY_HW_VERSION);
|
||||
if (value.isEmpty()) {
|
||||
LOG_WARNING(TAG, " '%s' exists but is empty — skipping", OLD_KEY_HW_VERSION);
|
||||
return;
|
||||
}
|
||||
|
||||
nvs_set_str(handle, NEW_KEY_HW_REVISION, value.c_str());
|
||||
nvs_erase_key(handle, OLD_KEY_HW_VERSION);
|
||||
LOG_INFO(TAG, " '%s' → '%s' = \"%s\"", OLD_KEY_HW_VERSION, NEW_KEY_HW_REVISION, value.c_str());
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Public entry point
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
bool NvsMigration::run() {
|
||||
// Ensure NVS flash partition is initialised
|
||||
esp_err_t err = nvs_flash_init();
|
||||
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
|
||||
LOG_WARNING(TAG, "NVS partition corrupt/version mismatch — erasing and reinitialising");
|
||||
nvs_flash_erase();
|
||||
err = nvs_flash_init();
|
||||
}
|
||||
if (err != ESP_OK) {
|
||||
LOG_ERROR(TAG, "nvs_flash_init failed: %d — cannot run migration", err);
|
||||
return false;
|
||||
}
|
||||
|
||||
nvs_handle_t handle;
|
||||
err = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &handle);
|
||||
if (err != ESP_OK) {
|
||||
LOG_ERROR(TAG, "nvs_open(\"%s\") failed: %d — cannot run migration", NVS_NAMESPACE, err);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Fast path — if none of the old keys exist, nothing to do
|
||||
bool needsMigration = nvsKeyExists(handle, OLD_KEY_UID)
|
||||
|| nvsKeyExists(handle, OLD_KEY_HW_TYPE)
|
||||
|| nvsKeyExists(handle, OLD_KEY_HW_VERSION);
|
||||
|
||||
if (!needsMigration) {
|
||||
LOG_INFO(TAG, "NVS schema is current — no migration needed");
|
||||
nvs_close(handle);
|
||||
return true;
|
||||
}
|
||||
|
||||
LOG_INFO(TAG, "Old NVS schema detected — running migration...");
|
||||
|
||||
migrateUid(handle);
|
||||
migrateHwType(handle);
|
||||
migrateHwVersion(handle);
|
||||
|
||||
nvs_commit(handle);
|
||||
nvs_close(handle);
|
||||
|
||||
LOG_INFO(TAG, "NVS migration complete");
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// NvsMigration.hpp — One-time NVS schema migration
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
//
|
||||
// Runs once at the very top of setup(), before any subsystem initializes.
|
||||
// Detects old NVS key schema and converts to the new one in-place.
|
||||
//
|
||||
// OLD schema (factory firmware / pre-2.0):
|
||||
// namespace : "device_id"
|
||||
// device_uid → raw device UID
|
||||
// hw_type → short slug e.g. "bell_plus", "bell_core"
|
||||
// hw_version → revision string e.g. "1.0"
|
||||
//
|
||||
// NEW schema (backend-provisioned / 2.0+):
|
||||
// namespace : "device_id"
|
||||
// serial → same value as old device_uid
|
||||
// hw_family → full hyphenated slug e.g. "vesper-plus", "vesper-standard"
|
||||
// hw_revision → same value as old hw_version
|
||||
//
|
||||
// Migration is idempotent — safe to run on every boot. If new keys are already
|
||||
// present it exits immediately without touching NVS.
|
||||
//
|
||||
// Remove this file (and its call in main.cpp) once ALL devices have passed
|
||||
// through firmware 1.9.x via the staged OTA upgrade chain.
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
#pragma once
|
||||
|
||||
namespace NvsMigration {
|
||||
/**
|
||||
* @brief Run NVS schema migration.
|
||||
*
|
||||
* Call this at the very top of setup(), before nvs_flash_init() is called
|
||||
* by ConfigManager. This function calls nvs_flash_init() internally and
|
||||
* leaves it initialised for subsequent callers.
|
||||
*
|
||||
* @return true Migration ran successfully (or was not needed).
|
||||
* @return false NVS could not be opened — device identity may be missing.
|
||||
*/
|
||||
bool run();
|
||||
}
|
||||
@@ -186,13 +186,14 @@ void OTAManager::checkForEmergencyUpdates() {
|
||||
return;
|
||||
}
|
||||
|
||||
LOG_INFO(TAG, "Checking for EMERGENCY updates only...");
|
||||
checkForUpdates("stable"); // Check stable channel
|
||||
|
||||
String channel = _configManager.getOtaChannel();
|
||||
LOG_INFO(TAG, "Checking for EMERGENCY updates on channel '%s'...", channel.c_str());
|
||||
checkForUpdates(channel);
|
||||
|
||||
// Only proceed if emergency flag is set
|
||||
if (_updateAvailable && _isEmergency) {
|
||||
LOG_INFO(TAG, "🚨 EMERGENCY update detected during scheduled check - updating immediately");
|
||||
update("stable");
|
||||
update(channel);
|
||||
} else if (_updateAvailable && _isMandatory) {
|
||||
LOG_INFO(TAG, "⚠️ Mandatory update available, but will wait for next boot");
|
||||
} else {
|
||||
@@ -201,8 +202,8 @@ void OTAManager::checkForEmergencyUpdates() {
|
||||
}
|
||||
|
||||
void OTAManager::checkForUpdates() {
|
||||
// Boot-time check: only check stable channel for emergency/mandatory updates
|
||||
checkForUpdates("stable");
|
||||
// Use the device's persisted OTA channel (default "stable")
|
||||
checkForUpdates(_configManager.getOtaChannel());
|
||||
}
|
||||
|
||||
void OTAManager::checkForUpdates(const String& channel) {
|
||||
@@ -232,9 +233,13 @@ void OTAManager::checkForUpdates(const String& channel) {
|
||||
_isMandatory ? "YES" : "NO", _isEmergency ? "YES" : "NO");
|
||||
setStatus(Status::IDLE);
|
||||
|
||||
// Auto-update for emergency or mandatory updates during boot check
|
||||
if (channel == "stable" && (_isEmergency || _isMandatory)) {
|
||||
LOG_INFO(TAG, "Emergency/Mandatory update detected - starting automatic update");
|
||||
// Auto-update for emergency or mandatory updates.
|
||||
// Emergency: apply immediately regardless of channel.
|
||||
// Mandatory: apply on this boot check (any channel).
|
||||
// Optional: do nothing — wait for user/MQTT trigger.
|
||||
if (_isEmergency || _isMandatory) {
|
||||
LOG_INFO(TAG, "OTA: %s update detected on channel '%s' — starting automatic update",
|
||||
_isEmergency ? "Emergency" : "Mandatory", channel.c_str());
|
||||
update(channel);
|
||||
}
|
||||
} else {
|
||||
@@ -350,14 +355,19 @@ bool OTAManager::checkVersion(const String& channel) {
|
||||
|
||||
_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);
|
||||
// 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
|
||||
|
||||
// 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);
|
||||
_lastError = ErrorCode::CHANNEL_MISMATCH;
|
||||
continue;
|
||||
}
|
||||
@@ -1073,10 +1083,18 @@ bool OTAManager::performManualUpdate(const String& channel) {
|
||||
LOG_INFO(TAG, "Starting manual OTA update from %s channel (direct-to-flash)...", channel.c_str());
|
||||
setStatus(Status::DOWNLOADING);
|
||||
|
||||
String firmwareUrl = buildFirmwareUrl(channel);
|
||||
std::vector<String> servers = _configManager.getUpdateServers();
|
||||
String hwType = _configManager.getHardwareVariant();
|
||||
String fromVersion = getCurrentVersion().toString();
|
||||
String toVersion = _availableVersion.toString();
|
||||
|
||||
// Download directly to flash
|
||||
return downloadDirectToFlash(firmwareUrl, _expectedFileSize);
|
||||
for (size_t i = 0; i < servers.size(); i++) {
|
||||
String firmwareUrl = buildFirmwareUrl(servers[i], hwType, channel, toVersion);
|
||||
if (downloadDirectToFlash(firmwareUrl, _expectedFileSize, fromVersion, toVersion, channel)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════════════════════════════
|
||||
@@ -1110,7 +1128,8 @@ bool OTAManager::performCustomUpdate(const String& firmwareUrl, const String& ch
|
||||
|
||||
setStatus(Status::DOWNLOADING);
|
||||
|
||||
bool result = downloadDirectToFlash(firmwareUrl, fileSize);
|
||||
String fromVersion = getCurrentVersion().toString();
|
||||
bool result = downloadDirectToFlash(firmwareUrl, fileSize, fromVersion, version, "custom");
|
||||
|
||||
if (result) {
|
||||
LOG_INFO(TAG, "🚀 Custom firmware installed - device will reboot");
|
||||
@@ -1136,7 +1155,8 @@ void OTAManager::setHardwareVariant(const String& variant) {
|
||||
// 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 hwVersion = _configManager.getHwVersion();
|
||||
return baseUrl + "/api/firmware/" + hwType + "/" + channel + "/latest?hw_version=" + hwVersion + "¤t_version=" + currentVersion;
|
||||
}
|
||||
|
||||
// GET /api/firmware/{hw_type}/{channel}/{version}/info
|
||||
|
||||
@@ -118,6 +118,7 @@
|
||||
#include "FirmwareValidator/FirmwareValidator.hpp"
|
||||
#include "InputManager/InputManager.hpp"
|
||||
#include "Version.hpp"
|
||||
#include "NvsMigration/NvsMigration.hpp"
|
||||
|
||||
#define TAG "Main"
|
||||
|
||||
@@ -198,6 +199,13 @@ void setup()
|
||||
Serial.begin(115200);
|
||||
Serial.print("VESPER System Booting UP! - Version ");
|
||||
Serial.println(FW_VERSION);
|
||||
|
||||
// ── NVS schema migration ─────────────────────────────────────────────────
|
||||
// Must run before ConfigManager::begin() so it sees the new key names.
|
||||
// Safe to run on every boot — exits immediately if schema is already current.
|
||||
// Remove this call (and NvsMigration.*) once all devices have passed through
|
||||
// firmware 1.9.x via the staged OTA upgrade chain.
|
||||
NvsMigration::run();
|
||||
Wire.begin(4,15);
|
||||
auto& hwConfig = configManager.getHardwareConfig();
|
||||
SPI.begin(hwConfig.ethSpiSck, hwConfig.ethSpiMiso, hwConfig.ethSpiMosi);
|
||||
|
||||
Reference in New Issue
Block a user