-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMiniOS_WiFi.ino
More file actions
2295 lines (1971 loc) · 84.3 KB
/
Copy pathMiniOS_WiFi.ino
File metadata and controls
2295 lines (1971 loc) · 84.3 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 - Sistema Operativo Minimalista con WiFi para ESP32-S3
* Versión con conectividad WiFi configurable
* Compilar directamente en Arduino IDE
*/
#include <Arduino.h>
#include <WiFi.h>
#include <WebServer.h>
#include <Preferences.h>
#include <DHT.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>
// ============================================
// CONFIGURACIÓN
// ============================================
#define MAX_TASKS 8
#define SERIAL_BAUD 115200
#define AP_SSID "MiniOS-ESP32"
#define AP_PASS "12345678"
#define WEB_PORT 80
// ============================================
// SISTEMA DE TAREAS SIMPLE
// ============================================
struct Task {
void (*function)(); // Función a ejecutar
unsigned long interval; // Intervalo en ms (0 = una vez)
unsigned long lastRun; // Última ejecución
bool active; // Tarea activa
const char* name; // Nombre de la tarea
int priority; // Prioridad (0-3)
};
Task tasks[MAX_TASKS];
int taskCount = 0;
unsigned long systemTime = 0;
// ============================================
// VARIABLES WIFI
// ============================================
WebServer server(WEB_PORT);
Preferences preferences;
String wifiSSID = "";
String wifiPassword = "";
bool wifiConnected = false;
bool apMode = false;
IPAddress localIP;
// ============================================
// SISTEMA DE CONTROL GPIO
// ============================================
#define MAX_GPIOS 10
// GPIOs clasificados por función según ESP32-S3
// GPIOs Analógicas (ADC)
const int ANALOG_GPIOS[] = {1, 2, 4, 5, 6, 7};
const int ANALOG_GPIOS_COUNT = 6;
// GPIOs Digitales (uso general)
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;
// GPIOs I2C (por defecto)
const int I2C_GPIOS[] = {8, 9}; // 8=SDA, 9=SCL
const int I2C_GPIOS_COUNT = 2;
// GPIOs SPI (usar con precaución)
const int SPI_GPIOS[] = {10, 11, 12, 13};
const int SPI_GPIOS_COUNT = 4;
// Modos de GPIO
enum GPIOMode {
GPIO_DISABLED = 0,
GPIO_OUTPUT = 1,
GPIO_INPUT = 2,
GPIO_INPUT_PULLUP = 3,
GPIO_PWM = 4
};
// Estructura de configuración de GPIO
struct GPIOConfig {
int pin; // Número de pin GPIO
GPIOMode mode; // Modo del pin
int value; // Valor actual (0/1 para digital, 0-4095 para analog, 0-255 para PWM)
int pwmChannel; // Canal PWM (0-15 para ESP32)
String name; // Nombre descriptivo
bool active; // Pin configurado
bool loopEnabled; // Parpadeo automático activado (solo OUTPUT)
unsigned long loopInterval; // Intervalo de parpadeo en ms
unsigned long lastToggle; // Última vez que se cambió el estado
// Para lecturas analógicas con conversión
bool hasFormula; // Tiene fórmula de conversión
float multiplier; // Factor de multiplicación (ej: 3.3/4095)
float offset; // Offset a sumar después de multiplicar
String unit; // Unidad de medida (mA, V, °C, etc)
String formulaType; // Tipo de sensor (4-20mA, 0-10V, custom, etc)
float convertedValue; // Valor después de aplicar la fórmula
};
GPIOConfig gpioConfigs[MAX_GPIOS];
int gpioCount = 0;
// ============================================
// SISTEMA DE SENSORES DHT
// ============================================
#define MAX_DHT_SENSORS 4
// Estructura de configuración de sensor DHT
struct DHTConfig {
int pin; // Pin GPIO donde está conectado
DHT* sensor; // Puntero al objeto DHT
String name; // Nombre descriptivo
float temperature; // Última temperatura leída
float humidity; // Última humedad leída
bool active; // Sensor configurado
unsigned long lastRead; // Última lectura
bool lastReadOk; // Última lectura exitosa
};
DHTConfig dhtSensors[MAX_DHT_SENSORS];
int dhtCount = 0;
// ============================================
// SISTEMA DE PANTALLA TFT I2C
// ============================================
// Pines para ST7735 SPI (128x160)
#define TFT_CS 10 // Chip select
#define TFT_RST 9 // Reset
#define TFT_DC 8 // Data/Command
#define TFT_MOSI 11 // SPI MOSI
#define TFT_SCLK 12 // SPI Clock
// Colores comunes
#define TFT_BLACK 0x0000
#define TFT_BLUE 0x001F
#define TFT_RED 0xF800
#define TFT_GREEN 0x07E0
#define TFT_CYAN 0x07FF
#define TFT_MAGENTA 0xF81F
#define TFT_YELLOW 0xFFE0
#define TFT_WHITE 0xFFFF
#define TFT_ORANGE 0xFD20
#define TFT_GREENYELLOW 0xAFE5
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);
bool tftEnabled = false;
bool tftInitialized = false;
uint8_t tftDisplayMode = 0; // 0=Apagado, 1=Info Sistema, 2=Sensores, 3=GPIO, 4=Personalizado
bool tftFirstDraw = true; // Primera vez dibujando la pantalla
// Variables para almacenar valores anteriores (evitar redibujo completo)
struct TFT_LastValues {
unsigned long freeHeap;
float temperature;
unsigned long uptime;
String wifiSSID;
String ipAddress;
int rssi;
bool wifiStatus; // 0=desconectado, 1=conectado, 2=AP
float dhtTemp[MAX_DHT_SENSORS];
float dhtHum[MAX_DHT_SENSORS];
bool dhtStatus[MAX_DHT_SENSORS];
float analogValues[MAX_GPIOS];
};
TFT_LastValues tftLast;
// ============================================
// NÚCLEO DEL OS
// ============================================
// Inicializar sistema
void OS_Init() {
Serial.begin(SERIAL_BAUD);
delay(100);
// Limpiar tareas
for(int i = 0; i < MAX_TASKS; i++) {
tasks[i].active = false;
}
Serial.println("\n╔════════════════════════════╗");
Serial.println("║ MiniOS ESP32-S3 + WiFi ║");
Serial.println("║ Sistema iniciado ║");
Serial.println("╚════════════════════════════╝");
Serial.printf("RAM libre: %d bytes\n", ESP.getFreeHeap());
Serial.printf("CPU: %d MHz\n", ESP.getCpuFreqMHz());
// Inicializar GPIO
GPIO_Init();
// Inicializar DHT
DHT_Init();
// Inicializar pantalla TFT (opcional)
// TFT_Init(); // Descomentar si se tiene pantalla conectada
// Inicializar WiFi
WiFi_Init();
Serial.println("\n📡 Comandos: help, ps, free, temp, wifi, ip, led, reboot");
Serial.println("💡 Use la interfaz web para configurar GPIO y sensores DHT\n");
}
// Añadir tarea
int OS_AddTask(void (*func)(), unsigned long interval, const char* name, int priority = 1) {
if(taskCount >= MAX_TASKS) {
Serial.println("[ERROR] Máximo de tareas alcanzado");
return -1;
}
for(int i = 0; i < MAX_TASKS; i++) {
if(!tasks[i].active) {
tasks[i].function = func;
tasks[i].interval = interval;
tasks[i].lastRun = 0;
tasks[i].active = true;
tasks[i].name = name;
tasks[i].priority = priority;
taskCount++;
Serial.printf("[OS] Tarea '%s' creada (Pri:%d)\n", name, priority);
return i;
}
}
return -1;
}
// Eliminar tarea
void OS_RemoveTask(int id) {
if(id >= 0 && id < MAX_TASKS && tasks[id].active) {
Serial.printf("[OS] Tarea '%s' eliminada\n", tasks[id].name);
tasks[id].active = false;
taskCount--;
}
}
// Scheduler simple con prioridades
void OS_Run() {
systemTime = millis();
// Ejecutar tareas por prioridad (3 = alta, 0 = baja)
for(int priority = 3; priority >= 0; priority--) {
for(int i = 0; i < MAX_TASKS; i++) {
if(tasks[i].active && tasks[i].priority == priority) {
// Verificar si toca ejecutar
if(tasks[i].interval == 0) {
// Ejecutar una sola vez
tasks[i].function();
tasks[i].active = false;
taskCount--;
} else if(systemTime - tasks[i].lastRun >= tasks[i].interval) {
// Ejecutar periódicamente
tasks[i].function();
tasks[i].lastRun = systemTime;
}
}
}
}
}
// ============================================
// FUNCIONES DE CONTROL 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 (existe en alguna categoría)
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 apropiado para un modo específico
bool GPIO_IsAppropriate(int pin, GPIOMode mode) {
// GPIOs analógicas solo para INPUT
bool isAnalog = GPIO_InList(pin, ANALOG_GPIOS, ANALOG_GPIOS_COUNT);
bool isDigital = GPIO_InList(pin, DIGITAL_GPIOS, DIGITAL_GPIOS_COUNT);
bool isSPI = GPIO_InList(pin, SPI_GPIOS, SPI_GPIOS_COUNT);
switch(mode) {
case GPIO_OUTPUT:
case GPIO_PWM:
// OUTPUT y PWM: solo digitales (no analógicas, no SPI por seguridad)
return isDigital;
case GPIO_INPUT:
case GPIO_INPUT_PULLUP:
// INPUT: analógicas o digitales (no SPI por seguridad)
return isAnalog || isDigital;
default:
return false;
}
}
// Mantener compatibilidad - verificar si GPIO es válido
bool GPIO_IsSafe(int pin) {
return GPIO_IsValid(pin);
}
// Obtener lista de GPIOs actualmente en uso
void GPIO_GetInUse(int* inUseList, int* count) {
*count = 0;
// Pines de pantalla TFT (si está inicializada)
if(tftInitialized) {
inUseList[(*count)++] = TFT_CS; // 10
inUseList[(*count)++] = TFT_DC; // 8
inUseList[(*count)++] = TFT_RST; // 9
inUseList[(*count)++] = TFT_MOSI; // 11
inUseList[(*count)++] = TFT_SCLK; // 12
}
// Pines configurados como GPIO
for(int i = 0; i < MAX_GPIOS; i++) {
if(gpioConfigs[i].active) {
inUseList[(*count)++] = gpioConfigs[i].pin;
}
}
// Pines usados por sensores DHT
for(int i = 0; i < MAX_DHT_SENSORS; i++) {
if(dhtSensors[i].active) {
inUseList[(*count)++] = dhtSensors[i].pin;
}
}
}
// Verificar si un pin está en uso
bool GPIO_IsInUse(int pin) {
int inUseList[50];
int count = 0;
GPIO_GetInUse(inUseList, &count);
for(int i = 0; i < count; i++) {
if(inUseList[i] == pin) return true;
}
return false;
}
// Inicializar sistema GPIO
void GPIO_Init() {
// Limpiar configuraciones
for(int i = 0; i < MAX_GPIOS; i++) {
gpioConfigs[i].active = false;
gpioConfigs[i].pin = -1;
gpioConfigs[i].mode = GPIO_DISABLED;
gpioConfigs[i].value = 0;
gpioConfigs[i].pwmChannel = -1;
gpioConfigs[i].name = "";
gpioConfigs[i].loopEnabled = false;
gpioConfigs[i].loopInterval = 500;
gpioConfigs[i].lastToggle = 0;
gpioConfigs[i].hasFormula = false;
gpioConfigs[i].multiplier = 1.0;
gpioConfigs[i].offset = 0.0;
gpioConfigs[i].unit = "";
gpioConfigs[i].formulaType = "";
gpioConfigs[i].convertedValue = 0.0;
}
gpioCount = 0;
// Cargar configuración desde NVS
GPIO_LoadConfig();
Serial.printf("[GPIO] Sistema inicializado (%d pines configurados)\n", gpioCount);
}
// Guardar configuración en NVS
void GPIO_SaveConfig() {
preferences.begin("gpio", false);
preferences.putInt("count", gpioCount);
for(int i = 0; i < MAX_GPIOS; i++) {
if(gpioConfigs[i].active) {
String prefix = "g" + String(i) + "_";
preferences.putInt((prefix + "pin").c_str(), gpioConfigs[i].pin);
preferences.putInt((prefix + "mode").c_str(), (int)gpioConfigs[i].mode);
preferences.putInt((prefix + "val").c_str(), gpioConfigs[i].value);
preferences.putString((prefix + "name").c_str(), gpioConfigs[i].name);
preferences.putBool((prefix + "loop").c_str(), gpioConfigs[i].loopEnabled);
preferences.putUInt((prefix + "intv").c_str(), gpioConfigs[i].loopInterval);
// Guardar parámetros de fórmula
preferences.putBool((prefix + "hasf").c_str(), gpioConfigs[i].hasFormula);
if(gpioConfigs[i].hasFormula) {
preferences.putFloat((prefix + "mult").c_str(), gpioConfigs[i].multiplier);
preferences.putFloat((prefix + "offs").c_str(), gpioConfigs[i].offset);
preferences.putString((prefix + "unit").c_str(), gpioConfigs[i].unit);
preferences.putString((prefix + "ftyp").c_str(), gpioConfigs[i].formulaType);
}
}
}
preferences.end();
Serial.println("[GPIO] Configuración guardada");
}
// Cargar configuración desde NVS
void GPIO_LoadConfig() {
preferences.begin("gpio", true); // read-only
int savedCount = preferences.getInt("count", 0);
for(int i = 0; i < MAX_GPIOS && i < savedCount; i++) {
String prefix = "g" + String(i) + "_";
int pin = preferences.getInt((prefix + "pin").c_str(), -1);
if(pin >= 0 && GPIO_IsSafe(pin)) {
gpioConfigs[i].pin = pin;
gpioConfigs[i].mode = (GPIOMode)preferences.getInt((prefix + "mode").c_str(), 0);
gpioConfigs[i].value = preferences.getInt((prefix + "val").c_str(), 0);
gpioConfigs[i].name = preferences.getString((prefix + "name").c_str(), "GPIO" + String(pin));
gpioConfigs[i].loopEnabled = preferences.getBool((prefix + "loop").c_str(), false);
gpioConfigs[i].loopInterval = preferences.getUInt((prefix + "intv").c_str(), 500);
gpioConfigs[i].lastToggle = 0;
// Cargar parámetros de fórmula
gpioConfigs[i].hasFormula = preferences.getBool((prefix + "hasf").c_str(), false);
if(gpioConfigs[i].hasFormula) {
gpioConfigs[i].multiplier = preferences.getFloat((prefix + "mult").c_str(), 1.0);
gpioConfigs[i].offset = preferences.getFloat((prefix + "offs").c_str(), 0.0);
gpioConfigs[i].unit = preferences.getString((prefix + "unit").c_str(), "");
gpioConfigs[i].formulaType = preferences.getString((prefix + "ftyp").c_str(), "");
}
gpioConfigs[i].active = true;
// Aplicar configuración al pin
GPIO_ApplyConfig(i);
gpioCount++;
}
}
preferences.end();
}
// Aplicar configuración física a un pin
void GPIO_ApplyConfig(int index) {
if(index < 0 || index >= MAX_GPIOS || !gpioConfigs[index].active) return;
GPIOConfig &cfg = gpioConfigs[index];
switch(cfg.mode) {
case GPIO_OUTPUT:
pinMode(cfg.pin, OUTPUT);
digitalWrite(cfg.pin, cfg.value);
break;
case GPIO_INPUT:
pinMode(cfg.pin, INPUT);
break;
case GPIO_INPUT_PULLUP:
pinMode(cfg.pin, INPUT_PULLUP);
break;
case GPIO_PWM:
// ESP32 Core 3.x usa ledcAttach directamente (sin canales)
ledcAttach(cfg.pin, 5000, 8); // 5 KHz, 8 bits
ledcWrite(cfg.pin, cfg.value);
break;
default:
break;
}
}
// Configurar un GPIO
int GPIO_Configure(int pin, GPIOMode mode, String name = "") {
if(!GPIO_IsValid(pin)) {
Serial.printf("[GPIO] ⚠️ GPIO %d no existe o no está disponible\n", pin);
return -1;
}
if(!GPIO_IsAppropriate(pin, mode)) {
Serial.printf("[GPIO] ⚠️ GPIO %d no es apropiado para este modo\n", pin);
if(GPIO_InList(pin, ANALOG_GPIOS, ANALOG_GPIOS_COUNT)) {
Serial.println("[GPIO] Este pin es analógico, solo puede usarse como INPUT");
} else if(GPIO_InList(pin, SPI_GPIOS, SPI_GPIOS_COUNT)) {
Serial.println("[GPIO] Este pin es SPI, se recomienda no usarlo");
}
return -1;
}
// Buscar si ya existe como GPIO configurado
bool alreadyConfigured = false;
for(int i = 0; i < MAX_GPIOS; i++) {
if(gpioConfigs[i].active && gpioConfigs[i].pin == pin) {
alreadyConfigured = true;
break;
}
}
// Si no está configurado como GPIO, verificar si está en uso por otra cosa
if(!alreadyConfigured && GPIO_IsInUse(pin)) {
Serial.printf("[GPIO] ⚠️ GPIO %d ya está en uso\n", pin);
if(tftInitialized && (pin == TFT_CS || pin == TFT_DC || pin == TFT_RST || pin == TFT_MOSI || pin == TFT_SCLK)) {
Serial.println("[GPIO] Este pin está siendo usado por la pantalla TFT");
}
for(int i = 0; i < MAX_DHT_SENSORS; i++) {
if(dhtSensors[i].active && dhtSensors[i].pin == pin) {
Serial.printf("[GPIO] Este pin está siendo usado por sensor DHT: %s\n", dhtSensors[i].name.c_str());
}
}
return -1;
}
// Buscar si ya existe para actualizar
for(int i = 0; i < MAX_GPIOS; i++) {
if(gpioConfigs[i].active && gpioConfigs[i].pin == pin) {
// Actualizar configuración existente
gpioConfigs[i].mode = mode;
if(name.length() > 0) gpioConfigs[i].name = name;
GPIO_ApplyConfig(i);
GPIO_SaveConfig();
Serial.printf("[GPIO] Pin %d actualizado\n", pin);
return i;
}
}
// Crear nueva configuración
if(gpioCount >= MAX_GPIOS) {
Serial.println("[GPIO] Máximo de pines alcanzado");
return -1;
}
for(int i = 0; i < MAX_GPIOS; i++) {
if(!gpioConfigs[i].active) {
gpioConfigs[i].pin = pin;
gpioConfigs[i].mode = mode;
gpioConfigs[i].value = 0;
gpioConfigs[i].pwmChannel = -1;
gpioConfigs[i].name = (name.length() > 0) ? name : "GPIO" + String(pin);
gpioConfigs[i].active = true;
gpioCount++;
GPIO_ApplyConfig(i);
GPIO_SaveConfig();
Serial.printf("[GPIO] Pin %d configurado como %s\n", pin,
mode == GPIO_OUTPUT ? "OUTPUT" :
mode == GPIO_INPUT ? "INPUT" :
mode == GPIO_INPUT_PULLUP ? "INPUT_PULLUP" :
mode == GPIO_PWM ? "PWM" : "DISABLED");
return i;
}
}
return -1;
}
// Escribir valor digital a un GPIO
bool GPIO_DigitalWrite(int pin, int value) {
for(int i = 0; i < MAX_GPIOS; i++) {
if(gpioConfigs[i].active && gpioConfigs[i].pin == pin) {
if(gpioConfigs[i].mode == GPIO_OUTPUT) {
digitalWrite(pin, value);
gpioConfigs[i].value = value;
return true;
}
}
}
return false;
}
// Leer valor de un GPIO (digital o analógico)
int GPIO_DigitalRead(int pin) {
for(int i = 0; i < MAX_GPIOS; i++) {
if(gpioConfigs[i].active && gpioConfigs[i].pin == pin) {
if(gpioConfigs[i].mode == GPIO_INPUT || gpioConfigs[i].mode == GPIO_INPUT_PULLUP) {
// Verificar si es pin analógico
bool isAnalog = GPIO_InList(pin, ANALOG_GPIOS, ANALOG_GPIOS_COUNT);
if(isAnalog) {
// Leer valor analógico (0-4095 en ESP32)
int rawValue = analogRead(pin);
gpioConfigs[i].value = rawValue;
// Aplicar fórmula si está configurada
if(gpioConfigs[i].hasFormula) {
gpioConfigs[i].convertedValue = (rawValue * gpioConfigs[i].multiplier) + gpioConfigs[i].offset;
} else {
gpioConfigs[i].convertedValue = rawValue;
}
} else {
// Leer valor digital
int value = digitalRead(pin);
gpioConfigs[i].value = value;
gpioConfigs[i].convertedValue = value;
}
return gpioConfigs[i].value;
}
}
}
return -1;
}
// Escribir valor PWM a un GPIO
bool GPIO_PWMWrite(int pin, int value) {
if(value < 0) value = 0;
if(value > 255) value = 255;
for(int i = 0; i < MAX_GPIOS; i++) {
if(gpioConfigs[i].active && gpioConfigs[i].pin == pin) {
if(gpioConfigs[i].mode == GPIO_PWM) {
ledcWrite(pin, value); // ESP32 Core 3.x usa el pin directamente
gpioConfigs[i].value = value;
return true;
}
}
}
return false;
}
// Eliminar configuración de un GPIO
bool GPIO_Remove(int pin) {
for(int i = 0; i < MAX_GPIOS; i++) {
if(gpioConfigs[i].active && gpioConfigs[i].pin == pin) {
// Limpiar PWM si aplica
if(gpioConfigs[i].mode == GPIO_PWM) {
ledcDetach(gpioConfigs[i].pin); // ESP32 Core 3.x
}
gpioConfigs[i].active = false;
gpioConfigs[i].pin = -1;
gpioCount--;
GPIO_SaveConfig();
Serial.printf("[GPIO] Pin %d eliminado\n", pin);
return true;
}
}
return false;
}
// Obtener estado de todos los GPIOs (para API)
String GPIO_GetStatusJSON() {
String json = "[";
bool first = true;
for(int i = 0; i < MAX_GPIOS; i++) {
if(gpioConfigs[i].active) {
if(!first) json += ",";
first = false;
// Leer valor actual si es entrada
if(gpioConfigs[i].mode == GPIO_INPUT || gpioConfigs[i].mode == GPIO_INPUT_PULLUP) {
GPIO_DigitalRead(gpioConfigs[i].pin);
}
json += "{";
json += "\"pin\":" + String(gpioConfigs[i].pin) + ",";
json += "\"name\":\"" + gpioConfigs[i].name + "\",";
json += "\"mode\":" + String((int)gpioConfigs[i].mode) + ",";
json += "\"value\":" + String(gpioConfigs[i].value) + ",";
json += "\"loop\":" + String(gpioConfigs[i].loopEnabled ? "true" : "false") + ",";
json += "\"interval\":" + String(gpioConfigs[i].loopInterval) + ",";
// Información de fórmula
json += "\"hasFormula\":" + String(gpioConfigs[i].hasFormula ? "true" : "false");
if(gpioConfigs[i].hasFormula) {
json += ",\"convertedValue\":" + String(gpioConfigs[i].convertedValue, 3);
json += ",\"unit\":\"" + gpioConfigs[i].unit + "\"";
json += ",\"formulaType\":\"" + gpioConfigs[i].formulaType + "\"";
}
json += "}";
}
}
json += "]";
return json;
}
// Activar/desactivar modo loop en un GPIO OUTPUT
bool GPIO_SetLoop(int pin, bool enabled, unsigned long interval = 500) {
for(int i = 0; i < MAX_GPIOS; i++) {
if(gpioConfigs[i].active && gpioConfigs[i].pin == pin) {
if(gpioConfigs[i].mode == GPIO_OUTPUT) {
gpioConfigs[i].loopEnabled = enabled;
if(interval > 0) {
gpioConfigs[i].loopInterval = interval;
}
gpioConfigs[i].lastToggle = millis();
GPIO_SaveConfig();
return true;
}
}
}
return false;
}
// Tarea para manejar el parpadeo automático de GPIOs
void taskGPIOBlink() {
unsigned long now = millis();
for(int i = 0; i < MAX_GPIOS; i++) {
if(gpioConfigs[i].active &&
gpioConfigs[i].mode == GPIO_OUTPUT &&
gpioConfigs[i].loopEnabled) {
// Verificar si toca cambiar el estado
if(now - gpioConfigs[i].lastToggle >= gpioConfigs[i].loopInterval) {
// Toggle del pin
gpioConfigs[i].value = !gpioConfigs[i].value;
digitalWrite(gpioConfigs[i].pin, gpioConfigs[i].value);
gpioConfigs[i].lastToggle = now;
}
}
}
}
// ============================================
// FUNCIONES DE CONTROL DHT
// ============================================
// Inicializar sistema DHT
void DHT_Init() {
// Limpiar configuraciones
for(int i = 0; i < MAX_DHT_SENSORS; i++) {
dhtSensors[i].active = false;
dhtSensors[i].pin = -1;
dhtSensors[i].sensor = nullptr;
dhtSensors[i].name = "";
dhtSensors[i].temperature = 0.0;
dhtSensors[i].humidity = 0.0;
dhtSensors[i].lastRead = 0;
dhtSensors[i].lastReadOk = false;
}
dhtCount = 0;
// Cargar configuración desde NVS
DHT_LoadConfig();
Serial.printf("[DHT] Sistema inicializado (%d sensores configurados)\n", dhtCount);
}
// Guardar configuración en NVS
void DHT_SaveConfig() {
preferences.begin("dht", false);
preferences.putInt("count", dhtCount);
for(int i = 0; i < MAX_DHT_SENSORS; i++) {
if(dhtSensors[i].active) {
String prefix = "d" + String(i) + "_";
preferences.putInt((prefix + "pin").c_str(), dhtSensors[i].pin);
preferences.putString((prefix + "name").c_str(), dhtSensors[i].name);
}
}
preferences.end();
Serial.println("[DHT] Configuración guardada");
}
// Cargar configuración desde NVS
void DHT_LoadConfig() {
preferences.begin("dht", true); // read-only
int savedCount = preferences.getInt("count", 0);
for(int i = 0; i < MAX_DHT_SENSORS && i < savedCount; i++) {
String prefix = "d" + String(i) + "_";
int pin = preferences.getInt((prefix + "pin").c_str(), -1);
if(pin >= 0 && GPIO_IsSafe(pin)) {
dhtSensors[i].pin = pin;
dhtSensors[i].name = preferences.getString((prefix + "name").c_str(), "DHT11-" + String(pin));
dhtSensors[i].sensor = new DHT(pin, DHT11);
dhtSensors[i].sensor->begin();
dhtSensors[i].active = true;
dhtSensors[i].lastReadOk = false;
dhtCount++;
Serial.printf("[DHT] Sensor cargado en GPIO %d\n", pin);
}
}
preferences.end();
}
// Configurar un nuevo sensor DHT
int DHT_Configure(int pin, String name = "") {
if(!GPIO_IsSafe(pin)) {
Serial.printf("[DHT] ⚠️ GPIO %d no es seguro\n", pin);
return -1;
}
// Verificar si el pin ya está en uso como DHT
bool alreadyDHT = false;
for(int i = 0; i < MAX_DHT_SENSORS; i++) {
if(dhtSensors[i].active && dhtSensors[i].pin == pin) {
alreadyDHT = true;
Serial.printf("[DHT] Pin %d ya está configurado como DHT\n", pin);
return -1;
}
}
// Verificar si está en uso por otra cosa
if(GPIO_IsInUse(pin)) {
Serial.printf("[DHT] ⚠️ GPIO %d ya está en uso\n", pin);
if(tftInitialized && (pin == TFT_CS || pin == TFT_DC || pin == TFT_RST || pin == TFT_MOSI || pin == TFT_SCLK)) {
Serial.println("[DHT] Este pin está siendo usado por la pantalla TFT");
}
for(int i = 0; i < MAX_GPIOS; i++) {
if(gpioConfigs[i].active && gpioConfigs[i].pin == pin) {
Serial.printf("[DHT] Este pin está siendo usado como GPIO: %s\n", gpioConfigs[i].name.c_str());
}
}
return -1;
}
// Buscar espacio libre
if(dhtCount >= MAX_DHT_SENSORS) {
Serial.println("[DHT] Máximo de sensores alcanzado");
return -1;
}
for(int i = 0; i < MAX_DHT_SENSORS; i++) {
if(!dhtSensors[i].active) {
dhtSensors[i].pin = pin;
dhtSensors[i].name = (name.length() > 0) ? name : "DHT11-" + String(pin);
dhtSensors[i].sensor = new DHT(pin, DHT11);
dhtSensors[i].sensor->begin();
dhtSensors[i].active = true;
dhtSensors[i].temperature = 0.0;
dhtSensors[i].humidity = 0.0;
dhtSensors[i].lastRead = 0;
dhtSensors[i].lastReadOk = false;
dhtCount++;
DHT_SaveConfig();
Serial.printf("[DHT] Sensor DHT11 configurado en GPIO %d\n", pin);
return i;
}
}
return -1;
}
// Leer datos de un sensor DHT
bool DHT_Read(int index) {
if(index < 0 || index >= MAX_DHT_SENSORS || !dhtSensors[index].active) {
return false;
}
float h = dhtSensors[index].sensor->readHumidity();
float t = dhtSensors[index].sensor->readTemperature();
// Verificar si la lectura es válida
if(isnan(h) || isnan(t)) {
dhtSensors[index].lastReadOk = false;
return false;
}
dhtSensors[index].humidity = h;
dhtSensors[index].temperature = t;
dhtSensors[index].lastRead = millis();
dhtSensors[index].lastReadOk = true;
return true;
}
// Eliminar un sensor DHT
bool DHT_Remove(int pin) {
for(int i = 0; i < MAX_DHT_SENSORS; i++) {
if(dhtSensors[i].active && dhtSensors[i].pin == pin) {
// Liberar memoria del sensor
if(dhtSensors[i].sensor != nullptr) {
delete dhtSensors[i].sensor;
dhtSensors[i].sensor = nullptr;
}
dhtSensors[i].active = false;
dhtSensors[i].pin = -1;
dhtCount--;
DHT_SaveConfig();
Serial.printf("[DHT] Sensor en GPIO %d eliminado\n", pin);
return true;
}
}
return false;
}
// Obtener estado de todos los sensores DHT (para API)
String DHT_GetStatusJSON() {
String json = "[";
bool first = true;
for(int i = 0; i < MAX_DHT_SENSORS; i++) {
if(dhtSensors[i].active) {
if(!first) json += ",";
first = false;
json += "{";
json += "\"pin\":" + String(dhtSensors[i].pin) + ",";
json += "\"name\":\"" + dhtSensors[i].name + "\",";
json += "\"temperature\":" + String(dhtSensors[i].temperature, 1) + ",";
json += "\"humidity\":" + String(dhtSensors[i].humidity, 1) + ",";
json += "\"lastRead\":" + String(dhtSensors[i].lastRead) + ",";
json += "\"status\":\"" + String(dhtSensors[i].lastReadOk ? "ok" : "error") + "\"";
json += "}";
}
}
json += "]";
return json;
}
// Tarea para leer sensores DHT periódicamente
void taskDHTRead() {
for(int i = 0; i < MAX_DHT_SENSORS; i++) {
if(dhtSensors[i].active) {
DHT_Read(i);
}
}
}
// ============================================
// FUNCIONES DE PANTALLA TFT
// ============================================
// Inicializar pantalla TFT
bool TFT_Init() {
if(tftInitialized) return true;
Serial.println("[TFT] Inicializando pantalla...");
tft.initR(INITR_BLACKTAB); // Inicializar ST7735 (128x160)
tft.setRotation(1); // Horizontal
tft.fillScreen(TFT_BLACK);
tftInitialized = true;
tftEnabled = true;
Serial.println("[TFT] Pantalla inicializada");
return true;
}
// Apagar pantalla
void TFT_Off() {
if(!tftInitialized) return;
tft.fillScreen(TFT_BLACK);
tftEnabled = false;
tftDisplayMode = 0;
tftFirstDraw = true; // Forzar redibujo completo al volver a encender
}
// Borrar y redibujar solo un valor en la pantalla
void TFT_UpdateValue(int y, int x, String newValue, uint16_t color = TFT_WHITE) {
// Borrar área del valor anterior (desde x hasta final de línea)
tft.fillRect(x, y, 160 - x, 8, TFT_BLACK);
// Escribir nuevo valor
tft.setCursor(x, y);
tft.setTextColor(color);
tft.setTextSize(1);
tft.print(newValue);
}
// Mostrar información del sistema (actualización optimizada)
void TFT_ShowSystemInfo() {
if(!tftInitialized || !tftEnabled) return;
unsigned long freeHeap = ESP.getFreeHeap();
float temperature = temperatureRead();
unsigned long uptime = millis() / 1000;
String ipAddr = wifiConnected ? WiFi.localIP().toString() : (apMode ? WiFi.softAPIP().toString() : "");
String ssid = wifiConnected ? WiFi.SSID() : (apMode ? String(AP_SSID) : "");
int rssi = wifiConnected ? WiFi.RSSI() : 0;
// Si es primera vez, dibujar todo
if(tftFirstDraw) {
tft.fillScreen(TFT_BLACK);
tft.setTextSize(1);
// Título
tft.setCursor(0, 0);
tft.setTextColor(TFT_CYAN);
tft.setTextSize(2);
tft.println("MiniOS");
// Etiquetas estáticas
tft.setTextSize(1);
tft.setTextColor(TFT_WHITE);
tft.setCursor(0, 20);