Serial default VERBOSE→INFO, MQTT default NONE→WARNING, SD NONE→WARNING. Per-subsystem MQTT caps added in CommunicationRouter: BellEngine/ OutputManager/HealthMonitor/ConfigManager at WARNING to silence per-note and per-poll spam; Player/Telemetry/OTAManager at INFO to keep state transitions visible. Remove early Logging::setLevel() call in main.cpp — CommunicationRouter applies all three channels once the MQTT callback is wired. Loop heartbeat downgraded DEBUG→VERBOSE. HealthMonitor polling noise (skipping/performing lines) removed; subsystem status and completion lines VERBOSE→DEBUG. FirmwareValidator boot-path checks VERBOSE→INFO (one-shot, worth seeing). ConfigManager isHealthy() false-branches and NVS read trace VERBOSE→DEBUG. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1523 lines
62 KiB
C++
1523 lines
62 KiB
C++
#include "ConfigManager.hpp"
|
|
|
|
#define TAG "ConfigManager"
|
|
#include "../../src/Logging/Logging.hpp"
|
|
#include <WiFi.h> // For MAC address generation
|
|
#include <time.h> // For timestamp generation
|
|
#include <algorithm> // For std::sort
|
|
#include "mbedtls/md.h" // For HMAC-SHA256 password derivation
|
|
|
|
// NVS namespace for device identity storage
|
|
const char* ConfigManager::NVS_NAMESPACE = "device_id";
|
|
|
|
// 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()
|
|
createDefaultBellConfig();
|
|
}
|
|
|
|
void ConfigManager::initializeCleanDefaults() {
|
|
// This method is called after NVS loading to set up clean defaults
|
|
// and auto-generate identifiers from loaded deviceUID
|
|
|
|
// Generate network identifiers from deviceUID
|
|
generateNetworkIdentifiers();
|
|
|
|
// Set MQTT user to deviceUID for unique identification
|
|
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.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);
|
|
|
|
LOG_DEBUG(TAG, "ConfigManager - Clean defaults initialized with auto-generated identifiers");
|
|
}
|
|
|
|
void ConfigManager::generateNetworkIdentifiers() {
|
|
|
|
networkConfig.hostname = "BellSystems-" + deviceConfig.serial;
|
|
networkConfig.apSsid = "BellSystems-Setup-" + deviceConfig.serial;
|
|
|
|
|
|
LOG_DEBUG(TAG, "ConfigManager - Generated hostname: %s, AP SSID: %s",
|
|
networkConfig.hostname.c_str(), networkConfig.apSsid.c_str());
|
|
}
|
|
|
|
void ConfigManager::createDefaultBellConfig() {
|
|
// Initialize default durations (90ms for all bells)
|
|
for (uint8_t i = 0; i < 16; i++) {
|
|
bellConfig.durations[i] = 90;
|
|
bellConfig.outputs[i] = i; // 0-indexed mapping
|
|
}
|
|
}
|
|
|
|
bool ConfigManager::begin() {
|
|
LOG_INFO(TAG, "ConfigManager - ✅ Initializing...");
|
|
|
|
// Step 1: NVS init — required on all variants (device identity + Agnus user config)
|
|
if (!initializeNVS()) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ NVS initialization failed, using empty defaults");
|
|
} else {
|
|
loadDeviceIdentityFromNVS();
|
|
}
|
|
|
|
// Step 2: Auto-generate hostname, AP SSID, MQTT credentials from serial
|
|
initializeCleanDefaults();
|
|
|
|
#if HAS_SD_CARD
|
|
// ── Vesper (SD card present) ─────────────────────────────────────────────
|
|
if (!ensureSDCard()) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ SD Card initialization failed, using defaults");
|
|
return false;
|
|
}
|
|
|
|
if (!loadUpdateServers()) {
|
|
LOG_WARNING(TAG, "ConfigManager - ⚠️ Could not load update servers - using fallback only");
|
|
}
|
|
|
|
if (!loadNetworkConfig()) {
|
|
LOG_WARNING(TAG, "ConfigManager - ⚠️ Creating default network config file");
|
|
saveNetworkConfig();
|
|
}
|
|
|
|
if (!loadTimeConfig()) {
|
|
LOG_WARNING(TAG, "ConfigManager - ⚠️ Creating default time config file (GMT+2)");
|
|
saveTimeConfig();
|
|
}
|
|
|
|
if (!loadBellDurations()) {
|
|
LOG_WARNING(TAG, "ConfigManager - ⚠️ Creating default bell durations file");
|
|
saveBellDurations();
|
|
}
|
|
|
|
if (!loadBellOutputs()) {
|
|
LOG_WARNING(TAG, "ConfigManager - ⚠️ Creating default bell outputs file");
|
|
saveBellOutputs();
|
|
}
|
|
|
|
if (!loadClockConfig()) {
|
|
LOG_WARNING(TAG, "ConfigManager - ⚠️ Creating default clock config file");
|
|
saveClockConfig();
|
|
}
|
|
|
|
if (!loadClockState()) {
|
|
LOG_WARNING(TAG, "ConfigManager - ⚠️ Creating default clock state file");
|
|
saveClockState();
|
|
}
|
|
|
|
if (!loadGeneralConfig()) {
|
|
LOG_WARNING(TAG, "ConfigManager - ⚠️ Creating default general config file");
|
|
saveGeneralConfig();
|
|
}
|
|
|
|
#else
|
|
// ── Agnus (no SD card — NVS only) ───────────────────────────────────────
|
|
LOG_INFO(TAG, "ConfigManager - No SD card variant — loading all user config from NVS");
|
|
|
|
loadNetworkConfigFromNVS();
|
|
loadBellConfigFromNVS();
|
|
loadGeneralConfigFromNVS();
|
|
// No time/clock/update-server config on Agnus.
|
|
#endif
|
|
|
|
LOG_INFO(TAG, "ConfigManager - ✅ Initialization Complete — Serial: %s, Hostname: %s",
|
|
deviceConfig.serial.c_str(), networkConfig.hostname.c_str());
|
|
return true;
|
|
}
|
|
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
// NVS (NON-VOLATILE STORAGE) IMPLEMENTATION
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
|
|
bool ConfigManager::initializeNVS() {
|
|
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, "ConfigManager - ⚠️ NVS partition truncated, erasing...");
|
|
ESP_ERROR_CHECK(nvs_flash_erase());
|
|
err = nvs_flash_init();
|
|
}
|
|
|
|
if (err != ESP_OK) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to initialize NVS flash: %s", esp_err_to_name(err));
|
|
return false;
|
|
}
|
|
|
|
err = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &nvsHandle);
|
|
if (err != ESP_OK) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to open NVS handle: %s", esp_err_to_name(err));
|
|
return false;
|
|
}
|
|
|
|
LOG_DEBUG(TAG, "ConfigManager - NVS initialized successfully");
|
|
return true;
|
|
}
|
|
|
|
bool ConfigManager::loadDeviceIdentityFromNVS() {
|
|
if (nvsHandle == 0) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ NVS not initialized, cannot load device identity");
|
|
return false;
|
|
}
|
|
|
|
// Read factory-set device identity from NVS (READ-ONLY)
|
|
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.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!");
|
|
LOG_ERROR(TAG, " ⚠️ Please flash factory firmware to set device identity");
|
|
LOG_ERROR(TAG, "═══════════════════════════════════════════════════════════════════════════");
|
|
return false;
|
|
}
|
|
|
|
LOG_INFO(TAG, "═══════════════════════════════════════════════════════════════════════════");
|
|
LOG_INFO(TAG, " 🏭 FACTORY DEVICE IDENTITY LOADED FROM NVS (READ-ONLY)");
|
|
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, "═══════════════════════════════════════════════════════════════════════════");
|
|
|
|
return true;
|
|
}
|
|
|
|
// REMOVED: saveDeviceIdentityToNVS() - Production firmware MUST NOT write device identity
|
|
// 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) {
|
|
if (nvsHandle == 0) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ NVS not initialized, returning default for key: %s", key);
|
|
return defaultValue;
|
|
}
|
|
|
|
size_t required_size = 0;
|
|
esp_err_t err = nvs_get_str(nvsHandle, key, NULL, &required_size);
|
|
|
|
if (err == ESP_ERR_NVS_NOT_FOUND) {
|
|
LOG_DEBUG(TAG, "ConfigManager - NVS key '%s' not found, using default: %s", key, defaultValue.c_str());
|
|
return defaultValue;
|
|
}
|
|
|
|
if (err != ESP_OK) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ Error reading NVS key '%s': %s", key, esp_err_to_name(err));
|
|
return defaultValue;
|
|
}
|
|
|
|
char* buffer = new char[required_size];
|
|
err = nvs_get_str(nvsHandle, key, buffer, &required_size);
|
|
|
|
if (err != ESP_OK) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ Error reading NVS value for key '%s': %s", key, esp_err_to_name(err));
|
|
delete[] buffer;
|
|
return defaultValue;
|
|
}
|
|
|
|
String result = String(buffer);
|
|
delete[] buffer;
|
|
|
|
LOG_DEBUG(TAG, "ConfigManager - NVS key '%s': %s", key, result.c_str());
|
|
return result;
|
|
}
|
|
|
|
uint8_t ConfigManager::readNVSU8(const char* key, uint8_t defaultValue) {
|
|
if (nvsHandle == 0) return defaultValue;
|
|
uint8_t val = defaultValue;
|
|
esp_err_t err = nvs_get_u8(nvsHandle, key, &val);
|
|
if (err == ESP_ERR_NVS_NOT_FOUND) return defaultValue;
|
|
if (err != ESP_OK) { LOG_ERROR(TAG, "NVS read u8 '%s': %s", key, esp_err_to_name(err)); return defaultValue; }
|
|
return val;
|
|
}
|
|
|
|
uint16_t ConfigManager::readNVSU16(const char* key, uint16_t defaultValue) {
|
|
if (nvsHandle == 0) return defaultValue;
|
|
uint16_t val = defaultValue;
|
|
esp_err_t err = nvs_get_u16(nvsHandle, key, &val);
|
|
if (err == ESP_ERR_NVS_NOT_FOUND) return defaultValue;
|
|
if (err != ESP_OK) { LOG_ERROR(TAG, "NVS read u16 '%s': %s", key, esp_err_to_name(err)); return defaultValue; }
|
|
return val;
|
|
}
|
|
|
|
bool ConfigManager::readNVSBool(const char* key, bool defaultValue) {
|
|
uint8_t val = readNVSU8(key, defaultValue ? 1 : 0);
|
|
return val != 0;
|
|
}
|
|
|
|
bool ConfigManager::writeNVSString(const char* key, const String& value) {
|
|
if (nvsHandle == 0) return false;
|
|
esp_err_t err = nvs_set_str(nvsHandle, key, value.c_str());
|
|
if (err != ESP_OK) { LOG_ERROR(TAG, "NVS write str '%s': %s", key, esp_err_to_name(err)); return false; }
|
|
return true;
|
|
}
|
|
|
|
bool ConfigManager::writeNVSU8(const char* key, uint8_t value) {
|
|
if (nvsHandle == 0) return false;
|
|
esp_err_t err = nvs_set_u8(nvsHandle, key, value);
|
|
if (err != ESP_OK) { LOG_ERROR(TAG, "NVS write u8 '%s': %s", key, esp_err_to_name(err)); return false; }
|
|
return true;
|
|
}
|
|
|
|
bool ConfigManager::writeNVSU16(const char* key, uint16_t value) {
|
|
if (nvsHandle == 0) return false;
|
|
esp_err_t err = nvs_set_u16(nvsHandle, key, value);
|
|
if (err != ESP_OK) { LOG_ERROR(TAG, "NVS write u16 '%s': %s", key, esp_err_to_name(err)); return false; }
|
|
return true;
|
|
}
|
|
|
|
bool ConfigManager::writeNVSBool(const char* key, bool value) {
|
|
return writeNVSU8(key, value ? 1 : 0);
|
|
}
|
|
|
|
bool ConfigManager::commitNVS() {
|
|
if (nvsHandle == 0) return false;
|
|
esp_err_t err = nvs_commit(nvsHandle);
|
|
if (err != ESP_OK) { LOG_ERROR(TAG, "NVS commit failed: %s", esp_err_to_name(err)); return false; }
|
|
return true;
|
|
}
|
|
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
// STANDARD SD CARD FUNCTIONALITY
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
|
|
bool ConfigManager::ensureSDCard() {
|
|
if (!sdInitialized) {
|
|
sdInitialized = SD.begin(hardwareConfig.sdChipSelect);
|
|
if (!sdInitialized) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ SD Card not available");
|
|
}
|
|
}
|
|
return sdInitialized;
|
|
}
|
|
|
|
|
|
bool ConfigManager::saveToSD() {
|
|
if (!ensureSDCard()) {
|
|
return false;
|
|
}
|
|
|
|
bool success = true;
|
|
success &= saveBellDurations();
|
|
success &= saveClockConfig();
|
|
success &= saveClockState();
|
|
return success;
|
|
}
|
|
|
|
// 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() {
|
|
return true;
|
|
}
|
|
|
|
bool ConfigManager::loadDeviceConfig() {
|
|
return true;
|
|
}
|
|
|
|
bool ConfigManager::isHealthy() const {
|
|
#if HAS_SD_CARD
|
|
if (!sdInitialized) {
|
|
LOG_DEBUG(TAG, "ConfigManager - Unhealthy: SD card not initialized");
|
|
return false;
|
|
}
|
|
#endif
|
|
|
|
if (deviceConfig.serial.isEmpty()) {
|
|
LOG_DEBUG(TAG, "ConfigManager - Unhealthy: Serial not set (factory configuration required)");
|
|
return false;
|
|
}
|
|
|
|
if (deviceConfig.hwFamily.isEmpty()) {
|
|
LOG_DEBUG(TAG, "ConfigManager - Unhealthy: HW family not set (factory configuration required)");
|
|
return false;
|
|
}
|
|
|
|
if (networkConfig.hostname.isEmpty()) {
|
|
LOG_DEBUG(TAG, "ConfigManager - Unhealthy: Hostname not generated (initialization issue)");
|
|
return false;
|
|
}
|
|
|
|
// Note: WiFi credentials are handled by WiFiManager, not checked here
|
|
|
|
return true;
|
|
}
|
|
|
|
// Bell configuration methods remain unchanged...
|
|
bool ConfigManager::loadBellDurations() {
|
|
if (!ensureSDCard()) {
|
|
return false;
|
|
}
|
|
|
|
File file = SD.open("/settings/relayTimings.json", FILE_READ);
|
|
if (!file) {
|
|
LOG_WARNING(TAG, "ConfigManager - ⚠️ Settings file not found on SD. Using default bell durations.");
|
|
return false;
|
|
}
|
|
|
|
StaticJsonDocument<512> doc;
|
|
DeserializationError error = deserializeJson(doc, file);
|
|
file.close();
|
|
|
|
if (error) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to parse settings from SD. Using default bell durations.");
|
|
return false;
|
|
}
|
|
|
|
for (uint8_t i = 0; i < 16; i++) {
|
|
String key = String("b") + (i + 1);
|
|
if (doc.containsKey(key)) {
|
|
bellConfig.durations[i] = doc[key].as<uint16_t>();
|
|
}
|
|
}
|
|
|
|
LOG_DEBUG(TAG, "ConfigManager - Bell durations loaded from SD");
|
|
return true;
|
|
}
|
|
|
|
bool ConfigManager::saveBellDurations() {
|
|
#if !HAS_SD_CARD
|
|
return saveBellConfigToNVS();
|
|
#endif
|
|
if (!ensureSDCard()) return false;
|
|
|
|
StaticJsonDocument<512> doc;
|
|
for (uint8_t i = 0; i < 16; i++) {
|
|
String key = String("b") + (i + 1);
|
|
doc[key] = bellConfig.durations[i];
|
|
}
|
|
|
|
char buffer[512];
|
|
size_t len = serializeJson(doc, buffer, sizeof(buffer));
|
|
|
|
if (len == 0 || len >= sizeof(buffer)) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to serialize bell durations JSON");
|
|
return false;
|
|
}
|
|
|
|
saveFileToSD("/settings", "relayTimings.json", buffer);
|
|
LOG_DEBUG(TAG, "ConfigManager - Bell durations saved to SD");
|
|
return true;
|
|
}
|
|
|
|
bool ConfigManager::loadBellOutputs() {
|
|
if (!ensureSDCard()) {
|
|
return false;
|
|
}
|
|
|
|
File file = SD.open("/settings/bellOutputs.json", FILE_READ);
|
|
if (!file) {
|
|
LOG_WARNING(TAG, "ConfigManager - ⚠️ Bell outputs file not found on SD. Using default 1:1 mapping.");
|
|
return false;
|
|
}
|
|
|
|
StaticJsonDocument<512> doc;
|
|
DeserializationError error = deserializeJson(doc, file);
|
|
file.close();
|
|
|
|
if (error) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to parse bell outputs from SD. Using defaults.");
|
|
return false;
|
|
}
|
|
|
|
for (uint8_t i = 0; i < 16; i++) {
|
|
String key = String("b") + (i + 1);
|
|
if (doc.containsKey(key)) {
|
|
bellConfig.outputs[i] = doc[key].as<uint16_t>(); // Already 0-indexed in file
|
|
}
|
|
}
|
|
|
|
LOG_DEBUG(TAG, "ConfigManager - Bell outputs loaded from SD");
|
|
return true;
|
|
}
|
|
|
|
bool ConfigManager::saveBellOutputs() {
|
|
#if !HAS_SD_CARD
|
|
return saveBellConfigToNVS();
|
|
#endif
|
|
if (!ensureSDCard()) return false;
|
|
|
|
StaticJsonDocument<512> doc;
|
|
for (uint8_t i = 0; i < 16; i++) {
|
|
String key = String("b") + (i + 1);
|
|
doc[key] = bellConfig.outputs[i]; // Save 0-indexed outputs
|
|
}
|
|
|
|
char buffer[512];
|
|
size_t len = serializeJson(doc, buffer, sizeof(buffer));
|
|
|
|
if (len == 0 || len >= sizeof(buffer)) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to serialize bell outputs JSON");
|
|
return false;
|
|
}
|
|
|
|
saveFileToSD("/settings", "bellOutputs.json", buffer);
|
|
LOG_DEBUG(TAG, "ConfigManager - Bell outputs saved to SD");
|
|
return true;
|
|
}
|
|
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
// BELL CONFIG — NVS STORAGE (Agnus: no SD card)
|
|
// NVS key layout:
|
|
// bd0..bd15 — bell durations (u16)
|
|
// bo0..bo15 — bell outputs (u16)
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
#if !HAS_SD_CARD
|
|
bool ConfigManager::loadBellConfigFromNVS() {
|
|
bool anyFound = false;
|
|
for (uint8_t i = 0; i < 16; i++) {
|
|
char keyD[5], keyO[5];
|
|
snprintf(keyD, sizeof(keyD), "bd%d", i);
|
|
snprintf(keyO, sizeof(keyO), "bo%d", i);
|
|
uint16_t dur = readNVSU16(keyD, bellConfig.durations[i]);
|
|
uint16_t out = readNVSU16(keyO, bellConfig.outputs[i]);
|
|
// readNVSU16 returns the default when key is not found — detect a real
|
|
// stored value by trying a sentinel read with an unlikely default.
|
|
// Simpler: just always write what we got; if nothing was stored the
|
|
// defaults from createDefaultBellConfig() remain unchanged.
|
|
bellConfig.durations[i] = dur;
|
|
bellConfig.outputs[i] = out;
|
|
anyFound = true; // NVS open succeeded — consider it loaded
|
|
}
|
|
LOG_DEBUG(TAG, "ConfigManager - Bell config loaded from NVS");
|
|
return anyFound;
|
|
}
|
|
|
|
bool ConfigManager::saveBellConfigToNVS() {
|
|
bool ok = true;
|
|
for (uint8_t i = 0; i < 16; i++) {
|
|
char keyD[5], keyO[5];
|
|
snprintf(keyD, sizeof(keyD), "bd%d", i);
|
|
snprintf(keyO, sizeof(keyO), "bo%d", i);
|
|
ok &= writeNVSU16(keyD, bellConfig.durations[i]);
|
|
ok &= writeNVSU16(keyO, bellConfig.outputs[i]);
|
|
}
|
|
ok &= commitNVS();
|
|
LOG_DEBUG(TAG, "ConfigManager - Bell config saved to NVS (%s)", ok ? "ok" : "errors");
|
|
return ok;
|
|
}
|
|
#endif
|
|
|
|
void ConfigManager::updateBellDurations(JsonVariant doc) {
|
|
for (uint8_t i = 0; i < 16; i++) {
|
|
String key = String("b") + (i + 1);
|
|
if (doc.containsKey(key)) {
|
|
bellConfig.durations[i] = doc[key].as<uint16_t>();
|
|
}
|
|
}
|
|
LOG_DEBUG(TAG, "ConfigManager - Updated bell durations");
|
|
}
|
|
|
|
void ConfigManager::updateBellOutputs(JsonVariant doc) {
|
|
for (uint8_t i = 0; i < 16; i++) {
|
|
String key = String("b") + (i + 1);
|
|
if (doc.containsKey(key)) {
|
|
bellConfig.outputs[i] = doc[key].as<uint16_t>() - 1;
|
|
LOG_DEBUG(TAG, "ConfigManager - Bell %d output set to %d", i + 1, bellConfig.outputs[i]);
|
|
}
|
|
}
|
|
LOG_DEBUG(TAG, "ConfigManager - Updated bell outputs");
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
uint16_t ConfigManager::getBellDuration(uint8_t bellIndex) const {
|
|
if (bellIndex >= 16) return 90;
|
|
return bellConfig.durations[bellIndex];
|
|
}
|
|
|
|
uint16_t ConfigManager::getBellOutput(uint8_t bellIndex) const {
|
|
if (bellIndex >= 16) return bellIndex;
|
|
return bellConfig.outputs[bellIndex];
|
|
}
|
|
|
|
void ConfigManager::setBellDuration(uint8_t bellIndex, uint16_t duration) {
|
|
if (bellIndex < 16) {
|
|
bellConfig.durations[bellIndex] = duration;
|
|
}
|
|
}
|
|
|
|
void ConfigManager::setBellOutput(uint8_t bellIndex, uint16_t output) {
|
|
if (bellIndex < 16) {
|
|
bellConfig.outputs[bellIndex] = output;
|
|
}
|
|
}
|
|
|
|
void ConfigManager::saveFileToSD(const char* dirPath, const char* filename, const char* data) {
|
|
if (!ensureSDCard()) {
|
|
return;
|
|
}
|
|
|
|
if (!SD.exists(dirPath)) {
|
|
SD.mkdir(dirPath);
|
|
}
|
|
|
|
String fullPath = String(dirPath);
|
|
if (!fullPath.endsWith("/")) fullPath += "/";
|
|
fullPath += filename;
|
|
|
|
File file = SD.open(fullPath.c_str(), FILE_WRITE);
|
|
if (!file) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to open file: %s", fullPath.c_str());
|
|
return;
|
|
}
|
|
|
|
file.print(data);
|
|
file.close();
|
|
LOG_DEBUG(TAG, "ConfigManager - File %s saved successfully", fullPath.c_str());
|
|
}
|
|
|
|
// Clock configuration methods and other remaining methods follow the same pattern...
|
|
// (Implementation would continue with all the clock config methods, update servers, etc.)
|
|
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
// MISSING CLOCK CONFIGURATION METHODS
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
|
|
void ConfigManager::updateClockOutputs(JsonVariant doc) {
|
|
if (doc.containsKey("c1")) {
|
|
clockConfig.c1output = doc["c1"].as<uint8_t>();
|
|
}
|
|
if (doc.containsKey("c2")) {
|
|
clockConfig.c2output = doc["c2"].as<uint8_t>();
|
|
}
|
|
if (doc.containsKey("pulseDuration")) {
|
|
clockConfig.pulseDuration = doc["pulseDuration"].as<uint16_t>();
|
|
}
|
|
if (doc.containsKey("pauseDuration")) {
|
|
clockConfig.pauseDuration = doc["pauseDuration"].as<uint16_t>();
|
|
}
|
|
LOG_DEBUG(TAG, "ConfigManager - Updated Clock outputs to: C1: %d / C2: %d, Pulse: %dms, Pause: %dms",
|
|
clockConfig.c1output, clockConfig.c2output, clockConfig.pulseDuration, clockConfig.pauseDuration);
|
|
}
|
|
|
|
void ConfigManager::updateClockAlerts(JsonVariant doc) {
|
|
if (doc.containsKey("alertType")) {
|
|
clockConfig.alertType = doc["alertType"].as<String>();
|
|
}
|
|
if (doc.containsKey("alertRingInterval")) {
|
|
clockConfig.alertRingInterval = doc["alertRingInterval"].as<uint16_t>();
|
|
}
|
|
if (doc.containsKey("hourBell")) {
|
|
uint8_t bellNum = doc["hourBell"].as<uint8_t>();
|
|
// Convert from 1-based (API) to 0-based (internal), or keep 255 (disabled)
|
|
clockConfig.hourBell = (bellNum == 255) ? 255 : bellNum - 1;
|
|
}
|
|
if (doc.containsKey("halfBell")) {
|
|
uint8_t bellNum = doc["halfBell"].as<uint8_t>();
|
|
// Convert from 1-based (API) to 0-based (internal), or keep 255 (disabled)
|
|
clockConfig.halfBell = (bellNum == 255) ? 255 : bellNum - 1;
|
|
}
|
|
if (doc.containsKey("quarterBell")) {
|
|
uint8_t bellNum = doc["quarterBell"].as<uint8_t>();
|
|
// Convert from 1-based (API) to 0-based (internal), or keep 255 (disabled)
|
|
clockConfig.quarterBell = (bellNum == 255) ? 255 : bellNum - 1;
|
|
}
|
|
LOG_DEBUG(TAG, "ConfigManager - Updated Clock alerts");
|
|
}
|
|
|
|
void ConfigManager::updateClockBacklight(JsonVariant doc) {
|
|
if (doc.containsKey("enabled")) {
|
|
clockConfig.backlight = doc["enabled"].as<bool>();
|
|
}
|
|
if (doc.containsKey("output")) {
|
|
clockConfig.backlightOutput = doc["output"].as<uint8_t>();
|
|
}
|
|
if (doc.containsKey("onTime")) {
|
|
clockConfig.backlightOnTime = doc["onTime"].as<String>();
|
|
}
|
|
if (doc.containsKey("offTime")) {
|
|
clockConfig.backlightOffTime = doc["offTime"].as<String>();
|
|
}
|
|
LOG_DEBUG(TAG, "ConfigManager - Updated Clock backlight");
|
|
}
|
|
|
|
void ConfigManager::updateClockSilence(JsonVariant doc) {
|
|
if (doc.containsKey("daytime")) {
|
|
JsonObject daytime = doc["daytime"];
|
|
if (daytime.containsKey("enabled")) {
|
|
clockConfig.daytimeSilenceEnabled = daytime["enabled"].as<bool>();
|
|
}
|
|
if (daytime.containsKey("onTime")) {
|
|
clockConfig.daytimeSilenceOnTime = daytime["onTime"].as<String>();
|
|
}
|
|
if (daytime.containsKey("offTime")) {
|
|
clockConfig.daytimeSilenceOffTime = daytime["offTime"].as<String>();
|
|
}
|
|
}
|
|
if (doc.containsKey("nighttime")) {
|
|
JsonObject nighttime = doc["nighttime"];
|
|
if (nighttime.containsKey("enabled")) {
|
|
clockConfig.nighttimeSilenceEnabled = nighttime["enabled"].as<bool>();
|
|
}
|
|
if (nighttime.containsKey("onTime")) {
|
|
clockConfig.nighttimeSilenceOnTime = nighttime["onTime"].as<String>();
|
|
}
|
|
if (nighttime.containsKey("offTime")) {
|
|
clockConfig.nighttimeSilenceOffTime = nighttime["offTime"].as<String>();
|
|
}
|
|
}
|
|
LOG_DEBUG(TAG, "ConfigManager - Updated Clock silence");
|
|
}
|
|
|
|
bool ConfigManager::loadClockConfig() {
|
|
if (!ensureSDCard()) return false;
|
|
|
|
File file = SD.open("/settings/clockConfig.json", FILE_READ);
|
|
if (!file) {
|
|
LOG_WARNING(TAG, "ConfigManager - ⚠️ Clock config file not found - using defaults");
|
|
return false;
|
|
}
|
|
|
|
StaticJsonDocument<1024> doc; // Increased size for all settings
|
|
DeserializationError error = deserializeJson(doc, file);
|
|
file.close();
|
|
|
|
if (error) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to parse clock config from SD: %s", error.c_str());
|
|
return false;
|
|
}
|
|
|
|
// Clock enable/outputs
|
|
if (doc.containsKey("enabled")) clockConfig.enabled = doc["enabled"].as<bool>();
|
|
if (doc.containsKey("c1output")) clockConfig.c1output = doc["c1output"].as<uint8_t>();
|
|
if (doc.containsKey("c2output")) clockConfig.c2output = doc["c2output"].as<uint8_t>();
|
|
if (doc.containsKey("pulseDuration")) clockConfig.pulseDuration = doc["pulseDuration"].as<uint16_t>();
|
|
if (doc.containsKey("pauseDuration")) clockConfig.pauseDuration = doc["pauseDuration"].as<uint16_t>();
|
|
|
|
// Alert settings
|
|
if (doc.containsKey("alertType")) clockConfig.alertType = doc["alertType"].as<String>();
|
|
if (doc.containsKey("alertRingInterval")) clockConfig.alertRingInterval = doc["alertRingInterval"].as<uint16_t>();
|
|
if (doc.containsKey("hourBell")) clockConfig.hourBell = doc["hourBell"].as<uint8_t>();
|
|
if (doc.containsKey("halfBell")) clockConfig.halfBell = doc["halfBell"].as<uint8_t>();
|
|
if (doc.containsKey("quarterBell")) clockConfig.quarterBell = doc["quarterBell"].as<uint8_t>();
|
|
|
|
// Backlight settings
|
|
if (doc.containsKey("backlight")) clockConfig.backlight = doc["backlight"].as<bool>();
|
|
if (doc.containsKey("backlightOutput")) clockConfig.backlightOutput = doc["backlightOutput"].as<uint8_t>();
|
|
if (doc.containsKey("backlightOnTime")) clockConfig.backlightOnTime = doc["backlightOnTime"].as<String>();
|
|
if (doc.containsKey("backlightOffTime")) clockConfig.backlightOffTime = doc["backlightOffTime"].as<String>();
|
|
|
|
// Silence period settings
|
|
if (doc.containsKey("daytimeSilenceEnabled")) clockConfig.daytimeSilenceEnabled = doc["daytimeSilenceEnabled"].as<bool>();
|
|
if (doc.containsKey("daytimeSilenceOnTime")) clockConfig.daytimeSilenceOnTime = doc["daytimeSilenceOnTime"].as<String>();
|
|
if (doc.containsKey("daytimeSilenceOffTime")) clockConfig.daytimeSilenceOffTime = doc["daytimeSilenceOffTime"].as<String>();
|
|
if (doc.containsKey("nighttimeSilenceEnabled")) clockConfig.nighttimeSilenceEnabled = doc["nighttimeSilenceEnabled"].as<bool>();
|
|
if (doc.containsKey("nighttimeSilenceOnTime")) clockConfig.nighttimeSilenceOnTime = doc["nighttimeSilenceOnTime"].as<String>();
|
|
if (doc.containsKey("nighttimeSilenceOffTime")) clockConfig.nighttimeSilenceOffTime = doc["nighttimeSilenceOffTime"].as<String>();
|
|
|
|
LOG_DEBUG(TAG, "ConfigManager - Clock config loaded");
|
|
return true;
|
|
}
|
|
|
|
bool ConfigManager::saveClockConfig() {
|
|
if (!ensureSDCard()) return false;
|
|
|
|
StaticJsonDocument<1024> doc; // Increased size for all settings
|
|
|
|
// Clock enable/outputs
|
|
doc["enabled"] = clockConfig.enabled;
|
|
doc["c1output"] = clockConfig.c1output;
|
|
doc["c2output"] = clockConfig.c2output;
|
|
doc["pulseDuration"] = clockConfig.pulseDuration;
|
|
doc["pauseDuration"] = clockConfig.pauseDuration;
|
|
|
|
// Alert settings
|
|
doc["alertType"] = clockConfig.alertType;
|
|
doc["alertRingInterval"] = clockConfig.alertRingInterval;
|
|
doc["hourBell"] = clockConfig.hourBell;
|
|
doc["halfBell"] = clockConfig.halfBell;
|
|
doc["quarterBell"] = clockConfig.quarterBell;
|
|
|
|
// Backlight settings
|
|
doc["backlight"] = clockConfig.backlight;
|
|
doc["backlightOutput"] = clockConfig.backlightOutput;
|
|
doc["backlightOnTime"] = clockConfig.backlightOnTime;
|
|
doc["backlightOffTime"] = clockConfig.backlightOffTime;
|
|
|
|
// Silence period settings
|
|
doc["daytimeSilenceEnabled"] = clockConfig.daytimeSilenceEnabled;
|
|
doc["daytimeSilenceOnTime"] = clockConfig.daytimeSilenceOnTime;
|
|
doc["daytimeSilenceOffTime"] = clockConfig.daytimeSilenceOffTime;
|
|
doc["nighttimeSilenceEnabled"] = clockConfig.nighttimeSilenceEnabled;
|
|
doc["nighttimeSilenceOnTime"] = clockConfig.nighttimeSilenceOnTime;
|
|
doc["nighttimeSilenceOffTime"] = clockConfig.nighttimeSilenceOffTime;
|
|
|
|
char buffer[1024];
|
|
size_t len = serializeJson(doc, buffer, sizeof(buffer));
|
|
|
|
if (len == 0 || len >= sizeof(buffer)) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to serialize clock config JSON");
|
|
return false;
|
|
}
|
|
|
|
saveFileToSD("/settings", "clockConfig.json", buffer);
|
|
LOG_DEBUG(TAG, "ConfigManager - Clock config saved");
|
|
return true;
|
|
}
|
|
|
|
bool ConfigManager::loadClockState() {
|
|
if (!ensureSDCard()) return false;
|
|
|
|
File file = SD.open("/settings/clockState.json", FILE_READ);
|
|
if (!file) {
|
|
LOG_WARNING(TAG, "ConfigManager - ⚠️ Clock state file not found - using defaults");
|
|
clockConfig.physicalHour = 0;
|
|
clockConfig.physicalMinute = 0;
|
|
clockConfig.nextOutputIsC1 = true;
|
|
clockConfig.lastSyncTime = 0;
|
|
return false;
|
|
}
|
|
|
|
StaticJsonDocument<256> doc;
|
|
DeserializationError error = deserializeJson(doc, file);
|
|
file.close();
|
|
|
|
if (error) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to parse clock state from SD: %s", error.c_str());
|
|
return false;
|
|
}
|
|
|
|
clockConfig.physicalHour = doc["hour"].as<uint8_t>() % 12;
|
|
clockConfig.physicalMinute = doc["minute"].as<uint8_t>() % 60;
|
|
clockConfig.nextOutputIsC1 = doc["nextIsC1"].as<bool>();
|
|
clockConfig.lastSyncTime = doc["lastSyncTime"].as<uint32_t>();
|
|
|
|
LOG_DEBUG(TAG, "ConfigManager - Clock state loaded");
|
|
return true;
|
|
}
|
|
|
|
bool ConfigManager::saveClockState() {
|
|
if (!ensureSDCard()) return false;
|
|
|
|
StaticJsonDocument<256> doc;
|
|
doc["hour"] = clockConfig.physicalHour;
|
|
doc["minute"] = clockConfig.physicalMinute;
|
|
doc["nextIsC1"] = clockConfig.nextOutputIsC1;
|
|
doc["lastSyncTime"] = clockConfig.lastSyncTime;
|
|
|
|
char buffer[256];
|
|
size_t len = serializeJson(doc, buffer, sizeof(buffer));
|
|
|
|
if (len == 0 || len >= sizeof(buffer)) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to serialize clock state JSON");
|
|
return false;
|
|
}
|
|
|
|
saveFileToSD("/settings", "clockState.json", buffer);
|
|
LOG_DEBUG(TAG, "ConfigManager - Clock state saved");
|
|
return true;
|
|
}
|
|
|
|
bool ConfigManager::loadUpdateServers() {
|
|
if (!ensureSDCard()) return false;
|
|
|
|
File file = SD.open("/settings/updateServers.json", FILE_READ);
|
|
if (!file) {
|
|
LOG_DEBUG(TAG, "ConfigManager - Update servers file not found - using fallback only");
|
|
return false;
|
|
}
|
|
|
|
StaticJsonDocument<1024> doc;
|
|
DeserializationError error = deserializeJson(doc, file);
|
|
file.close();
|
|
|
|
if (error) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to parse update servers JSON: %s", error.c_str());
|
|
return false;
|
|
}
|
|
|
|
updateServers.clear();
|
|
if (doc.containsKey("servers") && doc["servers"].is<JsonArray>()) {
|
|
JsonArray serversArray = doc["servers"];
|
|
for (JsonObject server : serversArray) {
|
|
if (server.containsKey("url")) {
|
|
String url = server["url"].as<String>();
|
|
if (!url.isEmpty()) {
|
|
updateServers.push_back(url);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
LOG_DEBUG(TAG, "ConfigManager - Loaded %d update servers from SD card", updateServers.size());
|
|
return true;
|
|
}
|
|
|
|
std::vector<String> ConfigManager::getUpdateServers() const {
|
|
std::vector<String> servers;
|
|
for (const String& server : updateServers) {
|
|
servers.push_back(server);
|
|
}
|
|
for (const String& url : updateConfig.fallbackServerUrls) {
|
|
if (!url.isEmpty()) servers.push_back(url);
|
|
}
|
|
return servers;
|
|
}
|
|
|
|
void ConfigManager::updateTimeConfig(long gmtOffsetSec, int daylightOffsetSec) {
|
|
timeConfig.gmtOffsetSec = gmtOffsetSec;
|
|
timeConfig.daylightOffsetSec = daylightOffsetSec;
|
|
saveTimeConfig(); // Save time config specifically
|
|
LOG_DEBUG(TAG, "ConfigManager - TimeConfig updated - GMT offset %ld sec, DST offset %d sec",
|
|
gmtOffsetSec, daylightOffsetSec);
|
|
}
|
|
|
|
void ConfigManager::updateNetworkConfig(const String& hostname, bool useStaticIP, IPAddress ip, IPAddress gateway,
|
|
IPAddress subnet, IPAddress dns1, IPAddress dns2) {
|
|
networkConfig.hostname = hostname;
|
|
networkConfig.useStaticIP = useStaticIP;
|
|
networkConfig.ip = ip;
|
|
networkConfig.gateway = gateway;
|
|
networkConfig.subnet = subnet;
|
|
networkConfig.dns1 = dns1;
|
|
networkConfig.dns2 = dns2;
|
|
saveNetworkConfig(); // Save immediately to SD
|
|
LOG_DEBUG(TAG, "ConfigManager - NetworkConfig updated - Hostname: %s, Static IP: %s, IP: %s",
|
|
hostname.c_str(), useStaticIP ? "enabled" : "disabled", ip.toString().c_str());
|
|
}
|
|
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
// NETWORK CONFIGURATION PERSISTENCE
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
|
|
bool ConfigManager::loadNetworkConfig() {
|
|
if (!ensureSDCard()) return false;
|
|
|
|
File file = SD.open("/settings/networkConfig.json", FILE_READ);
|
|
if (!file) {
|
|
LOG_DEBUG(TAG, "ConfigManager - Network config file not found - using auto-generated hostname and DHCP");
|
|
return false;
|
|
}
|
|
|
|
StaticJsonDocument<512> doc;
|
|
DeserializationError error = deserializeJson(doc, file);
|
|
file.close();
|
|
|
|
if (error) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to parse network config from SD: %s", error.c_str());
|
|
return false;
|
|
}
|
|
|
|
// Load hostname if present (overrides auto-generated)
|
|
if (doc.containsKey("hostname")) {
|
|
String customHostname = doc["hostname"].as<String>();
|
|
if (!customHostname.isEmpty()) {
|
|
networkConfig.hostname = customHostname;
|
|
LOG_DEBUG(TAG, "ConfigManager - Custom hostname loaded from SD: %s", customHostname.c_str());
|
|
}
|
|
}
|
|
|
|
// Load static IP configuration
|
|
if (doc.containsKey("useStaticIP")) {
|
|
networkConfig.useStaticIP = doc["useStaticIP"].as<bool>();
|
|
}
|
|
|
|
// Load permanent AP mode setting
|
|
if (doc.containsKey("permanentAPMode")) {
|
|
networkConfig.permanentAPMode = doc["permanentAPMode"].as<bool>();
|
|
LOG_DEBUG(TAG, "ConfigManager - Permanent AP mode: %s", networkConfig.permanentAPMode ? "enabled" : "disabled");
|
|
}
|
|
|
|
if (doc.containsKey("ip")) {
|
|
String ipStr = doc["ip"].as<String>();
|
|
if (!ipStr.isEmpty() && ipStr != "0.0.0.0") {
|
|
networkConfig.ip.fromString(ipStr);
|
|
}
|
|
}
|
|
|
|
if (doc.containsKey("gateway")) {
|
|
String gwStr = doc["gateway"].as<String>();
|
|
if (!gwStr.isEmpty() && gwStr != "0.0.0.0") {
|
|
networkConfig.gateway.fromString(gwStr);
|
|
}
|
|
}
|
|
|
|
if (doc.containsKey("subnet")) {
|
|
String subnetStr = doc["subnet"].as<String>();
|
|
if (!subnetStr.isEmpty() && subnetStr != "0.0.0.0") {
|
|
networkConfig.subnet.fromString(subnetStr);
|
|
}
|
|
}
|
|
|
|
if (doc.containsKey("dns1")) {
|
|
String dns1Str = doc["dns1"].as<String>();
|
|
if (!dns1Str.isEmpty() && dns1Str != "0.0.0.0") {
|
|
networkConfig.dns1.fromString(dns1Str);
|
|
}
|
|
}
|
|
|
|
if (doc.containsKey("dns2")) {
|
|
String dns2Str = doc["dns2"].as<String>();
|
|
if (!dns2Str.isEmpty() && dns2Str != "0.0.0.0") {
|
|
networkConfig.dns2.fromString(dns2Str);
|
|
}
|
|
}
|
|
|
|
LOG_DEBUG(TAG, "ConfigManager - Network config loaded - Hostname: %s, Static IP: %s",
|
|
networkConfig.hostname.c_str(),
|
|
networkConfig.useStaticIP ? "enabled" : "disabled");
|
|
|
|
return true;
|
|
}
|
|
|
|
bool ConfigManager::saveNetworkConfig() {
|
|
#if !HAS_SD_CARD
|
|
return saveNetworkConfigToNVS();
|
|
#endif
|
|
if (!ensureSDCard()) return false;
|
|
|
|
StaticJsonDocument<512> doc;
|
|
|
|
// Save hostname (user can customize)
|
|
doc["hostname"] = networkConfig.hostname;
|
|
|
|
// Save static IP configuration
|
|
doc["useStaticIP"] = networkConfig.useStaticIP;
|
|
doc["ip"] = networkConfig.ip.toString();
|
|
doc["gateway"] = networkConfig.gateway.toString();
|
|
doc["subnet"] = networkConfig.subnet.toString();
|
|
doc["dns1"] = networkConfig.dns1.toString();
|
|
doc["dns2"] = networkConfig.dns2.toString();
|
|
|
|
// Save permanent AP mode setting
|
|
doc["permanentAPMode"] = networkConfig.permanentAPMode;
|
|
|
|
char buffer[512];
|
|
size_t len = serializeJson(doc, buffer, sizeof(buffer));
|
|
|
|
if (len == 0 || len >= sizeof(buffer)) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to serialize network config JSON");
|
|
return false;
|
|
}
|
|
|
|
saveFileToSD("/settings", "networkConfig.json", buffer);
|
|
LOG_DEBUG(TAG, "ConfigManager - Network config saved to SD");
|
|
return true;
|
|
}
|
|
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
// NETWORK CONFIG — NVS STORAGE (Agnus: no SD card)
|
|
// NVS key layout (all strings to keep it simple; IPs stored as dotted strings):
|
|
// nc_host — custom hostname (empty = use auto-generated)
|
|
// nc_static — useStaticIP (u8 bool)
|
|
// nc_ip — static IP string
|
|
// nc_gw — gateway string
|
|
// nc_sn — subnet string
|
|
// nc_dns1 — DNS1 string
|
|
// nc_dns2 — DNS2 string
|
|
// nc_apmode — permanentAPMode (u8 bool)
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
#if !HAS_SD_CARD
|
|
bool ConfigManager::loadNetworkConfigFromNVS() {
|
|
String customHostname = readNVSString("nc_host", "");
|
|
if (!customHostname.isEmpty()) {
|
|
networkConfig.hostname = customHostname;
|
|
}
|
|
networkConfig.useStaticIP = readNVSBool("nc_static", false);
|
|
networkConfig.permanentAPMode = readNVSBool("nc_apmode", false);
|
|
|
|
String ipStr = readNVSString("nc_ip", "");
|
|
if (!ipStr.isEmpty() && ipStr != "0.0.0.0") networkConfig.ip.fromString(ipStr);
|
|
|
|
String gwStr = readNVSString("nc_gw", "");
|
|
if (!gwStr.isEmpty() && gwStr != "0.0.0.0") networkConfig.gateway.fromString(gwStr);
|
|
|
|
String snStr = readNVSString("nc_sn", "");
|
|
if (!snStr.isEmpty() && snStr != "0.0.0.0") networkConfig.subnet.fromString(snStr);
|
|
|
|
String dns1Str = readNVSString("nc_dns1", "");
|
|
if (!dns1Str.isEmpty() && dns1Str != "0.0.0.0") networkConfig.dns1.fromString(dns1Str);
|
|
|
|
String dns2Str = readNVSString("nc_dns2", "");
|
|
if (!dns2Str.isEmpty() && dns2Str != "0.0.0.0") networkConfig.dns2.fromString(dns2Str);
|
|
|
|
LOG_DEBUG(TAG, "ConfigManager - Network config loaded from NVS — hostname: %s, staticIP: %s",
|
|
networkConfig.hostname.c_str(), networkConfig.useStaticIP ? "yes" : "no");
|
|
return true;
|
|
}
|
|
|
|
bool ConfigManager::saveNetworkConfigToNVS() {
|
|
bool ok = true;
|
|
ok &= writeNVSString("nc_host", networkConfig.hostname);
|
|
ok &= writeNVSBool ("nc_static", networkConfig.useStaticIP);
|
|
ok &= writeNVSBool ("nc_apmode", networkConfig.permanentAPMode);
|
|
ok &= writeNVSString("nc_ip", networkConfig.ip.toString());
|
|
ok &= writeNVSString("nc_gw", networkConfig.gateway.toString());
|
|
ok &= writeNVSString("nc_sn", networkConfig.subnet.toString());
|
|
ok &= writeNVSString("nc_dns1", networkConfig.dns1.toString());
|
|
ok &= writeNVSString("nc_dns2", networkConfig.dns2.toString());
|
|
ok &= commitNVS();
|
|
LOG_DEBUG(TAG, "ConfigManager - Network config saved to NVS (%s)", ok ? "ok" : "errors");
|
|
return ok;
|
|
}
|
|
#endif
|
|
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
// TIME CONFIGURATION PERSISTENCE
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
|
|
bool ConfigManager::loadTimeConfig() {
|
|
if (!ensureSDCard()) return false;
|
|
|
|
File file = SD.open("/settings/timeConfig.json", FILE_READ);
|
|
if (!file) {
|
|
LOG_DEBUG(TAG, "ConfigManager - Time config file not found - using defaults (GMT+2)");
|
|
return false;
|
|
}
|
|
|
|
StaticJsonDocument<256> doc;
|
|
DeserializationError error = deserializeJson(doc, file);
|
|
file.close();
|
|
|
|
if (error) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to parse time config from SD: %s", error.c_str());
|
|
return false;
|
|
}
|
|
|
|
// Load NTP server if present
|
|
if (doc.containsKey("ntpServer")) {
|
|
String ntpServer = doc["ntpServer"].as<String>();
|
|
if (!ntpServer.isEmpty()) {
|
|
timeConfig.ntpServer = ntpServer;
|
|
}
|
|
}
|
|
|
|
// Load GMT offset
|
|
if (doc.containsKey("gmtOffsetSec")) {
|
|
timeConfig.gmtOffsetSec = doc["gmtOffsetSec"].as<long>();
|
|
}
|
|
|
|
// Load daylight saving offset
|
|
if (doc.containsKey("daylightOffsetSec")) {
|
|
timeConfig.daylightOffsetSec = doc["daylightOffsetSec"].as<int>();
|
|
}
|
|
|
|
LOG_DEBUG(TAG, "ConfigManager - Time config loaded - NTP: %s, GMT offset: %ld, DST offset: %d",
|
|
timeConfig.ntpServer.c_str(),
|
|
timeConfig.gmtOffsetSec,
|
|
timeConfig.daylightOffsetSec);
|
|
|
|
return true;
|
|
}
|
|
|
|
bool ConfigManager::saveTimeConfig() {
|
|
if (!ensureSDCard()) return false;
|
|
|
|
StaticJsonDocument<256> doc;
|
|
|
|
// Save NTP server
|
|
doc["ntpServer"] = timeConfig.ntpServer;
|
|
|
|
// Save timezone offsets
|
|
doc["gmtOffsetSec"] = timeConfig.gmtOffsetSec;
|
|
doc["daylightOffsetSec"] = timeConfig.daylightOffsetSec;
|
|
|
|
char buffer[256];
|
|
size_t len = serializeJson(doc, buffer, sizeof(buffer));
|
|
|
|
if (len == 0 || len >= sizeof(buffer)) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to serialize time config JSON");
|
|
return false;
|
|
}
|
|
|
|
saveFileToSD("/settings", "timeConfig.json", buffer);
|
|
LOG_DEBUG(TAG, "ConfigManager - Time config saved to SD");
|
|
return true;
|
|
}
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
// SETTINGS RESET IMPLEMENTATION
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
|
|
bool ConfigManager::resetAllToDefaults() {
|
|
|
|
LOG_INFO(TAG, "═══════════════════════════════════════════════════════════════════════════");
|
|
LOG_INFO(TAG, " 🏭 RESET SETTINGS TO DEFAULTS INITIATED");
|
|
LOG_INFO(TAG, "═══════════════════════════════════════════════════════════════════════════");
|
|
|
|
if (!ensureSDCard()) {
|
|
return false;
|
|
}
|
|
|
|
bool allDeleted = true;
|
|
int filesDeleted = 0;
|
|
int filesFailed = 0;
|
|
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
// STEP 1: Delete all configuration files
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
|
|
const char* settingsFiles[] = {
|
|
"/settings/deviceConfig.json",
|
|
"/settings/networkConfig.json",
|
|
"/settings/timeConfig.json",
|
|
"/settings/relayTimings.json",
|
|
"/settings/bellOutputs.json",
|
|
"/settings/clockConfig.json",
|
|
"/settings/clockState.json",
|
|
"/settings/updateServers.json"
|
|
};
|
|
|
|
int numFiles = sizeof(settingsFiles) / sizeof(settingsFiles[0]);
|
|
|
|
LOG_DEBUG(TAG, "ConfigManager - Step 1: Deleting %d configuration files...", numFiles);
|
|
|
|
for (int i = 0; i < numFiles; i++) {
|
|
const char* filepath = settingsFiles[i];
|
|
|
|
if (SD.exists(filepath)) {
|
|
if (SD.remove(filepath)) {
|
|
LOG_DEBUG(TAG, "ConfigManager - Deleted: %s", filepath);
|
|
filesDeleted++;
|
|
} else {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to delete: %s", filepath);
|
|
filesFailed++;
|
|
allDeleted = false;
|
|
}
|
|
} else {
|
|
LOG_DEBUG(TAG, "ConfigManager - Skip (not found): %s", filepath);
|
|
}
|
|
}
|
|
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
// STEP 2: Delete all melodies recursively
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
|
|
if (SD.exists("/melodies")) {
|
|
LOG_DEBUG(TAG, "ConfigManager - Step 2: Deleting melody files...");
|
|
|
|
File melodiesDir = SD.open("/melodies");
|
|
if (melodiesDir && melodiesDir.isDirectory()) {
|
|
int melodiesDeleted = 0;
|
|
int melodiesFailed = 0;
|
|
|
|
File entry = melodiesDir.openNextFile();
|
|
while (entry) {
|
|
String entryPath = String("/melodies/") + entry.name();
|
|
|
|
if (!entry.isDirectory()) {
|
|
if (SD.remove(entryPath.c_str())) {
|
|
LOG_DEBUG(TAG, "ConfigManager - Deleted melody: %s", entryPath.c_str());
|
|
melodiesDeleted++;
|
|
} else {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to delete melody: %s", entryPath.c_str());
|
|
melodiesFailed++;
|
|
allDeleted = false;
|
|
}
|
|
}
|
|
|
|
entry.close();
|
|
entry = melodiesDir.openNextFile();
|
|
}
|
|
|
|
melodiesDir.close();
|
|
|
|
// Try to remove the empty directory
|
|
if (SD.rmdir("/melodies")) {
|
|
LOG_DEBUG(TAG, "ConfigManager - Deleted /melodies directory");
|
|
} else {
|
|
LOG_WARNING(TAG, "ConfigManager - ⚠️ Could not delete /melodies directory (may not be empty)");
|
|
}
|
|
|
|
LOG_DEBUG(TAG, "ConfigManager - Melodies deleted: %d, failed: %d", melodiesDeleted, melodiesFailed);
|
|
filesDeleted += melodiesDeleted;
|
|
filesFailed += melodiesFailed;
|
|
}
|
|
} else {
|
|
LOG_DEBUG(TAG, "ConfigManager - /melodies directory not found");
|
|
}
|
|
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
// SUMMARY
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
|
|
LOG_INFO(TAG, "═══════════════════════════════════════════════════════════════════════════");
|
|
LOG_INFO(TAG, "ConfigManager - Full reset summary:");
|
|
LOG_INFO(TAG, "ConfigManager - ✅ Files deleted: %d", filesDeleted);
|
|
LOG_INFO(TAG, "ConfigManager - ❌ Files failed: %d", filesFailed);
|
|
LOG_INFO(TAG, "ConfigManager - 🔄 Total processed: %d", filesDeleted + filesFailed);
|
|
LOG_INFO(TAG, "═══════════════════════════════════════════════════════════════════════════");
|
|
|
|
LOG_INFO(TAG, "ConfigManager - ✅ RESET TO DEFAULT COMPLETE");
|
|
LOG_INFO(TAG, "ConfigManager - 🔄 Device will boot with default settings on next restart");
|
|
LOG_INFO(TAG, "ConfigManager - 🆔 Device identity (UID) preserved");
|
|
|
|
return allDeleted;
|
|
}
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
// GET ALL SETTINGS AS JSON
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
|
|
String ConfigManager::getAllSettingsAsJson() const {
|
|
// Use a large document to hold everything
|
|
DynamicJsonDocument doc(4096);
|
|
|
|
// Device info
|
|
JsonObject device = doc.createNestedObject("device");
|
|
device["serial"] = deviceConfig.serial;
|
|
device["hw_family"] = deviceConfig.hwFamily;
|
|
device["hw_revision"] = deviceConfig.hwRevision;
|
|
device["fwVersion"] = FW_VERSION;
|
|
|
|
// Network config
|
|
JsonObject network = doc.createNestedObject("network");
|
|
network["hostname"] = networkConfig.hostname;
|
|
network["useStaticIP"] = networkConfig.useStaticIP;
|
|
network["ip"] = networkConfig.ip.toString();
|
|
network["gateway"] = networkConfig.gateway.toString();
|
|
network["subnet"] = networkConfig.subnet.toString();
|
|
network["dns1"] = networkConfig.dns1.toString();
|
|
network["dns2"] = networkConfig.dns2.toString();
|
|
|
|
// Time config
|
|
JsonObject time = doc.createNestedObject("time");
|
|
time["ntpServer"] = timeConfig.ntpServer;
|
|
time["gmtOffsetSec"] = timeConfig.gmtOffsetSec;
|
|
time["daylightOffsetSec"] = timeConfig.daylightOffsetSec;
|
|
|
|
// Bell durations (relay timings)
|
|
JsonObject bellDurations = doc.createNestedObject("bellDurations");
|
|
for (uint8_t i = 0; i < 16; i++) {
|
|
String key = String("b") + (i + 1);
|
|
bellDurations[key] = bellConfig.durations[i];
|
|
}
|
|
|
|
// Bell outputs (physical output mapping)
|
|
JsonObject bellOutputs = doc.createNestedObject("bellOutputs");
|
|
for (uint8_t i = 0; i < 16; i++) {
|
|
String key = String("b") + (i + 1);
|
|
bellOutputs[key] = bellConfig.outputs[i];
|
|
}
|
|
|
|
// Clock configuration
|
|
JsonObject clock = doc.createNestedObject("clock");
|
|
clock["enabled"] = clockConfig.enabled;
|
|
clock["c1output"] = clockConfig.c1output;
|
|
clock["c2output"] = clockConfig.c2output;
|
|
clock["pulseDuration"] = clockConfig.pulseDuration;
|
|
clock["pauseDuration"] = clockConfig.pauseDuration;
|
|
|
|
// Clock state
|
|
JsonObject clockState = doc.createNestedObject("clockState");
|
|
clockState["physicalHour"] = clockConfig.physicalHour;
|
|
clockState["physicalMinute"] = clockConfig.physicalMinute;
|
|
clockState["nextOutputIsC1"] = clockConfig.nextOutputIsC1;
|
|
clockState["lastSyncTime"] = clockConfig.lastSyncTime;
|
|
|
|
// Clock alerts
|
|
JsonObject alerts = doc.createNestedObject("alerts");
|
|
alerts["alertType"] = clockConfig.alertType;
|
|
alerts["alertRingInterval"] = clockConfig.alertRingInterval;
|
|
alerts["hourBell"] = clockConfig.hourBell;
|
|
alerts["halfBell"] = clockConfig.halfBell;
|
|
alerts["quarterBell"] = clockConfig.quarterBell;
|
|
|
|
// Clock backlight
|
|
JsonObject backlight = doc.createNestedObject("backlight");
|
|
backlight["enabled"] = clockConfig.backlight;
|
|
backlight["output"] = clockConfig.backlightOutput;
|
|
backlight["onTime"] = clockConfig.backlightOnTime;
|
|
backlight["offTime"] = clockConfig.backlightOffTime;
|
|
|
|
// Silence periods
|
|
JsonObject silence = doc.createNestedObject("silence");
|
|
JsonObject daytime = silence.createNestedObject("daytime");
|
|
daytime["enabled"] = clockConfig.daytimeSilenceEnabled;
|
|
daytime["onTime"] = clockConfig.daytimeSilenceOnTime;
|
|
daytime["offTime"] = clockConfig.daytimeSilenceOffTime;
|
|
JsonObject nighttime = silence.createNestedObject("nighttime");
|
|
nighttime["enabled"] = clockConfig.nighttimeSilenceEnabled;
|
|
nighttime["onTime"] = clockConfig.nighttimeSilenceOnTime;
|
|
nighttime["offTime"] = clockConfig.nighttimeSilenceOffTime;
|
|
|
|
// Serialize to string
|
|
String output;
|
|
serializeJson(doc, output);
|
|
return output;
|
|
}
|
|
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
// GENERAL CONFIGURATION - LOG LEVELS
|
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
|
|
bool ConfigManager::setSerialLogLevel(uint8_t level) {
|
|
if (level > 5) { // Max level is VERBOSE (5)
|
|
LOG_WARNING(TAG, "ConfigManager - ⚠️ Invalid serial log level %d, valid range is 0-5", level);
|
|
return false;
|
|
}
|
|
generalConfig.serialLogLevel = level;
|
|
LOG_DEBUG(TAG, "ConfigManager - Serial log level set to %d", level);
|
|
return true;
|
|
}
|
|
|
|
bool ConfigManager::setSdLogLevel(uint8_t level) {
|
|
if (level > 5) { // Max level is VERBOSE (5)
|
|
LOG_WARNING(TAG, "ConfigManager - ⚠️ Invalid SD log level %d, valid range is 0-5", level);
|
|
return false;
|
|
}
|
|
generalConfig.sdLogLevel = level;
|
|
LOG_DEBUG(TAG, "ConfigManager - SD log level set to %d", level);
|
|
return true;
|
|
}
|
|
|
|
bool ConfigManager::setMqttLogLevel(uint8_t level) {
|
|
if (level > 5) { // Max level is VERBOSE (5)
|
|
LOG_WARNING(TAG, "ConfigManager - ⚠️ Invalid MQTT log level %d, valid range is 0-5", level);
|
|
return false;
|
|
}
|
|
generalConfig.mqttLogLevel = level;
|
|
LOG_DEBUG(TAG, "ConfigManager - MQTT log level set to %d", level);
|
|
return true;
|
|
}
|
|
|
|
bool ConfigManager::loadGeneralConfig() {
|
|
if (!ensureSDCard()) return false;
|
|
|
|
File file = SD.open("/settings/generalConfig.json", FILE_READ);
|
|
if (!file) {
|
|
LOG_WARNING(TAG, "ConfigManager - ⚠️ General config file not found - using defaults");
|
|
return false;
|
|
}
|
|
|
|
StaticJsonDocument<256> doc;
|
|
DeserializationError error = deserializeJson(doc, file);
|
|
file.close();
|
|
|
|
if (error) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to parse general config from SD: %s", error.c_str());
|
|
return false;
|
|
}
|
|
|
|
if (doc.containsKey("serialLogLevel")) {
|
|
generalConfig.serialLogLevel = doc["serialLogLevel"].as<uint8_t>();
|
|
}
|
|
if (doc.containsKey("sdLogLevel")) {
|
|
generalConfig.sdLogLevel = doc["sdLogLevel"].as<uint8_t>();
|
|
}
|
|
if (doc.containsKey("mqttLogLevel")) {
|
|
generalConfig.mqttLogLevel = doc["mqttLogLevel"].as<uint8_t>();
|
|
}
|
|
if (doc.containsKey("mqttEnabled")) {
|
|
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, OTA channel: %s",
|
|
generalConfig.serialLogLevel, generalConfig.sdLogLevel, generalConfig.mqttLogLevel,
|
|
generalConfig.mqttEnabled ? "true" : "false", generalConfig.otaChannel.c_str());
|
|
return true;
|
|
}
|
|
|
|
bool ConfigManager::saveGeneralConfig() {
|
|
#if !HAS_SD_CARD
|
|
return saveGeneralConfigToNVS();
|
|
#endif
|
|
if (!ensureSDCard()) return false;
|
|
|
|
StaticJsonDocument<256> doc;
|
|
doc["serialLogLevel"] = generalConfig.serialLogLevel;
|
|
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));
|
|
|
|
if (len == 0 || len >= sizeof(buffer)) {
|
|
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to serialize general config JSON");
|
|
return false;
|
|
}
|
|
|
|
saveFileToSD("/settings", "generalConfig.json", buffer);
|
|
LOG_DEBUG(TAG, "ConfigManager - General config saved (MQTT enabled: %s)", generalConfig.mqttEnabled ? "true" : "false");
|
|
return true;
|
|
}
|
|
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
// GENERAL CONFIG — NVS STORAGE (Agnus: no SD card)
|
|
// NVS key layout:
|
|
// gc_slog — serialLogLevel (u8)
|
|
// gc_mlog — mqttLogLevel (u8)
|
|
// gc_mqtt — mqttEnabled (u8 bool)
|
|
// gc_ota — otaChannel (str)
|
|
// Note: sdLogLevel omitted — no SD card on Agnus.
|
|
// ════════════════════════════════════════════════════════════════════════════
|
|
#if !HAS_SD_CARD
|
|
bool ConfigManager::loadGeneralConfigFromNVS() {
|
|
generalConfig.serialLogLevel = readNVSU8 ("gc_slog", generalConfig.serialLogLevel);
|
|
generalConfig.mqttLogLevel = readNVSU8 ("gc_mlog", generalConfig.mqttLogLevel);
|
|
generalConfig.mqttEnabled = readNVSBool ("gc_mqtt", generalConfig.mqttEnabled);
|
|
generalConfig.otaChannel = readNVSString("gc_ota", generalConfig.otaChannel);
|
|
mqttConfig.enabled = generalConfig.mqttEnabled;
|
|
LOG_DEBUG(TAG, "ConfigManager - General config loaded from NVS — serialLog: %d, mqttEnabled: %s, otaCh: %s",
|
|
generalConfig.serialLogLevel, generalConfig.mqttEnabled ? "true" : "false",
|
|
generalConfig.otaChannel.c_str());
|
|
return true;
|
|
}
|
|
|
|
bool ConfigManager::saveGeneralConfigToNVS() {
|
|
bool ok = true;
|
|
ok &= writeNVSU8 ("gc_slog", generalConfig.serialLogLevel);
|
|
ok &= writeNVSU8 ("gc_mlog", generalConfig.mqttLogLevel);
|
|
ok &= writeNVSBool ("gc_mqtt", generalConfig.mqttEnabled);
|
|
ok &= writeNVSString("gc_ota", generalConfig.otaChannel);
|
|
ok &= commitNVS();
|
|
LOG_DEBUG(TAG, "ConfigManager - General config saved to NVS (%s)", ok ? "ok" : "errors");
|
|
return ok;
|
|
}
|
|
#endif
|
|
|
|
// =============================================================================
|
|
// HMAC-SHA256 MQTT password derivation
|
|
// Password = HMAC-SHA256(MQTT_SECRET, deviceUID), first 16 bytes as hex (32 chars)
|
|
// Matches backend: hmac.new(secret, uid, sha256).hexdigest()[:32]
|
|
// MQTT_SECRET is injected at compile time via -DMQTT_SECRET="..." in platformio.ini
|
|
// =============================================================================
|
|
String ConfigManager::computeMqttPassword(const String& uid) {
|
|
const char* secret = MQTT_SECRET;
|
|
const uint8_t* key = (const uint8_t*)secret;
|
|
size_t keyLen = strlen(secret);
|
|
|
|
const uint8_t* msg = (const uint8_t*)uid.c_str();
|
|
size_t msgLen = uid.length();
|
|
|
|
uint8_t hmacResult[32]; // SHA-256 produces 32 bytes
|
|
|
|
mbedtls_md_context_t ctx;
|
|
const mbedtls_md_info_t* info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
|
|
|
|
mbedtls_md_init(&ctx);
|
|
mbedtls_md_setup(&ctx, info, 1); // 1 = HMAC mode
|
|
mbedtls_md_hmac_starts(&ctx, key, keyLen);
|
|
mbedtls_md_hmac_update(&ctx, msg, msgLen);
|
|
mbedtls_md_hmac_finish(&ctx, hmacResult);
|
|
mbedtls_md_free(&ctx);
|
|
|
|
// Convert first 16 bytes (32 hex chars) — matches backend [:32]
|
|
char hexStr[33];
|
|
for (int i = 0; i < 16; i++) {
|
|
snprintf(&hexStr[i * 2], 3, "%02x", hmacResult[i]);
|
|
}
|
|
hexStr[32] = '\0';
|
|
|
|
return String(hexStr);
|
|
}
|