Se rendre au contenu

← Compilation | Sommaire | Suivant : Modes du routeur →

3. Structure de l'application



3.1 Vue d'ensemble des modules

ACRouter repose sur une architecture modulaire avec une hiérarchie de composants claire.


Architecture des composants

python
┌─────────────────────────────────────────────────────────────┐
│                        main.cpp                             │
│                    (Application Entry)                      │
└────────────┬────────────────────────────────────────────────┘
             │
             ├─────────────────────────────────────────────────┐
             │                                                 │
     ┌───────▼──────┐                                ┌─────────▼─────────┐
     │   acrouter   │                                │      comm         │
     │     _hal     │◄───────────────────────────────│  (Communication)  │
     │  (Hardware)  │                                └─────────┬─────────┘
     └───────┬──────┘                                          │
             │                                                 │
             │  ┌──────────────────┐                           │
             ├──►  RouterController│                           │
             │  └──────────────────┘                           │
             │                                                 │
             │  ┌──────────────────┐                           │
             ├──►   DimmerHAL      │                           │
             │  └──────────────────┘                           │
             │                                                 │
             │  ┌──────────────────┐                           │
             └──►  PowerMeterADC   │                           │
                └──────────────────┘                           │
                                                               │
     ┌──────────────────┐                             ┌────────▼────────┐
     │      utils       │◄────────────────────────────│  WiFiManager    │
     │  (Utilities)     │                             ├─────────────────┤
     └───────┬──────────┘                             │ WebServerManager│
             │                                        ├─────────────────┤
             ├──► ConfigManager                       │   NTPManager    │
             │                                        ├─────────────────┤
             ├──► HardwareConfigManager               │   OTAManager    │
             │                                        └─────────────────┘
             └──► SerialCommand

     ┌──────────────────┐
     │    rbdimmer      │
     │  (External lib)  │
     └──────────────────┘

     ┌──────────────────┐
     │     sensors      │
     │  (Sensor Types)  │
     └──────────────────┘



