forked from melkati/CO2-Gadget
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CO2_Gadget_WIFI.h
1552 lines (1440 loc) · 59.6 KB
/
CO2_Gadget_WIFI.h
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
#ifndef CO2_Gadget_WIFI
#define CO2_Gadget_WIFI
// clang-format off
/*****************************************************************************************************/
/********* *********/
/********* SETUP WIFI *********/
/********* *********/
/*****************************************************************************************************/
// clang-format on
#include <Arduino.h>
#ifdef SUPPORT_CAPTIVE_PORTAL
DNSServer dnsServer;
#endif
WiFiClient espClient;
AsyncWebServer server(80);
void printSmallChar(char c, int row) {
switch (c) {
case '0':
switch (row) {
case 0:
Serial.print(" 000 ");
break;
case 1:
Serial.print("0 0");
break;
case 2:
Serial.print("0 0");
break;
case 3:
Serial.print("0 0");
break;
case 4:
Serial.print(" 000 ");
break;
}
break;
case '1':
switch (row) {
case 0:
Serial.print(" 1 ");
break;
case 1:
Serial.print(" 11 ");
break;
case 2:
Serial.print(" 1 ");
break;
case 3:
Serial.print(" 1 ");
break;
case 4:
Serial.print(" 111 ");
break;
}
break;
case '2':
switch (row) {
case 0:
Serial.print(" 222 ");
break;
case 1:
Serial.print(" 2");
break;
case 2:
Serial.print(" 22 ");
break;
case 3:
Serial.print(" 2 ");
break;
case 4:
Serial.print(" 2222");
break;
}
break;
case '3':
switch (row) {
case 0:
Serial.print(" 333 ");
break;
case 1:
Serial.print(" 3");
break;
case 2:
Serial.print(" 33 ");
break;
case 3:
Serial.print(" 3");
break;
case 4:
Serial.print(" 333 ");
break;
}
break;
case '4':
switch (row) {
case 0:
Serial.print("4 4");
break;
case 1:
Serial.print("4 4");
break;
case 2:
Serial.print("44444");
break;
case 3:
Serial.print(" 4");
break;
case 4:
Serial.print(" 4");
break;
}
break;
case '5':
switch (row) {
case 0:
Serial.print("55555");
break;
case 1:
Serial.print("5 ");
break;
case 2:
Serial.print("555 ");
break;
case 3:
Serial.print(" 5");
break;
case 4:
Serial.print("555 ");
break;
}
break;
case '6':
switch (row) {
case 0:
Serial.print(" 666 ");
break;
case 1:
Serial.print("6 ");
break;
case 2:
Serial.print("6666 ");
break;
case 3:
Serial.print("6 6");
break;
case 4:
Serial.print(" 666 ");
break;
}
break;
case '7':
switch (row) {
case 0:
Serial.print("77777");
break;
case 1:
Serial.print(" 7");
break;
case 2:
Serial.print(" 7 ");
break;
case 3:
Serial.print(" 7 ");
break;
case 4:
Serial.print(" 7 ");
break;
}
break;
case '8':
switch (row) {
case 0:
Serial.print(" 888 ");
break;
case 1:
Serial.print("8 8");
break;
case 2:
Serial.print(" 888 ");
break;
case 3:
Serial.print("8 8");
break;
case 4:
Serial.print(" 888 ");
break;
}
break;
case '9':
switch (row) {
case 0:
Serial.print(" 999 ");
break;
case 1:
Serial.print("9 9");
break;
case 2:
Serial.print(" 9999");
break;
case 3:
Serial.print(" 9");
break;
case 4:
Serial.print(" 999 ");
break;
}
break;
case '.':
switch (row) {
case 0:
Serial.print(" ");
break;
case 1:
Serial.print(" ");
break;
case 2:
Serial.print(" ");
break;
case 3:
Serial.print(" ");
break;
case 4:
Serial.print(" o ");
break;
}
break;
default:
Serial.print(" "); // Default character for unhandled
break;
}
}
void printLargeASCII(const char *text) {
for (int row = 0; row < 5; row++) { // 5 rows for each character
for (int i = 0; i < strlen(text); i++) {
printSmallChar(text[i], row);
Serial.print(" "); // Space between characters
}
Serial.println(); // New line after each row of characters
}
}
void onWifiSettingsChanged(std::string ssid, std::string password) {
#ifdef WIFI_PRIVACY
Serial.print("-->[WiFi] onWifiSettingsChanged() (SSID: ");
Serial.print(ssid.c_str());
Serial.println(")");
#else
Serial.print("-->[WiFi] onWifiSettingsChanged() (SSID: ");
Serial.print(ssid.c_str());
Serial.print(", Password: ");
Serial.print(password.c_str());
Serial.println(")");
#endif
WiFi.begin(ssid.c_str(), password.c_str());
}
String getMACAddressAsString() {
byte mac[6];
WiFi.macAddress(mac);
String macAddress = String(mac[5], HEX) + ":" +
String(mac[4], HEX) + ":" +
String(mac[3], HEX) + ":" +
String(mac[2], HEX) + ":" +
String(mac[1], HEX) + ":" +
String(mac[0], HEX);
return macAddress;
}
void printDisconnectReason(int reasonCode) {
#ifdef DEBUG_WIFI_EVENTS
switch (reasonCode) {
case WIFI_REASON_UNSPECIFIED:
Serial.println("-->[WiFi-event] Unspecified error");
break;
case WIFI_REASON_AUTH_EXPIRE:
Serial.println("-->[WiFi-event] Authentication expired");
break;
case WIFI_REASON_AUTH_LEAVE:
Serial.println("-->[WiFi-event] Authentication left");
break;
case WIFI_REASON_ASSOC_EXPIRE:
Serial.println("-->[WiFi-event] Association expired");
break;
case WIFI_REASON_ASSOC_TOOMANY:
Serial.println("-->[WiFi-event] Too many associations");
break;
case WIFI_REASON_NOT_AUTHED:
Serial.println("-->[WiFi-event] Not authenticated");
break;
case WIFI_REASON_NOT_ASSOCED:
Serial.println("-->[WiFi-event] Not associated");
break;
case WIFI_REASON_ASSOC_LEAVE:
Serial.println("-->[WiFi-event] Association left");
break;
case WIFI_REASON_ASSOC_NOT_AUTHED:
Serial.println("-->[WiFi-event] Association not authenticated");
break;
case WIFI_REASON_DISASSOC_PWRCAP_BAD:
Serial.println("-->[WiFi-event] Disassociation power capability invalid");
break;
case WIFI_REASON_DISASSOC_SUPCHAN_BAD:
Serial.println("-->[WiFi-event] Disassociation supported channel invalid");
break;
case WIFI_REASON_IE_INVALID:
Serial.println("-->[WiFi-event] Invalid IE");
break;
case WIFI_REASON_MIC_FAILURE:
Serial.println("-->[WiFi-event] MIC failure");
break;
case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT:
Serial.println("-->[WiFi-event] 4-way handshake timeout");
break;
case WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT:
Serial.println("-->[WiFi-event] Group key update timeout");
break;
case WIFI_REASON_IE_IN_4WAY_DIFFERS:
Serial.println("-->[WiFi-event] IE in 4-way differs");
break;
case WIFI_REASON_GROUP_CIPHER_INVALID:
Serial.println("-->[WiFi-event] Invalid group cipher");
break;
case WIFI_REASON_PAIRWISE_CIPHER_INVALID:
Serial.println("-->[WiFi-event] Invalid pairwise cipher");
break;
case WIFI_REASON_AKMP_INVALID:
Serial.println("-->[WiFi-event] Invalid AKMP");
break;
case WIFI_REASON_UNSUPP_RSN_IE_VERSION:
Serial.println("-->[WiFi-event] Unsupported RSN IE version");
break;
case WIFI_REASON_INVALID_RSN_IE_CAP:
Serial.println("-->[WiFi-event] Invalid RSN IE capabilities");
break;
case WIFI_REASON_802_1X_AUTH_FAILED:
Serial.println("-->[WiFi-event] 802.1X authentication failed");
break;
case WIFI_REASON_CIPHER_SUITE_REJECTED:
Serial.println("-->[WiFi-event] Cipher suite rejected");
break;
case WIFI_REASON_BEACON_TIMEOUT:
Serial.println("-->[WiFi-event] Beacon timeout");
break;
case WIFI_REASON_NO_AP_FOUND:
Serial.println("-->[WiFi-event] No AP found");
break;
case WIFI_REASON_AUTH_FAIL:
Serial.println("-->[WiFi-event] Authentication failed");
break;
case WIFI_REASON_ASSOC_FAIL:
Serial.println("-->[WiFi-event] Association failed");
break;
case WIFI_REASON_HANDSHAKE_TIMEOUT:
Serial.println("-->[WiFi-event] Handshake timeout");
break;
default:
Serial.println("-->[WiFi-event] Unknown reason");
break;
}
#endif // DEBUG_WIFI_EVENTS
}
void printWiFiStatus() { // Print wifi status on serial monitor
// Get current status
// WL_CONNECTED: assigned when connected to a WiFi network;
// WL_NO_SHIELD: assigned when no WiFi shield is present;
// WL_IDLE_STATUS: it is a temporary status assigned when WiFi.begin() is called and remains active until the number of attempts expires (resulting in WL_CONNECT_FAILED) or a connection is established (resulting in WL_CONNECTED);
// WL_NO_SSID_AVAIL: assigned when no SSID are available;
// WL_SCAN_COMPLETED: assigned when the scan networks is completed;
// WL_CONNECT_FAILED: assigned when the connection fails for all the attempts;
// WL_CONNECTION_LOST: assigned when the connection is lost;
// WL_DISCONNECTED: assigned when disconnected from a network;
Serial.print("-->[WiFi-Status] ");
switch (WiFi.status()) {
case WL_CONNECTED:
Serial.println("WiFi connected");
break;
case WL_NO_SHIELD:
Serial.println("No WiFi HW detected");
break;
case WL_IDLE_STATUS:
Serial.println("Attempting...");
break;
case WL_NO_SSID_AVAIL:
Serial.println("No SSID available");
break;
case WL_SCAN_COMPLETED:
Serial.println("Networks scan completed");
break;
case WL_CONNECT_FAILED:
Serial.println("Connect failed");
break;
case WL_CONNECTION_LOST:
Serial.println("Connection lost");
break;
case WL_DISCONNECTED:
Serial.println("Disconnected");
break;
default:
Serial.println("Unknown status");
break;
}
// Print the SSID of the network you're attached to:
Serial.print("-->[WiFi] SSID: ");
Serial.println(WiFi.SSID());
// Print your WiFi shield's IP address:
Serial.print("-->[WiFi] IP Address: ");
Serial.println(WiFi.localIP());
// Print your WiFi shield's MAC address:
Serial.print("-->[WiFi] MAC Address: ");
MACAddress = getMACAddressAsString();
Serial.println(MACAddress);
// Print the received signal strength:
Serial.print("-->[WiFi] Signal strength (RSSI):");
Serial.print(WiFi.RSSI());
Serial.println(" dBm");
/*
// Print authentication used:
Serial.print("Encryption type: ");
switch (WiFi.encryptionType()) {
case WIFI_AUTH_OPEN:
Serial.println("Open WiFi");
break;
case WIFI_AUTH_WEP:
Serial.println("WEP");
break;
case WIFI_AUTH_WPA_PSK:
Serial.println("WPA-PSK");
break;
case WIFI_AUTH_WPA2_PSK:
Serial.println("WPA2-PSK");
break;
case WIFI_AUTH_WPA_WPA2_PSK:
Serial.println("WPA-WPA2-PSK");
break;
case WIFI_AUTH_WPA2_ENTERPRISE:
Serial.println("WPA2-Enterprise");
break;
default:
Serial.println("Unknown encryption type");
break;
}
*/
}
String getWiFiDisconnectReason(uint8_t reason) {
switch (reason) {
case WIFI_REASON_AUTH_EXPIRE:
return "Auth Expired";
case WIFI_REASON_AUTH_LEAVE:
return "Auth Leave";
case WIFI_REASON_ASSOC_EXPIRE:
return "Association Expired";
case WIFI_REASON_ASSOC_TOOMANY:
return "Too Many Associations";
case WIFI_REASON_NOT_AUTHED:
return "Not Authenticated";
case WIFI_REASON_NOT_ASSOCED:
return "Not Associated";
case WIFI_REASON_ASSOC_LEAVE:
return "Association Leave";
case WIFI_REASON_ASSOC_NOT_AUTHED:
return "Association not Authenticated";
case WIFI_REASON_DISASSOC_PWRCAP_BAD:
return "Disassociate Power Cap Bad";
case WIFI_REASON_DISASSOC_SUPCHAN_BAD:
return "Disassociate Supported Channel Bad";
case WIFI_REASON_IE_INVALID:
return "IE Invalid";
case WIFI_REASON_MIC_FAILURE:
return "Mic Failure";
case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT:
return "4-Way Handshake Timeout";
case WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT:
return "Group Key Update Timeout";
case WIFI_REASON_IE_IN_4WAY_DIFFERS:
return "IE In 4-Way Handshake Differs";
case WIFI_REASON_GROUP_CIPHER_INVALID:
return "Group Cipher Invalid";
case WIFI_REASON_PAIRWISE_CIPHER_INVALID:
return "Pairwise Cipher Invalid";
case WIFI_REASON_AKMP_INVALID:
return "AKMP Invalid";
case WIFI_REASON_UNSUPP_RSN_IE_VERSION:
return "Unsupported RSN IE version";
case WIFI_REASON_INVALID_RSN_IE_CAP:
return "Invalid RSN IE Cap";
case WIFI_REASON_802_1X_AUTH_FAILED:
return "802.1x Authentication Failed";
case WIFI_REASON_CIPHER_SUITE_REJECTED:
return "Cipher Suite Rejected";
case WIFI_REASON_BEACON_TIMEOUT:
return "Beacon Timeout";
case WIFI_REASON_NO_AP_FOUND:
return "AP Not Found";
case WIFI_REASON_AUTH_FAIL:
return "Authentication Failed";
case WIFI_REASON_ASSOC_FAIL:
return "Association Failed";
case WIFI_REASON_HANDSHAKE_TIMEOUT:
return "Handshake Failed";
case WIFI_REASON_CONNECTION_FAIL:
return "Connection Failed";
case WIFI_REASON_UNSPECIFIED:
default:
return "Unspecified";
}
}
void WiFiEvent(WiFiEvent_t event, WiFiEventInfo_t info) {
#ifdef DEBUG_WIFI_EVENTS
Serial.printf("-->[WiFi-event] event: %d - ", event);
switch (event) {
case SYSTEM_EVENT_WIFI_READY:
Serial.println("WiFi interface ready");
break;
case SYSTEM_EVENT_SCAN_DONE:
Serial.println("Completed scan for access points");
break;
case SYSTEM_EVENT_STA_START:
Serial.println("WiFi client started");
break;
case SYSTEM_EVENT_STA_STOP:
Serial.println("WiFi clients stopped");
break;
case SYSTEM_EVENT_STA_CONNECTED:
Serial.println("Connected to access point");
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
Serial.println("Disconnected from WiFi access point");
break;
case SYSTEM_EVENT_STA_AUTHMODE_CHANGE:
Serial.println("Authentication mode of access point has changed");
break;
case SYSTEM_EVENT_STA_GOT_IP:
Serial.print("Obtained IP address: ");
Serial.println(WiFi.localIP());
break;
case SYSTEM_EVENT_STA_LOST_IP:
Serial.println("Lost IP address and IP address is reset to 0");
break;
case SYSTEM_EVENT_STA_WPS_ER_SUCCESS:
Serial.println("WiFi Protected Setup (WPS): succeeded in enrollee mode");
break;
case SYSTEM_EVENT_STA_WPS_ER_FAILED:
Serial.println("WiFi Protected Setup (WPS): failed in enrollee mode");
break;
case SYSTEM_EVENT_STA_WPS_ER_TIMEOUT:
Serial.println("WiFi Protected Setup (WPS): timeout in enrollee mode");
break;
case SYSTEM_EVENT_STA_WPS_ER_PIN:
Serial.println("WiFi Protected Setup (WPS): pin code in enrollee mode");
break;
case SYSTEM_EVENT_AP_START:
Serial.println("WiFi access point started");
break;
case SYSTEM_EVENT_AP_STOP:
Serial.println("WiFi access point stopped");
break;
case SYSTEM_EVENT_AP_STACONNECTED:
Serial.println("Client connected");
break;
case SYSTEM_EVENT_AP_STADISCONNECTED:
Serial.println("Client disconnected");
break;
case SYSTEM_EVENT_AP_STAIPASSIGNED:
Serial.println("Assigned IP address to client");
break;
case SYSTEM_EVENT_AP_PROBEREQRECVED:
Serial.println("Received probe request");
break;
case SYSTEM_EVENT_GOT_IP6:
Serial.println("IPv6 is preferred");
break;
case SYSTEM_EVENT_ETH_START:
Serial.println("Ethernet started");
break;
case SYSTEM_EVENT_ETH_STOP:
Serial.println("Ethernet stopped");
break;
case SYSTEM_EVENT_ETH_CONNECTED:
Serial.println("Ethernet connected");
break;
case SYSTEM_EVENT_ETH_DISCONNECTED:
Serial.println("Ethernet disconnected");
break;
case SYSTEM_EVENT_ETH_GOT_IP:
Serial.println("Obtained IP address");
break;
default:
break;
}
#endif // DEBUG_WIFI_EVENTS
}
void initMDNS() {
#ifdef SUPPORT_MDNS
/*use mdns for host name resolution*/
if (!MDNS.begin(hostName.c_str())) { // http://esp32.local
Serial.println("-->[WiFi] Error setting up MDNS responder!");
while (1) {
delay(100);
}
}
// Serial.print("-->[WiFi] mDNS responder started. CO2 Gadget web interface at: http://");
// Serial.print(hostName);
// Serial.println(".local");
// Serial.printf("-->[WiFi] mDNS responder started. CO2 Gadget web interface at: http://%s.local\n", hostName.c_str());
Serial.println("-->[WiFi] mDNS responder started. CO2 Gadget web interface at: http://" + hostName + ".local");
MDNS.addService("http", "tcp", 80);
#endif
}
void disableWiFi() {
WiFi.disconnect(true); // Disconnect from the network
WiFi.mode(WIFI_OFF); // Switch WiFi off
Serial.println("-->[WiFi] WiFi disabled!");
}
// Replaces placeholder with actual values
String processor(const String &var) {
// Serial.println(var);
if (var == "CO2") {
return String(co2);
} else if (var == "TEMPERATURE") {
return String(temp);
} else if (var == "HUMIDITY") {
return String(hum);
}
return String();
}
bool checkStringIsNumerical(String myString) {
uint16_t Numbers = 0;
for (uint16_t i = 0; i < myString.length(); i++) {
if (myString[i] == '0' || myString[i] == '1' || myString[i] == '2' ||
myString[i] == '3' || myString[i] == '4' || myString[i] == '5' ||
myString[i] == '6' || myString[i] == '7' || myString[i] == '8' ||
myString[i] == '9') {
Numbers++;
}
}
if (Numbers == myString.length()) {
return true;
} else {
return false;
}
}
void WiFiStationConnected(WiFiEvent_t event, WiFiEventInfo_t info) {
#ifdef DEBUG_WIFI_EVENTS
Serial.println("-->[WiFi-event] Connected to WiFi access point");
#endif
}
void WiFiStationGotIP(WiFiEvent_t event, WiFiEventInfo_t info) {
WiFiConnectionRetries = 0;
timeTroubledWIFI = 0;
troubledMQTT = false;
troubledWIFI = false;
#ifdef DEBUG_WIFI_EVENTS
Serial.println("-->[WiFi-event] WiFi got IP)");
Serial.print("-->[WiFi-event] IP address: ");
Serial.println(WiFi.localIP());
#endif
}
void WiFiStationDisconnected(WiFiEvent_t event, WiFiEventInfo_t info) {
#ifdef SUPPORT_CAPTIVE_PORTAL
if (captivePortalActive) return;
#endif
++WiFiConnectionRetries;
Serial.println("-->[WiFi] Disconnected from WiFi access point. Reason: " + getWiFiDisconnectReason(info.wifi_sta_disconnected.reason) + " (" + String(info.wifi_sta_disconnected.reason) + ") Retries: " + String(WiFiConnectionRetries) + " of " + String(maxWiFiConnectionRetries));
#ifdef DEBUG_WIFI_EVENTS
Serial.println("-->[WiFi-event] Disconnected from WiFi access point");
Serial.print("-->[WiFi-event] WiFi lost connection. Reason: (");
Serial.print(info.wifi_sta_disconnected.reason);
Serial.print(") ");
printDisconnectReason(info.wifi_sta_disconnected.reason);
Serial.print("-->[WiFi-event] Retries: ");
Serial.print(WiFiConnectionRetries);
Serial.print(" of ");
Serial.println(maxWiFiConnectionRetries);
#endif
if (WiFiConnectionRetries >= maxWiFiConnectionRetries) {
disableWiFi();
troubledWIFI = true;
Serial.println("-->[WiFi-event] WiFi troubled");
timeTroubledWIFI = millis();
#ifdef DEBUG_WIFI_EVENTS
Serial.println("-->[WiFi-event] Not possible to connect to WiFi after " + String(WiFiConnectionRetries) + " tries. Will try later.");
#endif
}
}
String getCO2GadgetStatusAsJson() {
StaticJsonDocument<512> doc;
doc["mainDeviceSelected"] = mainDeviceSelected;
doc["CO2"] = co2;
doc["Temperature"] = temp;
doc["Humidity"] = hum;
doc["WiFiStatus"] = WiFi.status();
doc["SSID"] = WiFi.SSID();
#ifndef WIFI_PRIVACY
doc["wifiPass"] = wifiPass;
#endif
doc["IP"] = WiFi.localIP().toString();
doc["RSSI"] = WiFi.RSSI();
doc["MACAddress"] = MACAddress;
doc["hostName"] = hostName;
doc["useStaticIP"] = useStaticIP;
doc["staticIP"] = staticIP.toString();
doc["gateway"] = gateway.toString();
doc["subnet"] = subnet.toString();
doc["dns1"] = dns1.toString();
doc["dns2"] = dns2.toString();
#ifdef SUPPORT_MQTT
doc["rootTopic"] = rootTopic;
doc["discoveryTopic"] = discoveryTopic;
doc["mqttClientId"] = mqttClientId;
doc["mqttBroker"] = mqttBroker;
doc["mqttUser"] = mqttUser;
#ifndef WIFI_PRIVACY
doc["mqttPass"] = mqttPass;
#endif
#ifdef SUPPORT_ESPNOW
char peerAddressString[18];
snprintf(peerAddressString, sizeof(peerAddressString),
"%02X:%02X:%02X:%02X:%02X:%02X",
peerESPNowAddress[0], peerESPNowAddress[1], peerESPNowAddress[2],
peerESPNowAddress[3], peerESPNowAddress[4], peerESPNowAddress[5]);
doc["peerESPNowAddress"] = peerAddressString;
#endif
#endif
doc["activeWIFI"] = activeWIFI;
#ifdef SUPPORT_MQTT
doc["activeMQTT"] = activeMQTT;
#endif
#ifdef SUPPORT_BLE
doc["activeBLE"] = activeBLE;
#endif
#ifdef SUPPORT_OTA
doc["activeOTA"] = activeOTA;
#endif
doc["troubledWiFi"] = troubledWIFI;
#ifdef SUPPORT_MQTT
doc["troubledMQTT"] = troubledMQTT;
#endif
#ifdef SUPPORT_ESPNOW
doc["troubledESPNOW"] = troubledESPNOW;
#endif
doc["measurementInterval"] = measurementInterval;
doc["sampleInterval"] = sampleInterval;
doc["calibrationValue"] = calibrationValue;
doc["pendingCalibration"] = pendingCalibration;
doc["freeHeap"] = ESP.getFreeHeap();
doc["minFreeHeap"] = ESP.getMinFreeHeap();
doc["uptime"] = millis();
String output;
serializeJson(doc, output);
return output;
}
String getCaptivePortalStatusAsJson() {
StaticJsonDocument<256> doc;
doc["captivePortalActive"] = captivePortalActive;
doc["forceCaptivePortalActive"] = forceCaptivePortalActive;
doc["captivePortalNoTimeout"] = captivePortalNoTimeout;
doc["timeCaptivePortalStarted"] = timeCaptivePortalStarted;
doc["timeToWaitForCaptivePortal"] = timeToWaitForCaptivePortal;
if (relaxedSecurity) doc["relaxedSecurity"] = relaxedSecurity;
// timeToWaitForCaptivePortal in seconds timeCaptivePortalStarted in milliseconds captivePortalTimeLeft in seconds
if (captivePortalActive && !captivePortalNoTimeout) { // If Captive Portal is active
doc["captivePortalTimeLeft"] = (timeToWaitForCaptivePortal - (millis() - timeCaptivePortalStarted) / 1000);
} else {
doc["captivePortalTimeLeft"] = 0;
}
#ifdef DEBUG_CAPTIVE_PORTAL
doc["captivePortalDebug"] = true;
#endif
String output;
serializeJson(doc, output);
return output;
}
String getWifiNetworksAsJson() {
StaticJsonDocument<1024> doc;
JsonArray networks = doc.createNestedArray("networks");
int numNetworks = WiFi.scanNetworks();
for (int i = 0; i < numNetworks; i++) {
JsonObject network = networks.createNestedObject();
network["SSID"] = WiFi.SSID(i);
network["RSSI"] = WiFi.RSSI(i);
network["Encryption"] = WiFi.encryptionType(i);
}
String output;
serializeJson(doc, output);
return output;
}
bool handleCaptivePortalSettings(String captivePortalPreferences) {
StaticJsonDocument<256> doc;
DeserializationError error = deserializeJson(doc, captivePortalPreferences);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.c_str());
return false;
}
#ifdef DEBUG_CAPTIVE_PORTAL
Serial.println("-->[CAPT] Received Captive Portal Settings: " + captivePortalPreferences);
#endif
if (doc.containsKey("captivePortalActive")) {
#ifdef DEBUG_CAPTIVE_PORTAL
// Serial.print("-->[CAPT] Received Captive Portal Settings: ");
// Serial.println(captivePortalPreferences);
Serial.println("-->[CAPT] Received Captive Portal Setting captivePortalActive: " + String(doc["captivePortalActive"] ? "Enabled" : "Disabled") + " (Actual value: " + String(captivePortalActive ? "Enabled" : "Disabled") + ")");
Serial.println("-->[CAPT] Received Captive Portal Setting forceCaptivePortalActive: " + String(doc["forceCaptivePortalActive"] ? "Enabled" : "Disabled") + " (Actual value: " + String(forceCaptivePortalActive ? "Enabled" : "Disabled") + ")");
Serial.println("-->[CAPT] Received Captive Portal Setting captivePortalNoTimeout: " + String(doc["captivePortalNoTimeout"] ? "Enabled" : "Disabled") + " (Actual value: " + String(captivePortalNoTimeout ? "Enabled" : "Disabled") + ")");
Serial.println("-->[CAPT] Received Captive Portal Setting timeCaptivePortalStarted: " + String(doc["timeCaptivePortalStarted"].as<unsigned long>()) + " (Actual value: " + String(timeCaptivePortalStarted) + ")");
Serial.println("-->[CAPT] Received Captive Portal Setting timeToWaitForCaptivePortal: " + String(doc["timeToWaitForCaptivePortal"].as<unsigned long>()) + " (Actual value: " + String(timeToWaitForCaptivePortal) + ")");
Serial.println("-->[CAPT] Received Captive Portal Setting captivePortalDebug " + String(doc["captivePortalDebug"] ? "Enabled" : "Disabled") + " (Actual value: " + String(captivePortalDebug ? "Enabled" : "Disabled") + ")");
#endif
if ((doc["forceCaptivePortalActive"] == true) && (!forceCaptivePortalActive)) { // If test captive portal is enabled and it was not enabled before
captivePortalActive = true;
forceCaptivePortalActive = true;
timeCaptivePortalStarted = millis();
Serial.println("-->[CAPT] *** Activating Captive Portal for testing");
} else if ((doc["forceCaptivePortalActive"] == false) && (forceCaptivePortalActive)) { // If test captive portal is disabled and it was enabled before
captivePortalActive = false;
forceCaptivePortalActive = false;
Serial.println("-->[CAPT] *** Deactivating Captive Portal for testing");
} else if ((doc["captivePortalActive"] == true) && (!captivePortalActive)) { // If captive portal is enabled and it was not enabled before
captivePortalActive = true;
timeCaptivePortalStarted = millis();
Serial.println("-->[CAPT] *** Activating Captive Portal");
}
#ifdef DEBUG_CAPTIVE_PORTAL
Serial.println("-->[CAPT] Captive Portal enabled for testing: " + String(forceCaptivePortalActive ? "Enabled" : "Disabled"));
Serial.println("-->[CAPT] Captive Portal Active: " + String(captivePortalActive ? "Enabled" : "Disabled"));
#endif
}
if (doc.containsKey("captivePortalNoTimeout")) {
// if captivePortalNoTimeout is being disabled, reset the timeCaptivePortalStarted
if (captivePortalNoTimeout && !doc["captivePortalNoTimeout"]) {
timeCaptivePortalStarted = millis();
}
captivePortalNoTimeout = doc["captivePortalNoTimeout"];
// Print if captive portal timeout is enabled or disabled
Serial.println("-->[CAPT] Captive Portal captivePortalNoTimeout: " + String(captivePortalNoTimeout ? "Enabled" : "Disabled"));
}
if (doc.containsKey("captivePortalDebug")) {
captivePortalDebug = doc["captivePortalDebug"];
// Print if captive portal debug is enabled or disabled
Serial.println("-->[CAPT] Captive Portal Debug: " + String(captivePortalDebug ? "Enabled" : "Disabled"));
}
return true;
}
const char *PARAM_INPUT_1 = "MeasurementInterval";
const char *PARAM_INPUT_2 = "CalibrateCO2";
const char *PARAM_INPUT_3 = "SetVRef";
void initWebServer() {
SPIFFS.begin();
#ifdef DEBUG_WIFI_EVENTS
// Print to serial the free space in the SPIFFS
Serial.print("-->[WiFi] SPIFFS total bytes: ");
Serial.println(SPIFFS.totalBytes());
Serial.print("-->[WiFi] SPIFFS used bytes: ");
Serial.println(SPIFFS.usedBytes());
Serial.print("-->[WiFi] SPIFFS free bytes: ");
Serial.println(SPIFFS.totalBytes() - SPIFFS.usedBytes());
#endif
// server.serveStatic("/", SPIFFS, "/").setDefaultFile("index.html");
// server.serveStatic("/", SPIFFS, "/index.html");
// server.serveStatic("/index.html", SPIFFS, "/index.html");
// server.serveStatic("/preferences.html", SPIFFS, "/preferences.html");
// server.serveStatic("/status.html", SPIFFS, "/status.html");
// server.serveStatic("favicon.ico", SPIFFS, "/favicon.png");
// server.serveStatic("main.js", SPIFFS, "/main.js");
// server.serveStatic("style.css", SPIFFS, "/style.css");
// server.serveStatic("preferences.js", SPIFFS, "/preferences.js");
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
if (request != nullptr) {
/** GZIPPED CONTENT ***/
AsyncWebServerResponse *response = request->beginResponse(SPIFFS, "/index.html.gz", "text/html");
response->addHeader("Content-Encoding", "gzip");
request->send(response);
} else {
Serial.println("---> [WiFi] Error: request is null");
}
});
server.on("/index.html", HTTP_GET, [](AsyncWebServerRequest *request) {
if (request != nullptr) {
/** GZIPPED CONTENT ***/
AsyncWebServerResponse *response = request->beginResponse(SPIFFS, "/index.html.gz", "text/html");
response->addHeader("Content-Encoding", "gzip");
request->send(response);
} else {
Serial.println("---> [WiFi] Error: request is null");
}
});
server.on("/preferences.html", HTTP_GET, [](AsyncWebServerRequest *request) {
if (request != nullptr) {
if (request->hasParam("relaxedSecurity")) relaxedSecurity = true;
if (request->hasParam("forceCaptivePortalActive")) forceCaptivePortalActive = true;
if (request->hasParam("captivePortalNoTimeout")) captivePortalNoTimeout = true;
#ifdef DEBUG_CAPTIVE_PORTAL
String debugText = "-->[WiFi] Loading preferences.html with parameters: ";
if (request->hasParam("captivePortalActive")) debugText += "captivePortalActive: " + String(captivePortalActive ? "Enabled" : "Disabled") + ", ";
if (request->hasParam("forceCaptivePortalActive")) debugText += "forceCaptivePortalActive: " + String(forceCaptivePortalActive ? "Enabled" : "Disabled") + ", ";
if (request->hasParam("captivePortalNoTimeout")) debugText += "captivePortalNoTimeout: " + String(captivePortalNoTimeout ? "Enabled" : "Disabled") + ", ";
if (request->hasParam("relaxedSecurity")) debugText += "relaxedSecurity: " + String(relaxedSecurity ? "Enabled" : "Disabled") + ", ";
if (request->hasParam("captivePortalActive") || request->hasParam("forceCaptivePortalActive") || request->hasParam("captivePortalNoTimeout") || request->hasParam("relaxedSecurity")) Serial.println(debugText);
#endif
if (WiFi.softAPgetStationNum() > 0) {
captivePortalActive = true;
Serial.println("-->[WiFi] Captive Portal active because there are connected stations");
}
if (forceCaptivePortalActive) captivePortalActive = true;
if (captivePortalActive) relaxedSecurity = true;
#ifdef DEBUG_CAPTIVE_PORTAL
Serial.println("-->[WiFi] Loading preferences.html with parameters: captivePortalActive: " + String(captivePortalActive ? "Enabled" : "Disabled") + ", forceCaptivePortalActive: " + String(forceCaptivePortalActive ? "Enabled" : "Disabled") + ", captivePortalNoTimeout: " + String(captivePortalNoTimeout ? "Enabled" : "Disabled") + ", relaxedSecurity: " + String(relaxedSecurity ? "Enabled" : "Disabled"));
#endif
/** GZIPPED CONTENT ***/
AsyncWebServerResponse *response = request->beginResponse(SPIFFS, "/preferences.html.gz", "text/html");
response->addHeader("Content-Encoding", "gzip");
request->send(response);
} else {
Serial.println("---> [WiFi] Error: request is null");
}
timeCaptivePortalStarted = millis();
});
server.on("/status.html", HTTP_GET, [](AsyncWebServerRequest *request) {
if (request != nullptr) {
/** GZIPPED CONTENT ***/
AsyncWebServerResponse *response = request->beginResponse(SPIFFS, "/status.html.gz", "text/html");
response->addHeader("Content-Encoding", "gzip");
request->send(response);
} else {
Serial.println("---> [WiFi] Error: request is null");
}
});
server.on("/ota.html", HTTP_GET, [](AsyncWebServerRequest *request) {
if (request != nullptr) {
AsyncWebServerResponse *response = request->beginResponse(SPIFFS, "/ota.html", "text/html");
response->addHeader("Content-Encoding", "text/html");
request->send(response);
} else {
Serial.println("---> [WiFi] Error: request is null");
}
});
server.on("/main.js", HTTP_GET, [](AsyncWebServerRequest *request) {
if (request != nullptr) {
/** GZIPPED CONTENT ***/
AsyncWebServerResponse *response = request->beginResponse(SPIFFS, "/main.js.gz", "application/javascript");
response->addHeader("Content-Encoding", "gzip");
request->send(response);
} else {
Serial.println("---> [WiFi] Error: request is null");
}
});
server.on("/preferences.js", HTTP_GET, [](AsyncWebServerRequest *request) {