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:
2026-03-15 11:39:11 +02:00
co-authored by Claude Sonnet 4.6
parent d4d8b1c380
commit 37b65cc15a
14 changed files with 561 additions and 96 deletions
+15 -11
View File
@@ -16,8 +16,8 @@ The firmware POSTs two events during an OTA update. Both are **best-effort** —
```json
{
"device_uid": "PV000000000000",
"hw_type": "VS",
"hw_version": "01",
"hw_type": "vesper",
"hw_version": "1.0",
"from_version": "1.2.3",
"to_version": "1.3.0",
"channel": "stable"
@@ -25,10 +25,10 @@ The firmware POSTs two events during an OTA update. Both are **best-effort** —
```
| Field | Type | Description |
|----------------|--------|--------------------------------------------------|
|----------------|--------|-----------------------------------------------------------------------|
| `device_uid` | string | Unique device identifier from NVS |
| `hw_type` | string | Hardware type code (e.g. `VS`, `VP`, `VX`) |
| `hw_version` | string | Hardware revision from NVS (e.g. `01`) |
| `hw_type` | string | Hardware type code (e.g. `vesper`, `vesper-plus`, `vesper-pro`) |
| `hw_version` | string | Hardware revision from NVS (e.g. `1.0`) |
| `from_version` | string | Semver of the firmware currently running |
| `to_version` | string | Semver of the firmware that was just downloaded |
| `channel` | string | Update channel (`stable`, `beta`, etc.) |
@@ -51,8 +51,8 @@ Any `2xx` status is accepted. Recommended: `204 No Content`.
```json
{
"device_uid": "PV000000000000",
"hw_type": "VS",
"hw_version": "01",
"hw_type": "vesper",
"hw_version": "1.0",
"from_version": "1.2.3",
"to_version": "1.3.0",
"channel": "stable",
@@ -97,13 +97,15 @@ Any `2xx` status is accepted. Recommended: `204 No Content`.
### Background
The firmware sends its current version as a query parameter on every version check:
The firmware sends its current version and hardware revision as query parameters on every version check:
```
GET /api/firmware/{hw_type}/{channel}/latest?current_version=5.7.1
GET /api/firmware/{hw_type}/{channel}/latest?hw_version=1.0&current_version=5.7.1
```
The server must use `current_version` to resolve upgrade chains and return the **correct next hop** rather than blindly returning the absolute latest. The device trusts whatever version the server returns and installs it.
Both parameters are optional. The server must use `current_version` to resolve upgrade chains and return the **correct next hop** rather than blindly returning the absolute latest. The device trusts whatever version the server returns and installs it.
`hw_version` allows the server to filter firmware releases to those compatible with the device's specific hardware revision — useful when a hardware change between revisions requires a different binary.
**Example:** Device is on `5.7.1`. Latest is `7.2.2` but has `min_fw_version = 6.0.0`.
- Without chain resolution → server returns `7.2.2` → device cannot install → update silently fails.
@@ -113,7 +115,7 @@ The server must use `current_version` to resolve upgrade chains and return the *
### Changes needed in `/api/firmware/{hw_type}/{channel}/latest`
1. **Accept `current_version` as an optional query parameter** (string, semver format e.g. `5.7.1`). If absent or unparseable, fall back to current behaviour (return absolute latest).
1. **Accept `hw_version` and `current_version` as optional query parameters** (both strings). If absent or unparseable, fall back to current behaviour (return absolute latest, no hw revision filtering).
2. **Resolve the next hop:**
```
@@ -135,6 +137,7 @@ WHERE hw_type = :hw_type
AND channel = :channel
AND version > :current_version
AND (min_fw_version IS NULL OR :current_version >= min_fw_version)
AND (min_hw_version IS NULL OR :hw_version >= min_hw_version) -- optional hw revision gate
ORDER BY version ASC -- semver-aware sort
LIMIT 1;
```
@@ -145,6 +148,7 @@ LIMIT 1;
| Scenario | Expected behaviour |
|---|---|
| `hw_version` absent / malformed | Ignore param, skip hw revision filtering |
| `current_version` absent / malformed | Ignore param, return absolute latest (existing behaviour) |
| Device already at latest | Return `404` or `200` with a "no update" indicator — firmware handles both |
| No version satisfies the chain constraint | Return `404` — firmware logs and skips |
+72 -9
View File
@@ -2,15 +2,20 @@
; Project Vesper — PlatformIO Configuration
; ═══════════════════════════════════════════════════════════════════════════════
;
; Hardware Variants:
; Hardware Variants (active):
; vesper-v1 — Kincony KC868-A6 (ESP32-D0WD-V3, 4MB flash) — current production board
; agnus-v1 — ESP32 base, no SD card, NVS-only settings storage
; agnus-mini-v1 — Same binary as agnus-v1, output limit enforced via app/NVS
;
; Future variants (not yet active):
; Future variants (commented out):
; vesper-plus-v1 — Vesper+ with RF remote support
; vesper-pro-v1 — Vesper Pro with onboard LCD
;
; Each environment auto-includes its variant header via -include variants/<name>.hpp
; which defines HAS_SD_CARD, HAS_RTC, OUTPUT_COUNT_MAX, etc. for that build.
;
; Build: pio run -e vesper-v1
; Upload: pio run -e vesper-v1 --target upload
; Upload: pio run -e vesper-v1 --target upload --upload-port COM8
; Monitor: pio device monitor
; Clean: pio run -e vesper-v1 --target clean
; ═══════════════════════════════════════════════════════════════════════════════
@@ -90,10 +95,68 @@ build_flags =
-DBOARD_VERSION=\"01\"
-DBOARD_NAME=\"Vesper\"
-DPSRAM_ENABLED=0
-DHAS_RF=0
-DHAS_LCD=0
-DMQTT_SECRET=\"deea8b2dbf21872bff8b4639ca16d0348358945ccd4c1cb6c5934ba510de1dce\"
-include variants/vesper.hpp
lib_deps = ${common.lib_deps}
; ───────────────────────────────────────────────────────────────────────────────
; AGNUS v1 — No SD card, NVS-only settings storage
; Same ESP32 base as Vesper. Agnus Mini is the same binary — output limiting
; is handled in the app and NVS, not in firmware.
; ───────────────────────────────────────────────────────────────────────────────
[env:agnus-v1]
platform = ${common.platform}
framework = ${common.framework}
board = esp32dev
monitor_speed = ${common.monitor_speed}
upload_speed = 921600
upload_protocol = esptool
board_build.partitions = min_spiffs.csv
build_unflags = -std=gnu++11
board_build.cmake_extra_args = -DCONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=4096
build_flags =
${common.build_flags_common}
-DBOARD_TYPE=\"AG\"
-DBOARD_VERSION=\"01\"
-DBOARD_NAME=\"Agnus\"
-DPSRAM_ENABLED=0
-DMQTT_SECRET=\"deea8b2dbf21872bff8b4639ca16d0348358945ccd4c1cb6c5934ba510de1dce\"
-include variants/agnus.hpp
lib_deps = ${common.lib_deps}
; ───────────────────────────────────────────────────────────────────────────────
; AGNUS MINI v1 — Same binary as agnus-v1, different NVS provisioning
; Output count is limited via the app and NVS key, not in firmware.
; Only exists as a separate env so OTA can target it independently.
; ───────────────────────────────────────────────────────────────────────────────
[env:agnus-mini-v1]
platform = ${common.platform}
framework = ${common.framework}
board = esp32dev
monitor_speed = ${common.monitor_speed}
upload_speed = 921600
upload_protocol = esptool
board_build.partitions = min_spiffs.csv
build_unflags = -std=gnu++11
board_build.cmake_extra_args = -DCONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=4096
build_flags =
${common.build_flags_common}
-DBOARD_TYPE=\"AM\"
-DBOARD_VERSION=\"01\"
-DBOARD_NAME=\"AgnusMini\"
-DPSRAM_ENABLED=0
-DMQTT_SECRET=\"deea8b2dbf21872bff8b4639ca16d0348358945ccd4c1cb6c5934ba510de1dce\"
-include variants/agnus.hpp
lib_deps = ${common.lib_deps}
@@ -112,8 +175,8 @@ lib_deps = ${common.lib_deps}
; -DBOARD_VERSION=\"01\"
; -DBOARD_NAME=\"Vesper+\"
; -DPSRAM_ENABLED=0
; -DHAS_RF=1
; -DHAS_LCD=0
; -DMQTT_SECRET=\"change-me-in-platformio-ini\"
; -include variants/vesper.hpp
; lib_deps = ${common.lib_deps}
@@ -131,6 +194,6 @@ lib_deps = ${common.lib_deps}
; -DBOARD_VERSION=\"01\"
; -DBOARD_NAME=\"VesperPro\"
; -DPSRAM_ENABLED=0
; -DHAS_RF=0
; -DHAS_LCD=1
; -DMQTT_SECRET=\"change-me-in-platformio-ini\"
; -include variants/vesper.hpp
; lib_deps = ${common.lib_deps}
+3 -3
View File
@@ -1,5 +1,5 @@
key,type,encoding,value
device_id,namespace,,
device_uid,data,string,PV000000000000
hw_type,data,string,VS
hw_version,data,string,01
serial,data,string,PV000000000000
hw_family,data,string,vesper
hw_revision,data,string,01
1 key type encoding value
2 device_id namespace
3 device_uid serial data string PV000000000000
4 hw_type hw_family data string VS vesper
5 hw_version hw_revision data string 01
@@ -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,21 +2,27 @@
#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"
};
}
@@ -26,6 +32,7 @@ CommandResult FirmwareHandler::execute(const CommandEnvelope& 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.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);
};
+34 -28
View File
@@ -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));
+15 -7
View File
@@ -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"
};
/**
@@ -221,6 +221,7 @@ public:
uint8_t sdLogLevel = 0;
uint8_t mqttLogLevel = 0;
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();
+202
View File
@@ -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;
}
+41
View File
@@ -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();
}
+38 -18
View File
@@ -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;
// 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 — server returns update_type
_updateChannel = channel; // channel is what we requested
// 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);
// 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 + "&current_version=" + currentVersion;
}
// GET /api/firmware/{hw_type}/{channel}/{version}/info
+8
View File
@@ -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);
+39
View File
@@ -0,0 +1,39 @@
// ═══════════════════════════════════════════════════════════════════════════════
// variants/agnus.hpp — Hardware capability definitions for Agnus v1
// ═══════════════════════════════════════════════════════════════════════════════
//
// This file is auto-included for all [env:agnus-*] builds via platformio.ini:
// build_flags = -include variants/agnus.hpp
//
// DO NOT include this file manually. It is injected at the compiler level so
// every translation unit sees the same definitions without explicit includes.
//
// Hardware: same ESP32 base as Vesper, no SD card.
// Agnus Mini is the same binary — output limiting is handled in the app/NVS.
// ═══════════════════════════════════════════════════════════════════════════════
#pragma once
// ── Identity ─────────────────────────────────────────────────────────────────
// HW_FAMILY matches the value stored in NVS key "hw_family" by the backend.
// The specific slug (e.g. "agnus" vs "agnus-mini") is set in NVS at provisioning
// time — HW_FAMILY here is the family prefix for this build.
#define HW_FAMILY "agnus" // Hardware family prefix (NVS hw_family will be e.g. "agnus" or "agnus-mini")
// ── Storage ──────────────────────────────────────────────────────────────────
#define HAS_SD_CARD 0 // No SD card — settings stored in NVS only
#define HAS_SPIFFS 0 // SPIFFS not used
// ── Connectivity ─────────────────────────────────────────────────────────────
#define HAS_ETHERNET 0 // WiFi only
#define HAS_RF 0 // No RF remote support
#define HAS_LCD 0 // No onboard LCD
// ── Output hardware ──────────────────────────────────────────────────────────
#define HAS_PCF8574 1 // PCF8574 I2C GPIO expanders for relay control
#define OUTPUT_COUNT_MAX 16 // Physical outputs available on the board
// (Agnus Mini limit is enforced via app/NVS,
// not in firmware)
// ── RTC ──────────────────────────────────────────────────────────────────────
#define HAS_RTC 1 // DS3231 RTC present
+37
View File
@@ -0,0 +1,37 @@
// ═══════════════════════════════════════════════════════════════════════════════
// variants/vesper.hpp — Hardware capability definitions for Vesper v1
// ═══════════════════════════════════════════════════════════════════════════════
//
// This file is auto-included for all [env:vesper-*] builds via platformio.ini:
// build_flags = -include variants/vesper.hpp
//
// DO NOT include this file manually. It is injected at the compiler level so
// every translation unit sees the same definitions without explicit includes.
//
// Hardware: Kincony KC868-A6 — ESP32-D0WD-V3, 4MB flash
// ═══════════════════════════════════════════════════════════════════════════════
#pragma once
// ── Identity ─────────────────────────────────────────────────────────────────
// HW_FAMILY matches the value stored in NVS key "hw_family" by the backend.
// It is used in OTA URL building and telemetry.
// The specific slug (e.g. "vesper-standard" vs "vesper-plus") is set in NVS
// at provisioning time — HW_FAMILY here is the family prefix for this build.
#define HW_FAMILY "vesper" // Hardware family prefix (NVS hw_family will be e.g. "vesper-standard")
// ── Storage ──────────────────────────────────────────────────────────────────
#define HAS_SD_CARD 1 // SD card present — configs stored on SD
#define HAS_SPIFFS 0 // SPIFFS not used (min_spiffs partition is tiny)
// ── Connectivity ─────────────────────────────────────────────────────────────
#define HAS_ETHERNET 0 // Ethernet removed in fw v138
#define HAS_RF 0 // No RF remote support on this variant
#define HAS_LCD 0 // No onboard LCD
// ── Output hardware ──────────────────────────────────────────────────────────
#define HAS_PCF8574 1 // PCF8574 I2C GPIO expanders for relay control
#define OUTPUT_COUNT_MAX 16 // Maximum physical outputs on this board
// ── RTC ──────────────────────────────────────────────────────────────────────
#define HAS_RTC 1 // DS3231 RTC present