3.2 Module acrouter_hal (couche d'abstraction matérielle)

Chemin : components/acrouter_hal/

Objectif : Couche d'abstraction matérielle pour travailler avec les capteurs, le variateur et les algorithmes de contrôle.


Composants

3.2.1 RouterController

Fichiers :

Description :

Contrôleur principal du routeur solaire. Implémente les algorithmes de contrôle pour les 6 modes de fonctionnement (OFF, AUTO, ECO, OFFGRID, MANUAL, BOOST).

Fonctionnalités :

  • Régulateur proportionnel pour l'équilibrage P_grid → 0
  • Contrôle du variateur selon le mode
  • Architecture pilotée par callback (appelé toutes les 200 ms depuis PowerMeterADC)
  • Limitation du niveau du variateur (0–100 %)
  • Détection d'état (IDLE, INCREASING, DECREASING, AT_MAXIMUM, AT_MINIMUM)

Paramètres principaux :

cpp
namespace RouterConfig {
    constexpr float DEFAULT_CONTROL_GAIN = 200.0f;      // Kp coefficient
    constexpr float DEFAULT_BALANCE_THRESHOLD = 10.0f;  // Balance threshold (W)
    constexpr uint8_t MIN_DIMMER_PERCENT = 0;
    constexpr uint8_t MAX_DIMMER_PERCENT = 100;
    constexpr uint32_t UPDATE_INTERVAL_MS = 200;        // Update frequency
}

Modes de fonctionnement :

cpp
enum class RouterMode : uint8_t {
    OFF = 0,        // Dimmer disabled
    AUTO,           // Solar Router (P_grid → 0)
    ECO,            // Export prevention
    OFFGRID,        // Off-grid mode
    MANUAL,         // Fixed level
    BOOST           // Forced 100%
};

Méthodes publiques :

cpp
// Initialization
bool begin(DimmerHAL* dimmer);

// Mode control
void setMode(RouterMode mode);
RouterMode getMode() const;

// Control parameters
void setControlGain(float gain);              // Set Kp
void setBalanceThreshold(float threshold);     // Set balance threshold
void setManualLevel(uint8_t percent);          // For MANUAL mode

// Main loop (called from PowerMeterADC callback)
void updateControl(const PowerData& data);

// Emergency stop
void emergencyStop();

// Status information
RouterStatus getStatus() const;

3.2.2 PowerMeterADC

Fichiers :

Description :

Wattmètre haute performance utilisant le DMA ADC en mode continu.

Architecture :

python
ADC DMA (80 kHz) → ISR callback (10 ms) → Processing Task → RMS calc (200 ms) → User Callback

Spécifications :

  • Fréquence d'échantillonnage : 10 kHz par canal (80 kHz au total pour 8 canaux)
  • Période RMS : 200 ms (10 périodes AC à 50 Hz)
  • Résolution : ADC 12 bits (0–4095)
  • Plage : 0–3,3 V (ADC_ATTEN_DB_12)
  • Canaux : Jusqu'à 4 canaux (tension + 3× courant)

Configuration DMA :

cpp
namespace PowerMeterConfig {
    constexpr uint32_t SAMPLING_FREQ_HZ = 20000;       // 20 kHz on ADC1, 5 kHz per channel for 4 channels
    constexpr uint8_t MAX_CHANNELS = 4;
    constexpr uint32_t FRAME_TIME_MS = 10;             // DMA callback every 10 ms
    constexpr uint32_t SAMPLES_PER_FRAME = 200;        // 200 samples/channel/frame
    constexpr uint16_t RMS_FRAMES_COUNT = 20;          // 20 frames = 200 ms
    constexpr uint32_t RMS_UPDATE_INTERVAL_MS = 200;   // RMS update
}

Capteurs pris en charge :

cpp
enum class SensorType : uint8_t {
    NONE = 0,           // Channel not used
    VOLTAGE_AC,         // ZMPT107 (voltage)
    CURRENT_LOAD,       // ACS-712 (load current, dimmer current sensor)
    CURRENT_GRID,       // SCT-013 (grid current)
    CURRENT_SOLAR,      // SCT-013 (solar panel current)
    CURRENT_AUX1,       // Additional channel 1
    CURRENT_AUX2        // Additional channel 2
};

Méthodes publiques :

cpp
// Initialization
bool begin();
void setCallback(std::function callback);

// Control
bool start();
void stop();
bool isRunning() const;

// Calibration
void setVoltageCalibration(float multiplier, float offset = 0.0f);
void setCurrentCalibration(uint8_t channel, float multiplier, float offset = 0.0f);

// Data retrieval
PowerData getPowerData() const;
float getVoltageRMS() const;
float getCurrentRMS(CurrentChannel channel) const;
float getPower(CurrentChannel channel) const;

Structure de données du callback :

cpp
struct PowerData {
    float voltage_rms;              // RMS voltage (V)
    float current_rms[3];           // RMS currents [LOAD, GRID, SOLAR] (A)
    float power[3];                 // Power [LOAD, GRID, SOLAR] (W)
    float power_dimmer;             // Dimmer power (W)
    uint32_t timestamp_ms;          // Timestamp
    bool valid;                     // Data is valid
};

3.2.3 DimmerHAL

Fichiers :

Description :

HAL pour le contrôle du variateur AC avec TRIAC et détecteur de passage par zéro.

Fonctionnalités :

  • Variateur à deux canaux (2 charges indépendantes)
  • Détection de passage par zéro pour la synchronisation de la forme d'onde AC
  • Détection automatique de la fréquence du réseau (50/60 Hz)
  • Courbe de puissance compensée RMS
  • Transitions progressives

Configuration matérielle :

cpp
namespace DimmerConfig {
    constexpr uint8_t PHASE_NUM = 0;                    // Single phase
    constexpr uint16_t MAINS_FREQUENCY = 0;             // 0 = auto-detect
    constexpr uint8_t MAX_CHANNELS = 2;                 // 2 channels
    constexpr uint32_t DEFAULT_TRANSITION_MS = 500;     // Transition time
}

Broches GPIO (par défaut) :

  • Passage par zéro : GPIO 18
  • Variateur canal 1 : GPIO 19
  • Variateur canal 2 : GPIO 23

Méthodes publiques :

cpp
// Initialization
bool begin();

// Channel control
void setPower(DimmerChannel channel, uint8_t percent);
void setPowerSmooth(DimmerChannel channel, uint8_t percent, uint32_t transition_ms);
uint8_t getPower(DimmerChannel channel) const;

// Quick turn off
void turnOff(DimmerChannel channel);
void turnOffAll();

// Power curve
void setCurve(DimmerChannel channel, DimmerCurve curve);

// Information
DimmerStatus getStatus(DimmerChannel channel) const;
bool isInitialized() const;

Types de courbes :

cpp
enum class DimmerCurve : uint8_t {
    LINEAR,         // Linear
    RMS,            // RMS-compensated (recommended for heating elements)
    LOGARITHMIC     // Logarithmic (for LED)
};

3.2.4 PinDefinitions.h

Fichier : include/PinDefinitions.h

Description :

Définitions centralisées des broches GPIO pour l'ensemble du projet.

Broches par défaut :

cpp
// ADC pins (ADC1 only!)
constexpr uint8_t ADC_VOLTAGE_PIN = 35;      // ZMPT107 voltage sensor
constexpr uint8_t ADC_CURRENT_LOAD_PIN = 39; // SCT-013 load current
constexpr uint8_t ADC_CURRENT_GRID_PIN = 36; // SCT-013 grid current
constexpr uint8_t ADC_CURRENT_SOLAR_PIN = 34;// SCT-013 solar current

// Dimmer pins
constexpr uint8_t DIMMER_ZEROCROSS_PIN = 18; // Zero-cross detector
constexpr uint8_t DIMMER_CH1_PIN = 19;       // Dimmer channel 1
constexpr uint8_t DIMMER_CH2_PIN = 23;       // Dimmer channel 2 (Phase 2)

// LED indicators
constexpr uint8_t LED_STATUS_PIN = 17;       // Status LED
constexpr uint8_t LED_LOAD_PIN = 5;          // Load indicator LED

// Relays (Phase 2)
constexpr uint8_t RELAY_CH1_PIN = 15;        // Relay 1
constexpr uint8_t RELAY_CH2_PIN = 2;         // Relay 2

Remarque : Les broches peuvent être réaffectées via le HardwareConfigManager et l'interface web.




3.3 Module utils (utilitaires)

Chemin : components/utils/

Objectif : Classes utilitaires pour la configuration, les commandes et les types de données.


Composants

3.3.1 ConfigManager

Fichiers :

Description :

Gestionnaire de configuration système avec sauvegarde automatique dans NVS.

Espace de noms NVS : "acrouter"

Paramètres stockés :

cpp
struct SystemConfig {
    // Router parameters
    uint8_t router_mode;        // RouterMode (0-5)
    float control_gain;         // Kp coefficient (10-1000)
    float balance_threshold;    // Balance threshold (W)
    uint8_t manual_level;       // Level for MANUAL mode (0-100%)

    // Sensor calibration
    float voltage_coef;         // Voltage coefficient
    float current_coef;         // Current coefficient (A/V)
    float current_threshold;    // Minimum current (A)
    float power_threshold;      // Minimum power (W)
};

Clés NVS :

cpp
namespace ConfigKeys {
    constexpr const char* ROUTER_MODE       = "router_mode";
    constexpr const char* CONTROL_GAIN      = "ctrl_gain";
    constexpr const char* BALANCE_THRESHOLD = "bal_thresh";
    constexpr const char* MANUAL_LEVEL      = "manual_lvl";
    constexpr const char* VOLTAGE_COEF      = "volt_coef";
    constexpr const char* CURRENT_COEF      = "curr_coef";
    // ... etc.
}

Méthodes publiques :

cpp
// Initialization
bool begin();

// Get configuration
const SystemConfig& getConfig() const;

// Set parameters (automatically saved to NVS)
bool setRouterMode(uint8_t mode);
bool setControlGain(float gain);
bool setBalanceThreshold(float threshold);
bool setManualLevel(uint8_t level);
bool setVoltageCoefficient(float coef);
bool setCurrentCoefficient(float coef);

// Bulk operations
bool saveAll();
bool loadAll();
bool resetToDefaults();

Valeurs par défaut :

cpp
namespace ConfigDefaults {
    constexpr uint8_t ROUTER_MODE = 1;          // AUTO
    constexpr float CONTROL_GAIN = 200.0f;
    constexpr float BALANCE_THRESHOLD = 10.0f;
    constexpr uint8_t MANUAL_LEVEL = 0;
    constexpr float VOLTAGE_COEF = 230.0f;
    constexpr float CURRENT_COEF = 50.0f;       // SCT-013 50A/1V
}

3.3.2 HardwareConfigManager

Fichiers :

Description :

Gestionnaire de configuration matérielle pour les broches GPIO et les types de capteurs. Permet la configuration complète de l'appareil sans recompilation.

Espace de noms NVS : "hw_config"

Composants configurables :

cpp
struct HardwareConfig {
    ADCChannelConfig adc_channels[4];       // 4 ADC channels
    DimmerChannelConfig dimmer_ch1;         // Dimmer 1
    DimmerChannelConfig dimmer_ch2;         // Dimmer 2
    uint8_t zerocross_gpio;                 // Zero-cross pin
    bool zerocross_enabled;
    RelayChannelConfig relay_ch1;           // Relay 1
    RelayChannelConfig relay_ch2;           // Relay 2
    uint8_t led_status_gpio;                // Status LED
    uint8_t led_load_gpio;                  // Load LED
};

Canal ADC :

cpp
struct ADCChannelConfig {
    uint8_t gpio;               // GPIO pin (ADC1 only: 32,33,34,35,36,39)
    SensorType type;            // Sensor type
    float multiplier;           // Calibration multiplier
    float offset;               // Calibration offset
    bool enabled;               // Channel enabled
};

Méthodes publiques :

cpp
// Initialization
bool begin();

// ADC channel configuration
bool setADCChannel(uint8_t channel, const ADCChannelConfig& config);
ADCChannelConfig getADCChannel(uint8_t channel) const;

// Dimmer configuration
bool setDimmerChannel(uint8_t channel, const DimmerChannelConfig& config);

// Relay configuration
bool setRelayChannel(uint8_t channel, const RelayChannelConfig& config);

// Zero-cross
bool setZeroCross(uint8_t gpio, bool enabled = true);

// LED
bool setStatusLED(uint8_t gpio);
bool setLoadLED(uint8_t gpio);

// Validation
bool validate(String* error_msg = nullptr) const;

// Bulk operations
bool saveAll();
bool loadAll();
bool resetToDefaults();
void printConfig() const;

Validation :

  • ✅ Vérification des conflits GPIO (une broche = une fonction)
  • ✅ Vérification de la validité des broches ADC (ADC1 uniquement)
  • ✅ Vérification des broches en entrée uniquement (34, 35, 36, 39 ne peuvent pas être des sorties)
  • ✅ Validation du type de capteur

Paramètres d'usine :

cpp
// ADC channels
ADC0: GPIO35, VOLTAGE_AC,    mult=230.0, offset=0.0, ENABLED
ADC1: GPIO39, CURRENT_LOAD,  mult=30.0,  offset=0.0, ENABLED
ADC2: GPIO36, CURRENT_GRID,  mult=30.0,  offset=0.0, ENABLED
ADC3: GPIO34, CURRENT_SOLAR, mult=30.0,  offset=0.0, ENABLED

// Dimmer
Ch1: GPIO19, ENABLED
Ch2: GPIO23, DISABLED

// Zero-Cross
GPIO18, ENABLED

3.3.3 SerialCommand

Fichiers :

Description :

Gestionnaire de commandes série pour la configuration et la surveillance via terminal.

Commandes principales :

bash
# Information
help                    # Show all commands
status                  # Current state
metrics                 # Power metrics
config-show             # Show configuration
hw-config-show          # Show hardware configuration

# Mode control
set-mode <0-5>          # Set mode (0=OFF, 1=AUTO, ...)
set-manual <0-100>      # Set level for MANUAL

# Parameters
set-kp           # Set Kp coefficient
set-threshold    # Set balance threshold

# Calibration
calibrate-voltage  [offset]
calibrate-current   [offset]

# Configuration
config-save             # Save configuration
config-reset            # Reset to factory defaults
hw-config-reset         # Reset hardware configuration

# System
reboot                  # Reboot
factory-reset           # Full reset (all settings)

Méthodes publiques :

cpp
// Initialization
void begin();

// Main loop (call from loop())
void update();

// Command registration
void registerCommand(const char* cmd, CommandHandler handler);

3.3.4 DataTypes.h

Fichier : include/DataTypes.h

Description :

Types de données communs utilisés dans l'ensemble du projet.

Structures principales :

cpp
// Power data
struct PowerData {
    float voltage_rms;
    float current_rms[3];       // [LOAD, GRID, SOLAR]
    float power[3];             // [LOAD, GRID, SOLAR]
    float power_dimmer;
    uint32_t timestamp_ms;
    bool valid;
};

// System metrics
struct SystemMetrics {
    PowerData power;
    uint8_t dimmer_percent;
    RouterMode mode;
    RouterState state;
    uint32_t uptime_ms;
    uint32_t free_heap;
};



3.4 Module comm (communication)

Chemin : components/comm/

Objectif : Communication réseau, serveur web, REST API, gestion WiFi.


Composants

3.4.1 WiFiManager

Fichiers :

Description :

Gestion WiFi avec prise en charge simultanée AP+STA (mode double ESP32).

Modes de fonctionnement :

cpp
enum class WiFiState : uint8_t {
    IDLE,               // Not initialized
    AP_ONLY,            // AP only (no STA credentials)
    STA_CONNECTING,     // Connecting to STA
    STA_CONNECTED,      // Connected to STA
    AP_STA,             // Both modes active
    STA_FAILED          // STA failed, AP active
};

Configuration par défaut :

cpp
AP SSID: "ACRouter_XXXXXX"  // XXXXXX = last 6 digits of MAC
AP Password: "12345678"
AP IP: 192.168.4.1
STA Timeout: 15 seconds

Méthodes publiques :

cpp
// Initialization
bool begin();

// AP mode
bool startAP(const char* ssid = nullptr, const char* password = nullptr);
void stopAP();
bool isAPActive() const;

// STA mode
bool connectSTA(const char* ssid, const char* password);
void disconnectSTA();
bool isSTAConnected() const;

// WiFi scan
std::vector scanNetworks();

// Status
WiFiStatus getStatus() const;

3.4.2 WebServerManager

Fichiers :

Description :

Serveur web HTTP avec REST API et interface Material UI.

Points de terminaison :

Pages web :

  • GET / – Tableau de bord (page principale)
  • GET /wifi – Page de configuration WiFi
  • GET /settings/hardware – Page de configuration matérielle

REST API – Statut et métriques :

  • GET /api/status – Statut du système
  • GET /api/metrics – Métriques de puissance
  • GET /api/config – Configuration du routeur

REST API – Contrôle :

  • POST /api/mode – Définir le mode
  • POST /api/manual – Définir le niveau manuel
  • POST /api/calibrate – Calibrage des capteurs

REST API – WiFi :

  • GET /api/wifi/status – Statut WiFi
  • GET /api/wifi/scan – Scan des réseaux
  • POST /api/wifi/connect – Se connecter au réseau
  • POST /api/wifi/disconnect – Se déconnecter
  • POST /api/wifi/forget – Oublier le réseau

REST API – Configuration matérielle :

  • GET /api/hardware/config – Obtenir la configuration
  • POST /api/hardware/config – Sauvegarder la configuration
  • POST /api/hardware/validate – Validation de la configuration

REST API – Système :

  • POST /api/system/reboot – Redémarrer

Méthodes publiques :

cpp
// Initialization
bool begin(uint16_t http_port = 80);

// Control
void start();
void stop();
bool isRunning() const;

// Processing (call from loop())
void handleClient();

Interface Material UI :


3.4.3 NTPManager

Fichiers :

Description :

Gestionnaire de synchronisation horaire via NTP (pour les fonctionnalités futures : mode SCHEDULE, journalisation).

Fonctionnalités :

  • Synchronisation automatique avec les serveurs NTP
  • Prise en charge des fuseaux horaires
  • Mises à jour horaires périodiques

Statut : Phase 2 (non critique pour la version actuelle)


3.4.4 OTAManager

Fichiers :

Description :

Gestionnaire de mise à jour OTA (Over-The-Air) du firmware.

Fonctionnalités :

  • Mise à jour via WiFi
  • Vérification d'intégrité (MD5)
  • Retour en arrière sécurisé en cas d'erreur
  • Utilise les partitions app0/app1

Statut : Phase 2 (infrastructure prête dans la table de partitions)




3.5 Module rbdimmer (bibliothèque externe)

Chemin : components/rbdimmer/

Description :

Bibliothèque externe pour le contrôle du variateur AC TRIAC avec détecteur de passage par zéro.

Fonctionnalités principales :

  • Commande TRIAC par angle de phase
  • Synchronisation par passage par zéro
  • Prise en charge de plusieurs courbes de puissance (LINEAR, RMS, LOGARITHMIC)
  • Détection automatique de la fréquence du réseau (50/60 Hz)

Remarque : DimmerHAL est un wrapper autour de rbdimmer pour faciliter l'utilisation.




3.6 Module sensors (types de capteurs)

Chemin : components/sensors/

Fichier : include/SensorTypes.h

Description :

Définitions des types de capteurs et configurations des canaux ADC.

Types de capteurs :

cpp
enum class SensorType : uint8_t {
    NONE = 0,           // Channel not used
    VOLTAGE_AC,         // ZMPT107 (AC voltage)
    CURRENT_LOAD,       // SCT-013 (load current)
    CURRENT_GRID,       // SCT-013 (grid current, import/export)
    CURRENT_SOLAR,      // SCT-013 (solar panel current)
    CURRENT_AUX1,       // Additional sensor 1
    CURRENT_AUX2        // Additional sensor 2
};

Configuration des canaux :

cpp
struct ADCChannelConfig {
    uint8_t gpio;               // GPIO pin
    SensorType type;            // Sensor type
    float multiplier;           // Calibration multiplier
    float offset;               // Offset
    bool enabled;               // Channel active
};



3.7 Dépendances entre modules


Graphe de dépendances

python
main.cpp
  │
  ├─► acrouter_hal
  │     ├─► RouterController
  │     │     └─► DimmerHAL → rbdimmer
  │     ├─► DimmerHAL → rbdimmer
  │     └─► PowerMeterADC → sensors
  │
  ├─► comm
  │     ├─► WiFiManager
  │     ├─► WebServerManager
  │     ├─► NTPManager
  │     └─► OTAManager
  │
  └─► utils
        ├─► ConfigManager
        ├─► HardwareConfigManager → sensors
        ├─► SerialCommand
        └─► DataTypes


Tableau des dépendances

Module Dépend de Utilisé dans
RouterController DimmerHAL, PowerMeterADC main.cpp
DimmerHAL rbdimmer, PinDefinitions RouterController
PowerMeterADC SensorTypes, DataTypes RouterController, WebServerManager
ConfigManager NVS main.cpp, WebServerManager
HardwareConfigManager SensorTypes, NVS main.cpp, WebServerManager
WiFiManager ESP32 WiFi main.cpp, WebServerManager
WebServerManager WiFiManager, tous main.cpp
SerialCommand ConfigManager, RouterController main.cpp



3.8 Paramètres des modules


ConfigManager (NVS namespace: "acrouter")

Paramètre Clé NVS Type Défaut Plage
Mode du routeur router_mode uint8_t 1 (AUTO) 0–5
Coefficient Kp ctrl_gain float 200.0 10.0–1000.0
Seuil d'équilibrage bal_thresh float 10.0 0.0–100.0
Niveau manuel manual_lvl uint8_t 0 0–100
Coeff. tension volt_coef float 230.0
Coeff. courant curr_coef float 50.0


HardwareConfigManager (NVS namespace: "hw_config")

Composant Clés NVS Exemple
ADC0 adc0_gpio, adc0_type, adc0_mult, adc0_offset, adc0_en GPIO35, VOLTAGE_AC, 230.0, 0.0, true
ADC1 adc1_gpio, adc1_type, adc1_mult, adc1_offset, adc1_en GPIO39, CURRENT_LOAD, 30.0, 0.0, true
Variateur 1 dim1_gpio, dim1_en GPIO19, true
Passage par zéro zc_gpio, zc_en GPIO18, true
Relais 1 rel1_gpio, rel1_pol, rel1_en GPIO15, true, false
LED de statut led_st_gpio GPIO17

← Compilation | Sommaire | Suivant : Modes du routeur →