/* * ═══════════════════════════════════════════════════════════════════════════════════ * CONFIGMANAGER.HPP - Deployment-Ready Configuration Management System * ═══════════════════════════════════════════════════════════════════════════════════ * * 🗂️ CLEAN DEPLOYMENT-READY CONFIG SYSTEM 🗂️ * * This restructured configuration system is designed for production deployment * with minimal hardcoded defaults, proper separation of factory vs user settings, * and clean configuration hierarchy. * * 🏗️ DEPLOYMENT PHILOSOPHY: * • Factory settings stored in NVS (permanent, set once) * • User settings stored on SD card (configurable via app) * • Hardware settings compiled per HWID variant * • Network credentials handled by WiFiManager only * • Auto-generated identifiers where appropriate * * ═══════════════════════════════════════════════════════════════════════════════════ */ #pragma once #include #include #include #include #include #include #include #include "../Version.hpp" class ConfigManager { public: // ═══════════════════════════════════════════════════════════════════════════════ // CONFIGURATION STRUCTURES - Clean deployment-ready design // ═══════════════════════════════════════════════════════════════════════════════ /** * @struct DeviceConfig * @brief Factory-set device identity (NVS storage) * * These values are set once during manufacturing and stored in NVS. * fwVersion is NOT stored — it is always read from the compiled FW_VERSION constant. */ struct DeviceConfig { 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" }; /** * @struct NetworkConfig * @brief Network connectivity settings * * WiFi credentials are handled entirely by WiFiManager. * Static IP settings are configured via app commands and stored on SD. * hostname is auto-generated from deviceUID. */ struct NetworkConfig { String hostname; // 🏭 Auto-generated: "BellSystems-" bool useStaticIP = false; // 🔧 Default DHCP, app-configurable via SD IPAddress ip; // 🏠 Empty default, read from SD IPAddress gateway; // 🌐 Empty default, read from SD IPAddress subnet; // 📊 Empty default, read from SD IPAddress dns1; // 📝 Empty default, read from SD IPAddress dns2; // 📝 Empty default, read from SD String apSsid; // 📡 Auto-generated AP name String apPass; // 🔐 AP is Open. No Password uint16_t discoveryPort = 32101; // 📡 Fixed discovery port bool permanentAPMode = false; // 🔘 Permanent AP mode toggle (stored on SD) String defaultWifiSsid = "BellSystemsInfra"; // 📡 Default WiFi SSID to try on boot String defaultWifiPsk = "v3sp3r_8998!"; // 🔐 Default WiFi password to try on boot }; /** * @struct MqttConfig * @brief MQTT broker connection settings * * Default configured for local Mosquitto broker. * Username defaults to deviceUID for unique identification. */ struct MqttConfig { IPAddress host = IPAddress(72,61,191,197); // 📡 MQTT broker (default cloud broker) int port = 1883; // 🔌 Standard MQTT port (non-SSL) String user; // 👤 Auto-set to deviceUID String password; // 🔑 Derived at runtime via computeMqttPassword() bool useSSL = false; // 🔒 SSL disabled for local broker bool enabled = true; // 🔘 MQTT enabled by default (can be toggled via command) }; /** * @struct MqttTopicConfig * @brief Per-topic ON/OFF switches for MQTT v2 publishing (loaded from SD/NVS) * * These only take effect while MqttConfig::enabled (the master switch) is * true — turning the master off stops everything regardless of these flags. * While the master is on, each flag independently gates whether its topic * publishes at all, so a device can "breathe" by disabling topics it * doesn't need (e.g. a fleet-only install with no phone app can turn off * control/command + control/ack entirely). * * `command` gates BOTH control/command (inbound subscribe) and control/ack * (outbound reply) together — see docs/reference/vesper_mqtt_topic_spec_v2.md. */ struct MqttTopicConfig { bool command = true; // control/command (subscribe) + control/ack (reply) bool heartbeat = true; // status/heartbeat bool playback = true; // status/playback bool reports = true; // control/reports (bell overload etc. — critical, unsolicited) bool alerts = true; // system/alerts bool info = true; // system/info bool logs = true; // system/logs (also gated by log.set_mqtt level — see Logging) bool metrics = true; // system/metrics }; /** * @struct HardwareConfig * @brief Hardware-specific settings (compiled per HWID) * * These values are hardware-variant specific and compiled into firmware. * Different values for different hardware revisions. */ struct HardwareConfig { uint8_t pcf8574Address = 0x24; // 🔌 Hardware-specific - OK as is uint8_t sdChipSelect = 5; // 💾 Hardware-specific - OK as is // Ethernet SPI configuration - hardware-specific uint8_t ethSpiSck = 18; // ⏱️ Hardware-specific - OK as is uint8_t ethSpiMiso = 19; // 🔄 Hardware-specific - OK as is uint8_t ethSpiMosi = 23; // 🔄 Hardware-specific - OK as is // ETH PHY Configuration - ETHERNET DISABLED (kept for legacy/future use) uint8_t ethPhyType = 9; // was ETH_PHY_W5500 (9) — Ethernet removed in v138 uint8_t ethPhyAddr = 1; // 📍 Hardware-specific - OK as is uint8_t ethPhyCs = 5; // 💾 Hardware-specific - OK as is int8_t ethPhyIrq = -1; // ⚡ Hardware-specific - OK as is int8_t ethPhyRst = -1; // 🔄 Hardware-specific - OK as is }; /** * @struct TimeConfig * @brief Timezone and NTP settings * * NTP server is universal default. * Timezone offsets default to 0 (UTC) and are configured via app. */ struct TimeConfig { String ntpServer = "pool.ntp.org"; // ⏰ Universal NTP - OK as is long gmtOffsetSec = 7200; // 🌍 Default GMT+2 (Greek Time), app-configurable via SD int daylightOffsetSec = 0; // ☀️ Default no DST, app-configurable via SD }; /** * @struct UpdateConfig * @brief OTA update server configuration * * Universal defaults for all devices. */ struct UpdateConfig { String fallbackServerUrls[2] = { "http://firmware.bellsystems.net", // 🥇 Primary fallback "http://firmware.bonamin.space" // 🥈 Secondary fallback }; int timeout = 10000; // ⏱️ Universal timeout - OK as is int retries = 3; // 🔄 Universal retries - OK as is }; /** * @struct BellConfig * @brief Bell system configuration (loaded from SD) * * All bell settings are loaded from SD card at startup. */ struct BellConfig { uint16_t durations[16]; // ⏱️ Loaded from SD at startup Factory Def: Min Size Hammer uint16_t outputs[16]; // 🔌 Loaded from SD at startup. Factory Def: Disabled }; /** * @struct ClockConfig * @brief Clock mechanism configuration (loaded from SD) * * All clock settings are loaded from SD card at startup. * This struct is correctly designed and needs no changes. */ struct ClockConfig { // ════════════════════════════════════════════════════════════════════════════ // CLOCK ENABLE/DISABLE - Master control for all clock functionality // ════════════════════════════════════════════════════════════════════════════ bool enabled = false; // 🔘 Enable/disable ALL clock functionality // ════════════════════════════════════════════════════════════════════════════ // CLOCK OUTPUTS - Physical output configuration // ════════════════════════════════════════════════════════════════════════════ uint8_t c1output = 255; // 🕐 Clock output #1 pin (255 = disabled) uint8_t c2output = 255; // 🕑 Clock output #2 pin (255 = disabled) uint16_t pulseDuration = 5000; // ⏱️ Pulse duration in milliseconds uint16_t pauseDuration = 2000; // 🛑 Pause between consecutive pulses // ════════════════════════════════════════════════════════════════════════════ // PHYSICAL CLOCK STATE - Position tracking for sync // ════════════════════════════════════════════════════════════════════════════ uint8_t physicalHour = 0; // 🕐 Physical clock hour (0-11) uint8_t physicalMinute = 0; // 🕐 Physical clock minute (0-59) bool nextOutputIsC1 = true; // 🔄 Which output fires next uint32_t lastSyncTime = 0; // ⏰ Last successful sync timestamp // ════════════════════════════════════════════════════════════════════════════ // ALERT CONFIGURATION - Bell alert behavior // ════════════════════════════════════════════════════════════════════════════ String alertType = "OFF"; // 🔔 Alert mode: "SINGLE", "HOURS", or "OFF" uint16_t alertRingInterval = 1200; // ⏰ Interval between bell rings (ms) 1-2s 0.2s steps uint8_t hourBell = 255; // 🕐 Bell for hourly alerts (255 = disabled) uint8_t halfBell = 255; // 🕕 Bell for half-hour alerts (255 = disabled) uint8_t quarterBell = 255; // 🕒 Bell for quarter-hour alerts (255 = disabled) // ════════════════════════════════════════════════════════════════════════════ // BACKLIGHT AUTOMATION - Clock illumination control // ════════════════════════════════════════════════════════════════════════════ bool backlight = false; // 💡 Enable/disable backlight automation uint8_t backlightOutput = 255; // 🔌 Backlight output pin (255 = disabled) String backlightOnTime = "18:00"; // 🌅 Time to turn backlight ON String backlightOffTime = "06:00"; // 🌄 Time to turn backlight OFF // ════════════════════════════════════════════════════════════════════════════ // SILENCE PERIODS - Quiet hours configuration // ════════════════════════════════════════════════════════════════════════════ bool daytimeSilenceEnabled = false; // 🌞 Enable/disable daytime silence String daytimeSilenceOnTime = "14:00"; // 🌞 Start of daytime silence String daytimeSilenceOffTime = "17:00"; // 🌞 End of daytime silence bool nighttimeSilenceEnabled = false; // 🌙 Enable/disable nighttime silence String nighttimeSilenceOnTime = "22:00"; // 🌙 Start of nighttime silence String nighttimeSilenceOffTime = "07:00"; // 🌙 End of nighttime silence }; /** * @struct General Config * @brief General configuration (loaded from SD) * * All clock settings are loaded from SD card at startup. */ struct GeneralConfig { uint8_t serialLogLevel = 3; // INFO uint8_t sdLogLevel = 2; // WARNING uint8_t mqttLogLevel = 2; // WARNING bool mqttEnabled = true; // MQTT enabled by default (master switch) bool bellsEnabled = true; // Master bell mechanism ON/OFF (blocks playback + clock alerts) String otaChannel = "stable"; // OTA release channel: "stable" | "beta" | "development" MqttTopicConfig mqttTopics; // Per-topic MQTT publish switches (only apply while mqttEnabled) }; private: // ═══════════════════════════════════════════════════════════════════════════════ // MEMBER VARIABLES - Clean deployment-ready storage // ═══════════════════════════════════════════════════════════════════════════════ DeviceConfig deviceConfig; NetworkConfig networkConfig; MqttConfig mqttConfig; HardwareConfig hardwareConfig; TimeConfig timeConfig; UpdateConfig updateConfig; BellConfig bellConfig; ClockConfig clockConfig; GeneralConfig generalConfig; bool sdInitialized = false; std::vector updateServers; nvs_handle_t nvsHandle = 0; static const char* NVS_NAMESPACE; // ═══════════════════════════════════════════════════════════════════════════════ // PRIVATE METHODS - Clean initialization and auto-generation // ═══════════════════════════════════════════════════════════════════════════════ /** * @brief Initialize configuration with clean defaults and auto-generation * * This method: * 1. Loads device identity from NVS (factory-set) * 2. Auto-generates hostname from deviceUID * 3. Auto-generates AP SSID from deviceUID * 4. Sets MQTT username to deviceUID * 5. Loads user-configurable settings from SD */ void initializeCleanDefaults(); /** * @brief Auto-generate network identifiers from deviceUID * * Generates: * - hostname: "BellSystems-" * - apSsid: "BellSystems-Setup-" * - mqttUser: deviceUID */ void generateNetworkIdentifiers(); bool ensureSDCard(); void createDefaultBellConfig(); // NVS management bool initializeNVS(); bool loadDeviceIdentityFromNVS(); String readNVSString(const char* key, const String& defaultValue); uint8_t readNVSU8(const char* key, uint8_t defaultValue); uint16_t readNVSU16(const char* key, uint16_t defaultValue); bool readNVSBool(const char* key, bool defaultValue); // NVS write helpers — used by Agnus (no SD card) to persist user config bool writeNVSString(const char* key, const String& value); bool writeNVSU8(const char* key, uint8_t value); bool writeNVSU16(const char* key, uint16_t value); bool writeNVSBool(const char* key, bool value); bool commitNVS(); String computeMqttPassword(const String& uid); public: // ═══════════════════════════════════════════════════════════════════════════════ // PUBLIC INTERFACE - Clean deployment-ready API // ═══════════════════════════════════════════════════════════════════════════════ ConfigManager(); /** * @brief Initialize clean deployment-ready configuration system * * Load order: * 1. Device identity from NVS (factory-set, permanent) * 2. Auto-generate network identifiers * 3. Load user settings from SD card * 4. Apply clean defaults for missing settings */ bool begin(); bool saveToSD(); // Configuration access (read-only getters) const DeviceConfig& getDeviceConfig() const { return deviceConfig; } const NetworkConfig& getNetworkConfig() const { return networkConfig; } const MqttConfig& getMqttConfig() const { return mqttConfig; } const HardwareConfig& getHardwareConfig() const { return hardwareConfig; } const TimeConfig& getTimeConfig() const { return timeConfig; } const UpdateConfig& getUpdateConfig() const { return updateConfig; } const BellConfig& getBellConfig() const { return bellConfig; } const ClockConfig& getClockConfig() const { return clockConfig; } const GeneralConfig& getGeneralConfig() const { return generalConfig; } // Device identity getters — factory-set via separate factory firmware, loaded // ONCE at boot from NVS and kept in RAM. Not writable through normal config // flows; the only write path is saveDeviceIdentityToNVS() below, reserved for // the sysadmin-only system.set_identity command. 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. void setFwVersion(const String&) {} // Sysadmin override: overwrites factory-set device identity in NVS and in RAM. // Gated to the system.set_identity command (MQTT-only). Caller is responsible // for updating the backend device record to match — this call does not. bool saveDeviceIdentityToNVS(const String& serial, const String& hwFamily, const String& hwRevision); // Configuration update methods for app commands void updateTimeConfig(long gmtOffsetSec, int daylightOffsetSec); void updateNetworkConfig(const String& hostname, bool useStaticIP, IPAddress ip, IPAddress gateway, IPAddress subnet, IPAddress dns1, IPAddress dns2); // AP Mode configuration bool getPermanentAPMode() const { return networkConfig.permanentAPMode; } void setPermanentAPMode(bool enabled) { networkConfig.permanentAPMode = enabled; } // Network configuration persistence bool loadNetworkConfig(); bool saveNetworkConfig(); #if !HAS_SD_CARD bool loadNetworkConfigFromNVS(); bool saveNetworkConfigToNVS(); #endif // Time configuration persistence bool loadTimeConfig(); bool saveTimeConfig(); // Bell and clock configuration methods bool loadBellDurations(); bool saveBellDurations(); bool loadBellOutputs(); bool saveBellOutputs(); #if !HAS_SD_CARD bool loadBellConfigFromNVS(); bool saveBellConfigToNVS(); #endif void updateBellDurations(JsonVariant doc); void updateBellOutputs(JsonVariant doc); uint16_t getBellDuration(uint8_t bellIndex) const; uint16_t getBellOutput(uint8_t bellIndex) const; void setBellDuration(uint8_t bellIndex, uint16_t duration); void setBellOutput(uint8_t bellIndex, uint16_t output); // Clock configuration methods (unchanged - already correct) bool getClockEnabled() const { return clockConfig.enabled; } void setClockEnabled(bool enabled) { clockConfig.enabled = enabled; } void updateClockOutputs(JsonVariant doc); uint8_t getClockOutput1() const { return clockConfig.c1output; } uint8_t getClockOutput2() const { return clockConfig.c2output; } uint16_t getClockPulseDuration() const { return clockConfig.pulseDuration; } uint16_t getClockPauseDuration() const { return clockConfig.pauseDuration; } void setClockOutput1(uint8_t output) { clockConfig.c1output = output; } void setClockOutput2(uint8_t output) { clockConfig.c2output = output; } void setClockPulseDuration(uint16_t duration) { clockConfig.pulseDuration = duration; } void setClockPauseDuration(uint16_t duration) { clockConfig.pauseDuration = duration; } // Physical clock state methods (unchanged) uint8_t getPhysicalClockHour() const { return clockConfig.physicalHour; } uint8_t getPhysicalClockMinute() const { return clockConfig.physicalMinute; } bool getNextOutputIsC1() const { return clockConfig.nextOutputIsC1; } uint32_t getLastSyncTime() const { return clockConfig.lastSyncTime; } void setPhysicalClockHour(uint8_t hour) { clockConfig.physicalHour = (hour % 12 == 0) ? 12 : hour % 12; } void setPhysicalClockMinute(uint8_t minute) { clockConfig.physicalMinute = minute % 60; } void setNextOutputIsC1(bool isC1) { clockConfig.nextOutputIsC1 = isC1; } void setLastSyncTime(uint32_t timestamp) { clockConfig.lastSyncTime = timestamp; } // Alert configuration methods (unchanged) String getAlertType() const { return clockConfig.alertType; } uint16_t getAlertRingInterval() const { return clockConfig.alertRingInterval; } uint8_t getHourBell() const { return clockConfig.hourBell; } uint8_t getHalfBell() const { return clockConfig.halfBell; } uint8_t getQuarterBell() const { return clockConfig.quarterBell; } void setAlertType(const String& type) { clockConfig.alertType = type; } void setAlertRingInterval(uint16_t interval) { clockConfig.alertRingInterval = interval; } void setHourBell(uint8_t bell) { clockConfig.hourBell = bell; } void setHalfBell(uint8_t bell) { clockConfig.halfBell = bell; } void setQuarterBell(uint8_t bell) { clockConfig.quarterBell = bell; } // Backlight configuration methods (unchanged) bool getBacklightEnabled() const { return clockConfig.backlight; } uint8_t getBacklightOutput() const { return clockConfig.backlightOutput; } String getBacklightOnTime() const { return clockConfig.backlightOnTime; } String getBacklightOffTime() const { return clockConfig.backlightOffTime; } void setBacklightEnabled(bool enabled) { clockConfig.backlight = enabled; } void setBacklightOutput(uint8_t output) { clockConfig.backlightOutput = output; } void setBacklightOnTime(const String& time) { clockConfig.backlightOnTime = time; } void setBacklightOffTime(const String& time) { clockConfig.backlightOffTime = time; } // Silence periods methods (unchanged) bool getDaytimeSilenceEnabled() const { return clockConfig.daytimeSilenceEnabled; } String getDaytimeSilenceOnTime() const { return clockConfig.daytimeSilenceOnTime; } String getDaytimeSilenceOffTime() const { return clockConfig.daytimeSilenceOffTime; } bool getNighttimeSilenceEnabled() const { return clockConfig.nighttimeSilenceEnabled; } String getNighttimeSilenceOnTime() const { return clockConfig.nighttimeSilenceOnTime; } String getNighttimeSilenceOffTime() const { return clockConfig.nighttimeSilenceOffTime; } void setDaytimeSilenceEnabled(bool enabled) { clockConfig.daytimeSilenceEnabled = enabled; } void setDaytimeSilenceOnTime(const String& time) { clockConfig.daytimeSilenceOnTime = time; } void setDaytimeSilenceOffTime(const String& time) { clockConfig.daytimeSilenceOffTime = time; } void setNighttimeSilenceEnabled(bool enabled) { clockConfig.nighttimeSilenceEnabled = enabled; } void setNighttimeSilenceOnTime(const String& time) { clockConfig.nighttimeSilenceOnTime = time; } void setNighttimeSilenceOffTime(const String& time) { clockConfig.nighttimeSilenceOffTime = time; } // General Config methods bool setSerialLogLevel(uint8_t level); bool setSdLogLevel(uint8_t level); bool setMqttLogLevel(uint8_t level); uint8_t getSerialLogLevel() const { return generalConfig.serialLogLevel; } uint8_t getSdLogLevel() const { return generalConfig.sdLogLevel; } uint8_t getMqttLogLevel() const { return generalConfig.mqttLogLevel; } void setMqttEnabled(bool enabled) { generalConfig.mqttEnabled = enabled; mqttConfig.enabled = enabled; } bool getMqttEnabled() const { return generalConfig.mqttEnabled; } void setBellsEnabled(bool enabled) { generalConfig.bellsEnabled = enabled; } bool getBellsEnabled() const { return generalConfig.bellsEnabled; } String getOtaChannel() const { return generalConfig.otaChannel; } void setOtaChannel(const String& channel) { generalConfig.otaChannel = channel; } // Per-topic MQTT switches (only take effect while getMqttEnabled() is true — see MqttTopicConfig) const MqttTopicConfig& getMqttTopicConfig() const { return generalConfig.mqttTopics; } void setMqttTopicConfig(const MqttTopicConfig& cfg) { generalConfig.mqttTopics = cfg; } bool loadGeneralConfig(); bool saveGeneralConfig(); #if !HAS_SD_CARD bool loadGeneralConfigFromNVS(); bool saveGeneralConfigToNVS(); #endif // Other methods (unchanged) void updateClockAlerts(JsonVariant doc); void updateClockBacklight(JsonVariant doc); void updateClockSilence(JsonVariant doc); bool loadClockConfig(); bool saveClockConfig(); bool loadClockState(); bool saveClockState(); void updateRealTimeFromCommand(JsonVariant doc); void updatePhysicalClockTimeFromCommand(JsonVariant doc); void saveFileToSD(const char* dirPath, const char* filename, const char* data); String getHardwareVariant() const { return deviceConfig.hwFamily; } bool loadDeviceConfig(); bool saveDeviceConfig(); bool loadUpdateServers(); std::vector getUpdateServers() const; String getAPSSID() const { return networkConfig.apSsid; } bool isHealthy() const; /** * @brief Get all configuration settings as a JSON string * @return JSON string containing all current settings */ String getAllSettingsAsJson() const; // ═══════════════════════════════════════════════════════════════════════════════ // FACTORY RESET // ═══════════════════════════════════════════════════════════════════════════════ /** * @brief Perform a full Reset of the Settings to Factory Defaults * * This method: * 1. Clears all user Settings on the SD card * 2. Deletes all Melodies on the SD card * * @return true if reset successful, false otherwise */ bool resetAllToDefaults(); }; // ═══════════════════════════════════════════════════════════════════════════════════ // DEPLOYMENT NOTES: // 2. USER SETTINGS: All loaded from SD card, configurable via app // 3. NETWORK: WiFiManager handles SSIDs/Passwords. IP Settigns loaded from SD, configurable via app // 4. IDENTIFIERS: Auto-generated from deviceUID for consistency // 5. DEFAULTS: Clean minimal defaults, everything configurable // ═══════════════════════════════════════════════════════════════════════════════════