refactor: Fixed the file hierarchy and switched to platform.io

This commit is contained in:
2026-02-28 21:57:42 +02:00
parent ab1e4f2e6d
commit 30d660268f
65 changed files with 1208 additions and 1281 deletions
+471
View File
@@ -0,0 +1,471 @@
/*
* ═══════════════════════════════════════════════════════════════════════════════════
* 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 <Arduino.h>
#include <ArduinoJson.h>
#include <SD.h>
#include <IPAddress.h>
#include <vector>
#include <nvs_flash.h>
#include <nvs.h>
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 updated automatically after OTA updates (SD storage).
*/
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 fwVersion = "0"; // 📋 Current firmware version (SD) - auto-updated (integer string)
};
/**
* @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-<DEVID>"
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 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 fallbackServerUrl = "http://firmware.bonamin.space"; // 🛡️ Universal fallback - OK as is
int timeout = 10000; // ⏱️ Universal timeout - OK as is
int retries = 3; // 🔄 Universal retries - OK as is
};
/**
* @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 = 5;
uint8_t sdLogLevel = 0;
uint8_t mqttLogLevel = 0;
bool mqttEnabled = true; // MQTT enabled by default
};
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<String> 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-<last6ofUID>"
* - apSsid: "BellSystems-Setup-<last6ofUID>"
* - mqttUser: deviceUID
*/
void generateNetworkIdentifiers();
bool ensureSDCard();
void createDefaultBellConfig();
// NVS management (READ-ONLY for factory-set device identity)
bool initializeNVS();
bool loadDeviceIdentityFromNVS();
String readNVSString(const char* key, const String& defaultValue);
// REMOVED: saveDeviceIdentityToNVS() and writeNVSString() - Production firmware is READ-ONLY
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 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 getFwVersion() const { return deviceConfig.fwVersion; }
/** @brief Set firmware version (auto-updated after OTA) */
void setFwVersion(const String& version) { deviceConfig.fwVersion = version; }
// 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();
// Time configuration persistence
bool loadTimeConfig();
bool saveTimeConfig();
// Bell and clock configuration methods (unchanged)
bool loadBellDurations();
bool saveBellDurations();
bool loadBellOutputs();
bool saveBellOutputs();
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; }
bool loadGeneralConfig();
bool saveGeneralConfig();
// 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.hwType; }
bool loadDeviceConfig();
bool saveDeviceConfig();
bool loadUpdateServers();
std::vector<String> 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
// ═══════════════════════════════════════════════════════════════════════════════════