← Compilación | Contenido | Siguiente: Modos del router →
3. Estructura de la aplicación
3.1 Descripción general de los módulos
ACRouter está basado en una arquitectura modular con una jerarquía de componentes clara.
Arquitectura de componentes
┌─────────────────────────────────────────────────────────────┐
│ 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 Módulo acrouter_hal (capa de abstracción de hardware)
Ruta: components/acrouter_hal/
Propósito: Capa de abstracción de hardware para trabajar con sensores, dimmer y algoritmos de control.
Componentes
3.2.1 RouterController
Archivos:
Descripción:
Controlador principal del enrutador solar. Implementa algoritmos de control para los 6 modos de operación (OFF, AUTO, ECO, OFFGRID, MANUAL, BOOST).
Funciones:
- Controlador proporcional para equilibrar P_grid → 0
- Control del dimmer según el modo
- Arquitectura basada en callback (llamado cada 200 ms desde PowerMeterADC)
- Limitación del nivel del dimmer (0–100 %)
- Detección de estado (IDLE, INCREASING, DECREASING, AT_MAXIMUM, AT_MINIMUM)
Parámetros principales:
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
}
Modos de operación:
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étodos públicos:
// 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
Archivos:
Descripción:
Medidor de potencia de alto rendimiento que utiliza DMA ADC en modo continuo.
Arquitectura:
ADC DMA (80 kHz) → ISR callback (10 ms) → Processing Task → RMS calc (200 ms) → User Callback
Especificaciones:
- Frecuencia de muestreo: 10 kHz por canal (80 kHz en total para 8 canales)
- Período RMS: 200 ms (10 períodos AC a 50 Hz)
- Resolución: ADC de 12 bits (0–4095)
- Rango: 0–3,3 V (ADC_ATTEN_DB_12)
- Canales: Hasta 4 canales (voltaje + 3× corriente)
Configuración DMA:
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
}
Sensores compatibles:
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étodos públicos:
// 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;
Estructura de datos del callback:
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
Archivos:
Descripción:
HAL para el control del dimmer AC con TRIAC y detector de cruce por cero.
Características:
- Dimmer de dos canales (2 cargas independientes)
- Detección de cruce por cero para sincronización de la forma de onda AC
- Detección automática de la frecuencia de red (50/60 Hz)
- Curva de potencia compensada por RMS
- Transiciones suaves
Configuración de hardware:
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
}
Pines GPIO (por defecto):
- Cruce por cero: GPIO 18
- Dimmer canal 1: GPIO 19
- Dimmer canal 2: GPIO 23
Métodos públicos:
// 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;
Tipos de curvas:
enum class DimmerCurve : uint8_t {
LINEAR, // Linear
RMS, // RMS-compensated (recommended for heating elements)
LOGARITHMIC // Logarithmic (for LED)
};
3.2.4 PinDefinitions.h
Archivo: include/PinDefinitions.h
Descripción:
Definiciones centralizadas de pines GPIO para todo el proyecto.
Pines por defecto:
// 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
Nota: Los pines pueden reasignarse mediante el HardwareConfigManager y la interfaz web.
3.3 Módulo utils (utilidades)
Ruta: components/utils/
Propósito: Clases auxiliares para configuración, comandos y tipos de datos.
Componentes
3.3.1 ConfigManager
Archivos:
Descripción:
Gestor de configuración del sistema con guardado automático en NVS.
Espacio de nombres NVS: "acrouter"
Parámetros almacenados:
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)
};
Claves NVS:
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étodos públicos:
// 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();
Valores por defecto:
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
Archivos:
Descripción:
Gestor de configuración de hardware para pines GPIO y tipos de sensores. Permite la configuración completa del dispositivo sin recompilación.
Espacio de nombres NVS: "hw_config"
Componentes configurables:
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:
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étodos públicos:
// 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;
Validación:
- ✅ Verificación de conflictos GPIO (un pin = una función)
- ✅ Verificación de validez de pines ADC (solo ADC1)
- ✅ Verificación de pines de solo entrada (34, 35, 36, 39 no pueden ser salidas)
- ✅ Validación del tipo de sensor
Configuración de fábrica:
// 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
Archivos:
Descripción:
Gestor de comandos serie para configuración y monitoreo a través del terminal.
Comandos principales:
# 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étodos públicos:
// Initialization
void begin();
// Main loop (call from loop())
void update();
// Command registration
void registerCommand(const char* cmd, CommandHandler handler);
3.3.4 DataTypes.h
Archivo: include/DataTypes.h
Descripción:
Tipos de datos comunes utilizados en todo el proyecto.
Estructuras principales:
// 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 Módulo comm (comunicación)
Ruta: components/comm/
Propósito: Comunicación de red, servidor web, REST API, gestión WiFi.
Componentes
3.4.1 WiFiManager
Archivos:
Descripción:
Gestión WiFi con soporte simultáneo AP+STA (modo dual ESP32).
Modos de operación:
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
};
Configuración por defecto:
AP SSID: "ACRouter_XXXXXX" // XXXXXX = last 6 digits of MAC
AP Password: "12345678"
AP IP: 192.168.4.1
STA Timeout: 15 seconds
Métodos públicos:
// 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
Archivos:
Descripción:
Servidor web HTTP con REST API e interfaz Material UI.
Puntos finales:
Páginas web:
GET /– Panel de control (página principal)GET /wifi– Página de configuración WiFiGET /settings/hardware– Página de configuración de hardware
REST API – Estado y métricas:
GET /api/status– Estado del sistemaGET /api/metrics– Métricas de potenciaGET /api/config– Configuración del router
REST API – Control:
POST /api/mode– Establecer modoPOST /api/manual– Establecer nivel manualPOST /api/calibrate– Calibración de sensores
REST API – WiFi:
GET /api/wifi/status– Estado WiFiGET /api/wifi/scan– Escaneo de redesPOST /api/wifi/connect– Conectar a redPOST /api/wifi/disconnect– DesconectarPOST /api/wifi/forget– Olvidar red
REST API – Configuración de hardware:
GET /api/hardware/config– Obtener configuraciónPOST /api/hardware/config– Guardar configuraciónPOST /api/hardware/validate– Validación de configuración
REST API – Sistema:
POST /api/system/reboot– Reiniciar
Métodos públicos:
// Initialization
bool begin(uint16_t http_port = 80);
// Control
void start();
void stop();
bool isRunning() const;
// Processing (call from loop())
void handleClient();
Interfaz Material UI:
- Estilos CSS separados (web/styles/MaterialStyles.h)
- Diseño reutilizable (web/components/Layout.h)
- Páginas individuales (web/pages/)
3.4.3 NTPManager
Archivos:
Descripción:
Gestor de sincronización horaria vía NTP (para funcionalidades futuras: modo SCHEDULE, registro de eventos).
Características:
- Sincronización automática con servidores NTP
- Soporte de zonas horarias
- Actualizaciones periódicas de hora
Estado: Fase 2 (no crítico para la versión actual)
3.4.4 OTAManager
Archivos:
Descripción:
Gestor de actualización OTA (Over-The-Air) del firmware.
Características:
- Actualización vía WiFi
- Verificación de integridad (MD5)
- Reversión segura en caso de errores
- Utiliza particiones app0/app1
Estado: Fase 2 (infraestructura preparada en la tabla de particiones)
3.5 Módulo rbdimmer (biblioteca externa)
Ruta: components/rbdimmer/
Descripción:
Biblioteca externa para el control del dimmer AC TRIAC con detector de cruce por cero.
Funcionalidades principales:
- Control TRIAC por ángulo de fase
- Sincronización por cruce por cero
- Soporte de múltiples curvas de potencia (LINEAR, RMS, LOGARITHMIC)
- Detección automática de la frecuencia de red (50/60 Hz)
Nota: DimmerHAL es un wrapper sobre rbdimmer para facilitar su uso.
3.6 Módulo sensors (tipos de sensores)
Ruta: components/sensors/
Archivo: include/SensorTypes.h
Descripción:
Definiciones de tipos de sensores y configuraciones de canales ADC.
Tipos de sensores:
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
};
Configuración de canales:
struct ADCChannelConfig {
uint8_t gpio; // GPIO pin
SensorType type; // Sensor type
float multiplier; // Calibration multiplier
float offset; // Offset
bool enabled; // Channel active
};
3.7 Dependencias entre módulos
Gráfico de dependencias
main.cpp
│
├─► acrouter_hal
│ ├─► RouterController
│ │ └─► DimmerHAL → rbdimmer
│ ├─► DimmerHAL → rbdimmer
│ └─► PowerMeterADC → sensors
│
├─► comm
│ ├─► WiFiManager
│ ├─► WebServerManager
│ ├─► NTPManager
│ └─► OTAManager
│
└─► utils
├─► ConfigManager
├─► HardwareConfigManager → sensors
├─► SerialCommand
└─► DataTypes
Tabla de dependencias
| Módulo | Depende de | Usado en |
|---|---|---|
| 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, todos | main.cpp |
| SerialCommand | ConfigManager, RouterController | main.cpp |
3.8 Ajustes de los módulos
ConfigManager (NVS namespace: "acrouter")
| Parámetro | Clave NVS | Tipo | Por defecto | Rango |
|---|---|---|---|---|
| Modo del router | router_mode |
uint8_t | 1 (AUTO) | 0–5 |
| Coeficiente Kp | ctrl_gain |
float | 200.0 | 10.0–1000.0 |
| Umbral de equilibrio | bal_thresh |
float | 10.0 | 0.0–100.0 |
| Nivel manual | manual_lvl |
uint8_t | 0 | 0–100 |
| Coef. de voltaje | volt_coef |
float | 230.0 | – |
| Coef. de corriente | curr_coef |
float | 50.0 | – |
HardwareConfigManager (NVS namespace: "hw_config")
| Componente | Claves NVS | Ejemplo |
|---|---|---|
| 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 |
| Dimmer 1 | dim1_gpio, dim1_en |
GPIO19, true |
| Cruce por cero | zc_gpio, zc_en |
GPIO18, true |
| Relé 1 | rel1_gpio, rel1_pol, rel1_en |
GPIO15, true, false |
| LED de estado | led_st_gpio |
GPIO17 |