-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMiniOS_WiFi_Client.ino
More file actions
2159 lines (1844 loc) · 68 KB
/
Copy pathMiniOS_WiFi_Client.ino
File metadata and controls
2159 lines (1844 loc) · 68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* MiniOS WiFi Client
* Versión ligera para conectar al backend centralizado
*
* Características:
* - Conexión WebSocket al backend
* - Identificación por MAC Address
* - Control GPIO remoto
* - Sensores DHT e I2C (AHT20, BMP280)
* - Actualizaciones OTA
* - Soporte multi-plataforma: ESP32, ESP32-S3, ESP32-C3
*/
#include <Arduino.h>
#include <WiFi.h>
#include <WebSocketsClient.h>
#include <ArduinoJson.h>
#include <HTTPClient.h>
#include <Update.h>
#include <Preferences.h>
#include <DHT.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_AHTX0.h>
#include <Adafruit_BMP280.h>
#include <Adafruit_BME280.h>
// Incluir NeoPixel solo si el board lo soporta
#if defined(CONFIG_IDF_TARGET_ESP32S3) || defined(CONFIG_IDF_TARGET_ESP32)
#include <Adafruit_NeoPixel.h>
#define HAS_RGB_LED true
#else
#define HAS_RGB_LED false
#endif
// ============================================
// DETECCIÓN AUTOMÁTICA DE PLATAFORMA
// ============================================
#if defined(CONFIG_IDF_TARGET_ESP32S3)
#define BOARD_MODEL "ESP32-S3"
#define BOARD_FAMILY "ESP32-S3"
#define LED_RGB_PIN 48
#define I2C_SDA_DEFAULT 21
#define I2C_SCL_DEFAULT 22
#elif defined(CONFIG_IDF_TARGET_ESP32C3)
#define BOARD_MODEL "ESP32-C3"
#define BOARD_FAMILY "ESP32-C3"
#define LED_RGB_PIN -1
#define I2C_SDA_DEFAULT 8
#define I2C_SCL_DEFAULT 9
#elif defined(CONFIG_IDF_TARGET_ESP32S2)
#define BOARD_MODEL "ESP32-S2"
#define BOARD_FAMILY "ESP32-S2"
#define LED_RGB_PIN -1
#define I2C_SDA_DEFAULT 21
#define I2C_SCL_DEFAULT 22
#else
#define BOARD_MODEL "ESP32"
#define BOARD_FAMILY "ESP32"
#define LED_RGB_PIN -1
#define I2C_SDA_DEFAULT 21
#define I2C_SCL_DEFAULT 22
#endif
// ============================================
// CONFIGURACIÓN
// ============================================
#define FIRMWARE_VERSION "2.0.0"
// WiFi - Configurar aquí o vía Serial
String WIFI_SSID = "CASA ROJAS";
String WIFI_PASS = "26ROJASM";
// Backend
String BACKEND_HOST = "minios.iot-robotics.cl"; // Dominio del backend
int BACKEND_PORT = 443; // Puerto 80 con Nginx, 443 con SSL
// Hardware
#define MAX_GPIOS 20
#define MAX_DHT_SENSORS 4
#define MAX_ULTRASONIC_SENSORS 4
#define MAX_I2C_SENSORS 4
#define LED_STATUS 2 // LED integrado
#define LED_RGB_COUNT 1
// Ahorro de energía - Deep Sleep
#define DEEP_SLEEP_ENABLED true
#define SENSOR_READ_TIMEOUT 15000 // 15s timeout para leer sensores y enviar
// ============================================
// CLASIFICACIÓN DE GPIOs POR PLATAFORMA
// ============================================
#if defined(CONFIG_IDF_TARGET_ESP32S3)
// ESP32-S3: 45 GPIOs disponibles
const int ANALOG_GPIOS[] = {1, 2, 4, 5, 6, 7};
const int ANALOG_GPIOS_COUNT = 6;
const int DIGITAL_GPIOS[] = {0, 3, 14, 15, 16, 17, 18, 19, 20, 21, 36, 37, 38, 39, 40, 41, 42, 45, 46};
const int DIGITAL_GPIOS_COUNT = 19;
const int I2C_GPIOS[] = {8, 9}; // 8=SDA, 9=SCL
const int I2C_GPIOS_COUNT = 2;
const int SPI_GPIOS[] = {10, 11, 12, 13};
const int SPI_GPIOS_COUNT = 4;
#elif defined(CONFIG_IDF_TARGET_ESP32C3)
// ESP32-C3: 13 GPIOs disponibles (0-10, 18-21)
// GPIO 2, 8, 9 son de boot/strapping - usar con precaución
const int ANALOG_GPIOS[] = {0, 1, 2, 3, 4}; // ADC1_CH0-4
const int ANALOG_GPIOS_COUNT = 5;
const int DIGITAL_GPIOS[] = {5, 6, 7, 10, 18, 19, 20, 21};
const int DIGITAL_GPIOS_COUNT = 8;
const int I2C_GPIOS[] = {8, 9}; // SDA=8, SCL=9 (default C3)
const int I2C_GPIOS_COUNT = 2;
const int SPI_GPIOS[] = {2, 6, 7, 10}; // MISO, MOSI, SCK, CS
const int SPI_GPIOS_COUNT = 4;
#elif defined(CONFIG_IDF_TARGET_ESP32S2)
// ESP32-S2
const int ANALOG_GPIOS[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
const int ANALOG_GPIOS_COUNT = 10;
const int DIGITAL_GPIOS[] = {0, 11, 12, 13, 14, 15, 16, 17, 18, 21, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42};
const int DIGITAL_GPIOS_COUNT = 20;
const int I2C_GPIOS[] = {8, 9};
const int I2C_GPIOS_COUNT = 2;
const int SPI_GPIOS[] = {10, 11, 12, 13};
const int SPI_GPIOS_COUNT = 4;
#else
// ESP32 estándar
const int ANALOG_GPIOS[] = {32, 33, 34, 35, 36, 39};
const int ANALOG_GPIOS_COUNT = 6;
const int DIGITAL_GPIOS[] = {0, 2, 4, 5, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 25, 26, 27};
const int DIGITAL_GPIOS_COUNT = 18;
const int I2C_GPIOS[] = {21, 22}; // SDA=21, SCL=22 (default)
const int I2C_GPIOS_COUNT = 2;
const int SPI_GPIOS[] = {5, 18, 19, 23};
const int SPI_GPIOS_COUNT = 4;
#endif
// ============================================
// ESTRUCTURAS
// ============================================
enum GPIOMode {
MODE_OUTPUT,
MODE_INPUT,
MODE_INPUT_PULLUP,
MODE_PWM
};
struct GPIOConfig {
int pin;
GPIOMode mode;
int value; // Valor digital (0/1) o analógico RAW (0-4095)
String name;
bool active;
bool loopEnabled;
unsigned long loopInterval;
unsigned long lastLoop;
bool isAnalog; // True si es pin analógico (ADC)
// Fórmulas de conversión para sensores analógicos
bool formulaEnabled;
String formulaType; // "4-20mA", "0-10V", "0-3.3V", "custom"
float formulaMin; // Valor mínimo de la escala
float formulaMax; // Valor máximo de la escala
float convertedValue; // Valor después de aplicar fórmula
String unit; // Unidad (°C, %, PSI, etc.)
};
struct DHTConfig {
int pin;
DHT* sensor;
String name;
String type;
float temperature;
float humidity;
bool active;
unsigned long readInterval;
unsigned long lastRead;
};
struct I2CConfig {
int id;
String name;
String sensorType; // "AHT20", "BMP280", "BME280"
uint8_t i2cAddress; // 0x38 (AHT20), 0x76/0x77 (BMP280)
bool active;
unsigned long readInterval;
unsigned long lastRead;
// Datos del sensor
float temperature;
float humidity; // Solo AHT20/BME280
float pressure; // Solo BMP280/BME280 (hPa)
float altitude; // Solo BMP280/BME280 (m)
// Punteros a objetos sensor
Adafruit_AHTX0* aht;
Adafruit_BMP280* bmp;
Adafruit_BME280* bme;
};
struct UltrasonicConfig {
int id;
int trigPin;
int echoPin;
String name;
int maxDistance; // cm
bool detectionEnabled;
int triggerDistance; // cm
int triggerGpioPin;
int triggerGpioValue;
int triggerDuration; // ms (0 = mantener)
bool active;
unsigned long readInterval;
unsigned long lastRead;
float lastDistance;
bool triggered;
unsigned long triggerStartTime;
// Buffer para detección de movimiento
float distanceBuffer[10]; // Últimas 10 lecturas para mejor análisis
int bufferIndex;
bool bufferFull;
// Estado de detección actual
unsigned long detectionStartTime;
float currentSpeed;
};
// ============================================
// VARIABLES GLOBALES
// ============================================
WebSocketsClient webSocket;
Preferences preferences;
// LED RGB solo en plataformas compatibles
#if HAS_RGB_LED
Adafruit_NeoPixel rgbLed(LED_RGB_COUNT, LED_RGB_PIN, NEO_GRB + NEO_KHZ800);
#endif
GPIOConfig gpios[MAX_GPIOS];
int gpioCount = 0;
DHTConfig dhtSensors[MAX_DHT_SENSORS];
int dhtCount = 0;
I2CConfig i2cSensors[MAX_I2C_SENSORS];
int i2cCount = 0;
UltrasonicConfig ultrasonicSensors[MAX_ULTRASONIC_SENSORS];
int ultrasonicCount = 0;
String deviceMac;
int deviceId = 0;
bool isRegistered = false;
// Sincronización de tiempo
String serverTimezone = "America/Santiago";
bool timeSync = false;
unsigned long lastTimeSync = 0;
const unsigned long TIME_SYNC_INTERVAL = 3600000; // Re-sincronizar cada hora
// Control de Deep Sleep
bool disableDeepSleep = false; // Flag para desactivar deep sleep (útil para OTA/debugging)
unsigned long deepSleepDuration = 60; // Segundos entre ciclos (configurable desde backend)
unsigned long lastDataSend = 0;
const unsigned long DATA_SEND_INTERVAL = 5000;
unsigned long lastReconnect = 0;
const unsigned long RECONNECT_INTERVAL = 5000;
// OTA
bool otaInProgress = false;
int otaId = 0;
String otaFilename = "";
int otaFilesize = 0;
String otaChecksum = "";
// ============================================
// PROTOTIPOS DE FUNCIONES
// ============================================
void connectWiFi();
void connectWebSocket();
void webSocketEvent(WStype_t type, uint8_t* payload, size_t length);
void registerDevice();
void syncTimeWithBackend();
void handleWebSocketMessage(const char* payload);
void handleConfig(JsonDocument& doc);
void handleCommand(JsonDocument& doc);
void sendSensorData();
void readDHTSensors();
void readI2CSensors();
void processGpioLoops();
void startOTA(int id, String filename, int filesize, String checksum);
void reportOTAStatus(const char* status, String error);
void loadConfig();
void saveConfig();
void handleSerial();
// Funciones de validación GPIO
bool GPIO_InList(int pin, const int* list, int count);
bool GPIO_IsValid(int pin);
bool GPIO_IsAnalog(int pin);
bool GPIO_IsAppropriate(int pin, GPIOMode mode);
float applyFormula(int rawValue, GPIOConfig& gpio);
// Ultrasonic HC-SR04
float readUltrasonic(int trigPin, int echoPin, int maxDistance);
void readUltrasonicSensors();
void processUltrasonicTriggers();
float calculateMovementSpeed(int sensorIndex);
bool isObjectMoving(int sensorIndex);
// LED RGB
void blinkRGB(uint8_t r, uint8_t g, uint8_t b, int duration = 50);
// Ahorro de energía
void enterDeepSleep(unsigned long seconds);
// ============================================
// SETUP
// ============================================
void setup() {
Serial.begin(115200);
delay(1000);
// Mostrar razón de wake-up
esp_sleep_wakeup_cause_t wakeup_reason = esp_sleep_get_wakeup_cause();
switch(wakeup_reason) {
case ESP_SLEEP_WAKEUP_TIMER:
Serial.println("⏰ Wake up: Timer (Deep Sleep)");
break;
case ESP_SLEEP_WAKEUP_UNDEFINED:
default:
Serial.println("🔌 Wake up: Power on / Reset");
break;
}
Serial.println("\n========================================");
Serial.println("MiniOS WiFi Client v" FIRMWARE_VERSION);
Serial.print("Board: ");
Serial.println(BOARD_MODEL);
Serial.println("========================================");
// LED de estado
pinMode(LED_STATUS, OUTPUT);
digitalWrite(LED_STATUS, LOW);
// LED RGB NeoPixel (solo si está disponible)
#if HAS_RGB_LED
rgbLed.begin();
rgbLed.setBrightness(50); // Brillo moderado (0-255)
rgbLed.clear();
rgbLed.show();
Serial.println("✅ LED RGB inicializado");
#endif
// Inicializar bus I2C con pines correctos según plataforma
Wire.begin(I2C_SDA_DEFAULT, I2C_SCL_DEFAULT);
Wire.setClock(100000); // 100kHz: más compatible con módulos AHT20+BMP280 combo
delay(100); // Dar tiempo a los sensores I2C para estabilizarse tras encendido
Serial.print("✅ I2C inicializado 100kHz (SDA:");
Serial.print(I2C_SDA_DEFAULT);
Serial.print(", SCL:");
Serial.print(I2C_SCL_DEFAULT);
Serial.println(")");
// Inicializar WiFi para obtener MAC
WiFi.mode(WIFI_STA);
// Obtener MAC
deviceMac = WiFi.macAddress();
Serial.print("MAC Address: ");
Serial.println(deviceMac);
if (deviceMac == "00:00:00:00:00:00" || deviceMac.length() == 0) {
Serial.println("⚠️ Error obteniendo MAC, reintentando...");
delay(100);
deviceMac = WiFi.macAddress();
Serial.print("MAC Address: ");
Serial.println(deviceMac);
}
// Cargar configuración guardada
loadConfig();
// Mostrar comandos disponibles
Serial.println("\nComandos disponibles:");
Serial.println(" wifi <ssid> <pass> - Configurar WiFi");
Serial.println(" server <host> <port> - Configurar backend");
Serial.println(" status - Ver estado");
Serial.println(" reboot - Reiniciar");
// Prompt para desactivar Deep Sleep (útil para subir firmware)
#if DEEP_SLEEP_ENABLED
Serial.println("\n⚠️ Deep Sleep ACTIVADO");
Serial.println("Presiona cualquier tecla en 10 segundos para DESACTIVAR Deep Sleep");
Serial.println("(útil para subir nuevo firmware vía USB)");
unsigned long startPrompt = millis();
while (millis() - startPrompt < 10000) { // Esperar 10 segundos
if (Serial.available()) {
// Leer y descartar la entrada
while (Serial.available()) Serial.read();
disableDeepSleep = true;
Serial.println("\n✅ Deep Sleep DESACTIVADO - Modo normal continuo");
Serial.println("El dispositivo permanecerá despierto para programación OTA/USB");
break;
}
delay(100);
// Mostrar countdown cada segundo
if ((millis() - startPrompt) % 1000 == 0) {
Serial.print(".");
}
}
if (!disableDeepSleep) {
Serial.println("\n⏰ Continuando con Deep Sleep activado");
}
#endif
// Conectar WiFi
if (WIFI_SSID.length() > 0) {
connectWiFi();
} else {
Serial.println("\n⚠️ WiFi no configurado. Usa: wifi <ssid> <pass>");
}
}
// ============================================
// LOOP PRINCIPAL
// ============================================
void loop() {
static bool taskCompleted = false;
if (taskCompleted) {
// Ya terminamos, esperar a que Deep Sleep se active
delay(1000);
return;
}
unsigned long startTime = millis();
// 1. Procesar comandos Serial (solo por 2 segundos)
while (millis() - startTime < 2000 && Serial.available()) {
handleSerial();
delay(10);
}
// 2. Verificar WiFi
if (WiFi.status() != WL_CONNECTED) {
Serial.println("❌ Sin WiFi, reintentando...");
connectWiFi();
if (WiFi.status() != WL_CONNECTED) {
Serial.println("❌ No se pudo conectar WiFi");
if (DEEP_SLEEP_ENABLED && !disableDeepSleep) {
enterDeepSleep(deepSleepDuration);
}
return;
}
}
// 3. Conectar WebSocket si no está conectado
if (!isRegistered) {
connectWebSocket();
// Esperar conexión (timeout 10s)
unsigned long wsStart = millis();
while (!isRegistered && millis() - wsStart < 10000) {
webSocket.loop();
delay(100);
}
if (!isRegistered) {
Serial.println("⚠️ No se pudo registrar en backend");
}
}
// 4. Re-sincronizar hora si es necesario (cada hora)
if (timeSync && millis() - lastTimeSync > TIME_SYNC_INTERVAL) {
syncTimeWithBackend();
}
// 5. Leer TODOS los sensores
Serial.println("📊 Leyendo sensores...");
readDHTSensors();
readI2CSensors();
readUltrasonicSensors(); // Lee y detecta
processUltrasonicTriggers(); // Procesa triggers
// 6. Enviar datos
if (isRegistered) {
Serial.println("📤 Enviando datos...");
sendSensorData();
// 6. Ventana de comandos: primero drenar mensajes pendientes del backend
// (comandos encolados mientras el dispositivo estaba dormido llegan aquí primero)
Serial.println("⏳ Procesando comandos pendientes...");
unsigned long drainStart = millis();
while (millis() - drainStart < 3000) {
webSocket.loop();
delay(50);
}
// Luego mantener ventana activa para comandos en tiempo real
Serial.println("⏳ Ventana de comandos abierta (15 segundos)...");
unsigned long commandWaitStart = millis();
while (millis() - commandWaitStart < 15000) {
webSocket.loop();
delay(100);
if (Serial.available()) {
handleSerial();
}
}
Serial.println("✅ Ventana de comandos cerrada.");
}
// 7. Marcar como completado
taskCompleted = true;
// 8. Entrar en Deep Sleep (solo si no está desactivado)
if (DEEP_SLEEP_ENABLED && !disableDeepSleep) {
enterDeepSleep(deepSleepDuration);
} else {
Serial.println("💡 Deep Sleep deshabilitado, esperando...");
delay(deepSleepDuration * 1000);
taskCompleted = false; // Repetir ciclo
}
}
// ============================================
// FUNCIONES DE VALIDACIÓN GPIO
// ============================================
// Verificar si un GPIO existe en una lista
bool GPIO_InList(int pin, const int* list, int count) {
for (int i = 0; i < count; i++) {
if (list[i] == pin) return true;
}
return false;
}
// Verificar si un GPIO es válido
bool GPIO_IsValid(int pin) {
return GPIO_InList(pin, ANALOG_GPIOS, ANALOG_GPIOS_COUNT) ||
GPIO_InList(pin, DIGITAL_GPIOS, DIGITAL_GPIOS_COUNT) ||
GPIO_InList(pin, I2C_GPIOS, I2C_GPIOS_COUNT) ||
GPIO_InList(pin, SPI_GPIOS, SPI_GPIOS_COUNT);
}
// Verificar si un GPIO es analógico
bool GPIO_IsAnalog(int pin) {
return GPIO_InList(pin, ANALOG_GPIOS, ANALOG_GPIOS_COUNT);
}
// Verificar si un GPIO es apropiado para un modo específico
bool GPIO_IsAppropriate(int pin, GPIOMode mode) {
bool isAnalog = GPIO_InList(pin, ANALOG_GPIOS, ANALOG_GPIOS_COUNT);
bool isDigital = GPIO_InList(pin, DIGITAL_GPIOS, DIGITAL_GPIOS_COUNT);
switch (mode) {
case MODE_OUTPUT:
case MODE_PWM:
// OUTPUT y PWM: solo digitales (no analógicas)
return isDigital;
case MODE_INPUT:
case MODE_INPUT_PULLUP:
// INPUT: analógicas o digitales
return isAnalog || isDigital;
default:
return false;
}
}
// Aplicar fórmula de conversión a valor analógico
float applyFormula(int rawValue, GPIOConfig& gpio) {
if (!gpio.formulaEnabled || !gpio.isAnalog) {
return (float)rawValue;
}
float voltage = (rawValue * 3.3) / 4095.0;
float normalized = 0;
if (gpio.formulaType == "4-20mA") {
// Sensor 4-20mA con resistencia 250Ω
// Voltaje = Corriente * Resistencia
// Corriente (mA) = Voltaje / 0.250
float current = voltage / 0.250; // mA
// Normalizar: 4mA = 0%, 20mA = 100%
normalized = (current - 4.0) / 16.0;
}
else if (gpio.formulaType == "0-10V") {
// Sensor 0-10V con divisor de voltaje 1:4
// Voltaje real = voltaje leído * 4
float realVoltage = voltage * 4.0;
// Normalizar: 0V = 0%, 10V = 100%
normalized = realVoltage / 10.0;
}
else if (gpio.formulaType == "0-3.3V") {
// Voltaje directo 0-3.3V
normalized = voltage / 3.3;
}
else {
// Custom o desconocido: usar valor RAW normalizado
normalized = rawValue / 4095.0;
}
// Limitar entre 0 y 1
if (normalized < 0) normalized = 0;
if (normalized > 1) normalized = 1;
// Escalar al rango min-max
return gpio.formulaMin + (normalized * (gpio.formulaMax - gpio.formulaMin));
}
// ============================================
// LED RGB
// ============================================
void blinkRGB(uint8_t r, uint8_t g, uint8_t b, int duration) {
#if HAS_RGB_LED
rgbLed.setPixelColor(0, rgbLed.Color(r, g, b));
rgbLed.show();
delay(duration);
rgbLed.clear();
rgbLed.show();
#endif
}
// ============================================
// WIFI
// ============================================
void connectWiFi() {
if (WIFI_SSID.length() == 0) return;
Serial.print("Conectando a WiFi: ");
Serial.println(WIFI_SSID);
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID.c_str(), WIFI_PASS.c_str());
int attempts = 0;
while (WiFi.status() != WL_CONNECTED && attempts < 20) {
delay(500);
Serial.print(".");
attempts++;
}
if (WiFi.status() == WL_CONNECTED) {
Serial.println("\n✅ WiFi conectado");
Serial.print("IP: ");
Serial.println(WiFi.localIP());
// Habilitar WiFi sleep mode para ahorro de energía
WiFi.setSleep(WIFI_PS_MIN_MODEM); // Ahorro moderado, mantiene conexión
Serial.println("💤 WiFi Sleep Mode habilitado");
digitalWrite(LED_STATUS, HIGH);
// Conectar al backend
if (BACKEND_HOST.length() > 0) {
connectWebSocket();
} else {
Serial.println("⚠️ Backend no configurado. Usa: server <host> <port>");
}
} else {
Serial.println("\n❌ Error conectando WiFi");
digitalWrite(LED_STATUS, LOW);
}
}
// ============================================
// WEBSOCKET
// ============================================
void connectWebSocket() {
Serial.print("Conectando a backend: ");
Serial.print(BACKEND_HOST);
Serial.print(":");
Serial.println(BACKEND_PORT);
// Usar SSL para puerto 443, sin SSL para otros puertos
if (BACKEND_PORT == 443) {
Serial.println("Usando conexión SSL (wss://)");
webSocket.beginSSL(BACKEND_HOST.c_str(), BACKEND_PORT, "/ws/device");
} else {
Serial.println("Usando conexión sin SSL (ws://)");
webSocket.begin(BACKEND_HOST.c_str(), BACKEND_PORT, "/ws/device");
}
webSocket.onEvent(webSocketEvent);
webSocket.setReconnectInterval(5000);
// Heartbeat para mantener conexión viva y detectar desconexiones
// Ping cada 15s, timeout 3s, 2 intentos antes de reconectar
webSocket.enableHeartbeat(15000, 3000, 2);
}
void webSocketEvent(WStype_t type, uint8_t* payload, size_t length) {
switch (type) {
case WStype_DISCONNECTED:
Serial.println("📴 WebSocket desconectado");
isRegistered = false;
break;
case WStype_CONNECTED:
Serial.println("🔌 WebSocket conectado");
registerDevice();
break;
case WStype_TEXT:
blinkRGB(0, 0, 255); // Azul: mensaje recibido
handleWebSocketMessage((char*)payload);
break;
case WStype_ERROR:
Serial.println("❌ WebSocket error");
break;
default:
break;
}
}
void registerDevice() {
StaticJsonDocument<512> doc;
doc["type"] = "register";
doc["mac_address"] = deviceMac;
doc["firmware_version"] = FIRMWARE_VERSION;
doc["ip_address"] = WiFi.localIP().toString();
doc["board_model"] = BOARD_MODEL; // 🆕 Enviar modelo de placa
doc["board_family"] = BOARD_FAMILY; // 🆕 Enviar familia del chip
String json;
serializeJson(doc, json);
// Debug: mostrar lo que se envía
Serial.println("📱 Enviando registro al backend:");
Serial.println(json);
webSocket.sendTXT(json);
blinkRGB(0, 255, 0); // Verde: datos enviados
}
void syncTimeWithBackend() {
Serial.println("🕐 Sincronizando hora con el servidor...");
HTTPClient http;
String url = String("http") + (BACKEND_PORT == 443 ? "s" : "") + "://" +
BACKEND_HOST + ":" + String(BACKEND_PORT) + "/api/time";
http.begin(url);
http.setTimeout(5000);
int httpCode = http.GET();
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
StaticJsonDocument<256> doc;
DeserializationError error = deserializeJson(doc, payload);
if (!error) {
unsigned long timestamp = doc["timestamp"];
const char* timezone = doc["timezone"];
if (timezone) {
serverTimezone = String(timezone);
}
// Configurar hora del sistema ESP32 con timezone de Chile
// Chile: UTC-3 (verano feb-mar, sep-nov) o UTC-4 (invierno abr-ago)
// Usamos UTC-3 como default (horario de verano)
long gmtOffset_sec = -3 * 3600; // -3 horas en segundos
int daylightOffset_sec = 0; // Sin DST adicional
configTime(gmtOffset_sec, daylightOffset_sec, "pool.ntp.org");
// Establecer la hora directamente desde el timestamp del servidor (UTC)
struct timeval tv;
tv.tv_sec = timestamp;
tv.tv_usec = 0;
settimeofday(&tv, NULL);
timeSync = true;
lastTimeSync = millis();
Serial.printf("✅ Hora sincronizada: %lu (Timezone: %s)\n", timestamp, serverTimezone.c_str());
// Mostrar hora actual
time_t now = time(nullptr);
Serial.print("📅 Fecha/Hora actual: ");
Serial.println(ctime(&now));
} else {
Serial.println("❌ Error parseando respuesta de tiempo");
}
} else {
Serial.printf("❌ Error obteniendo hora del servidor (HTTP %d)\n", httpCode);
}
http.end();
}
void handleWebSocketMessage(const char* payload) {
StaticJsonDocument<2048> doc;
DeserializationError error = deserializeJson(doc, payload);
if (error) {
Serial.print("Error parseando JSON: ");
Serial.println(error.c_str());
return;
}
const char* type = doc["type"];
if (strcmp(type, "config") == 0) {
handleConfig(doc);
} else if (strcmp(type, "command") == 0) {
handleCommand(doc);
} else if (strcmp(type, "scan_i2c") == 0) {
scanAndReportI2C();
}
}
void handleConfig(JsonDocument& doc) {
deviceId = doc["device_id"];
isRegistered = true;
Serial.print("✅ Registrado como dispositivo ID: ");
Serial.println(deviceId);
// Aplicar sleep_interval si el backend lo envía (viene en ms, convertir a segundos)
if (doc.containsKey("sleep_interval")) {
unsigned long newSleep = doc["sleep_interval"].as<unsigned long>() / 1000;
if (newSleep >= 5) {
deepSleepDuration = newSleep;
preferences.begin("minios", false);
preferences.putUInt("sleep_secs", (uint32_t)deepSleepDuration);
preferences.end();
Serial.printf("⏰ Sleep interval: %lu segundos\n", deepSleepDuration);
}
}
// Sincronizar hora con el servidor
if (!timeSync) {
syncTimeWithBackend();
}
// Configurar GPIOs
JsonArray gpioArray = doc["gpio"].as<JsonArray>();
gpioCount = 0;
for (JsonObject gpio : gpioArray) {
if (gpioCount >= MAX_GPIOS) break;
int pin = gpio["pin"];
String modeStr = gpio["mode"].as<String>();
// Determinar modo
GPIOMode mode;
if (modeStr == "OUTPUT") {
mode = MODE_OUTPUT;
} else if (modeStr == "INPUT") {
mode = MODE_INPUT;
} else if (modeStr == "INPUT_PULLUP") {
mode = MODE_INPUT_PULLUP;
} else if (modeStr == "PWM") {
mode = MODE_PWM;
} else {
Serial.printf("[GPIO] Modo desconocido para pin %d\n", pin);
continue;
}
// Validar pin
if (!GPIO_IsValid(pin)) {
Serial.printf("[GPIO] Pin %d no es válido\n", pin);
continue;
}
if (!GPIO_IsAppropriate(pin, mode)) {
Serial.printf("[GPIO] Pin %d no es apropiado para modo %s\n", pin, modeStr.c_str());
if (GPIO_IsAnalog(pin)) {
Serial.println("[GPIO] Este pin es analógico, solo puede usarse como INPUT");
}
continue;
}
gpios[gpioCount].pin = pin;
gpios[gpioCount].name = gpio["name"].as<String>();
gpios[gpioCount].value = gpio["value"];
gpios[gpioCount].active = gpio["active"];
gpios[gpioCount].loopEnabled = gpio["loop_enabled"];
gpios[gpioCount].loopInterval = gpio["loop_interval"];
gpios[gpioCount].lastLoop = 0;
gpios[gpioCount].isAnalog = GPIO_IsAnalog(pin);
gpios[gpioCount].mode = mode;
// Configuración de fórmulas para sensores analógicos
gpios[gpioCount].formulaEnabled = gpio["formula_enabled"] | false;
gpios[gpioCount].formulaType = gpio["formula_type"].as<String>();
gpios[gpioCount].formulaMin = gpio["formula_min"] | 0.0;
gpios[gpioCount].formulaMax = gpio["formula_max"] | 100.0;
gpios[gpioCount].unit = gpio["unit"].as<String>();
gpios[gpioCount].convertedValue = 0;
// Aplicar configuración física
switch (mode) {
case MODE_OUTPUT:
pinMode(pin, OUTPUT);
digitalWrite(pin, gpios[gpioCount].value);
break;
case MODE_INPUT:
pinMode(pin, INPUT);
break;
case MODE_INPUT_PULLUP:
pinMode(pin, INPUT_PULLUP);
break;
case MODE_PWM:
ledcAttach(pin, 5000, 8);
ledcWrite(pin, gpios[gpioCount].value);
break;
}
gpioCount++;
}
Serial.print("GPIOs configurados: ");
Serial.println(gpioCount);
// Configurar DHT
JsonArray dhtArray = doc["dht"].as<JsonArray>();
// Limpiar sensores anteriores
for (int i = 0; i < dhtCount; i++) {
if (dhtSensors[i].sensor) {
delete dhtSensors[i].sensor;
}
}
dhtCount = 0;
for (JsonObject dht : dhtArray) {
if (dhtCount >= MAX_DHT_SENSORS) break;
int pin = dht["pin"];
String type = dht["sensor_type"].as<String>();
dhtSensors[dhtCount].pin = pin;
dhtSensors[dhtCount].name = dht["name"].as<String>();
dhtSensors[dhtCount].type = type;
dhtSensors[dhtCount].active = dht["active"];
dhtSensors[dhtCount].readInterval = dht["read_interval"] | 5000;
dhtSensors[dhtCount].lastRead = 0;
dhtSensors[dhtCount].temperature = 0;
dhtSensors[dhtCount].humidity = 0;
uint8_t dhtType = (type == "DHT22") ? DHT22 : DHT11;
dhtSensors[dhtCount].sensor = new DHT(pin, dhtType);
dhtSensors[dhtCount].sensor->begin();
dhtCount++;
}
Serial.print("Sensores DHT configurados: ");
Serial.println(dhtCount);
// Configurar sensores I2C
JsonArray i2cArray = doc["i2c"].as<JsonArray>();
// Limpiar sensores anteriores
for (int i = 0; i < i2cCount; i++) {
if (i2cSensors[i].aht) delete i2cSensors[i].aht;
if (i2cSensors[i].bmp) delete i2cSensors[i].bmp;
if (i2cSensors[i].bme) delete i2cSensors[i].bme;
}
i2cCount = 0;
for (JsonObject i2c : i2cArray) {
if (i2cCount >= MAX_I2C_SENSORS) break;
String sensorType = i2c["sensor_type"].as<String>();
uint8_t address = i2c["i2c_address"] | 0x00;
i2cSensors[i2cCount].id = i2c["id"];
i2cSensors[i2cCount].name = i2c["name"].as<String>();
i2cSensors[i2cCount].sensorType = sensorType;
i2cSensors[i2cCount].i2cAddress = address;
i2cSensors[i2cCount].active = i2c["active"] | true;
i2cSensors[i2cCount].readInterval = i2c["read_interval"] | 5000;
i2cSensors[i2cCount].lastRead = 0;
i2cSensors[i2cCount].temperature = 0;
i2cSensors[i2cCount].humidity = 0;
i2cSensors[i2cCount].pressure = 0;