-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
ESPEasyWifi.cpp
1210 lines (1065 loc) · 34.9 KB
/
ESPEasyWifi.cpp
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
#include "../ESPEasyCore/ESPEasyWifi.h"
#include "../../ESPEasy-Globals.h"
#include "../DataStructs/TimingStats.h"
#include "../ESPEasyCore/ESPEasyNetwork.h"
#include "../ESPEasyCore/ESPEasyWiFiEvent.h"
#include "../ESPEasyCore/ESPEasyWifi_ProcessEvent.h"
#include "../ESPEasyCore/ESPEasy_Log.h"
#include "../ESPEasyCore/Serial.h"
#include "../Globals/ESPEasyWiFiEvent.h"
#include "../Globals/EventQueue.h"
#include "../Globals/NetworkState.h"
#include "../Globals/RTC.h"
#include "../Globals/SecuritySettings.h"
#include "../Globals/Services.h"
#include "../Globals/Settings.h"
#include "../Globals/WiFi_AP_Candidates.h"
#include "../Helpers/ESPEasy_time_calc.h"
#include "../Helpers/Misc.h"
#include "../Helpers/Networking.h"
#include "../Helpers/StringConverter.h"
#include "../Helpers/StringGenerator_WiFi.h"
// ********************************************************************************
// WiFi state
// ********************************************************************************
/*
WiFi STA states:
1 STA off => ESPEASY_WIFI_DISCONNECTED
2 STA connecting
3 STA connected => ESPEASY_WIFI_CONNECTED
4 STA got IP => ESPEASY_WIFI_GOT_IP
5 STA connected && got IP => ESPEASY_WIFI_SERVICES_INITIALIZED
N.B. the states are flags, meaning both "connected" and "got IP" must be set
to be considered ESPEASY_WIFI_SERVICES_INITIALIZED
The flag wifiConnectAttemptNeeded indicates whether a new connect attempt is needed.
This is set to true when:
- Security settings have been saved with AP mode enabled. FIXME TD-er, this may not be the best check.
- WiFi connect timeout reached & No client is connected to the AP mode of the node.
- Wifi is reset
- WiFi setup page has been loaded with SSID/pass values.
WiFi AP mode states:
1 AP on => reset AP disable timer
2 AP client connect/disconnect => reset AP disable timer
3 AP off => AP disable timer = 0;
AP mode will be disabled when both apply:
- AP disable timer (timerAPoff) expired
- No client is connected to the AP.
AP mode will be enabled when at least one applies:
- No valid WiFi settings
- Start AP timer (timerAPstart) expired
Start AP timer is set or cleared at:
- Set timerAPstart when "valid WiFi connection" state is observed.
- Disable timerAPstart when ESPEASY_WIFI_SERVICES_INITIALIZED wifi state is reached.
For the first attempt to connect after a cold boot (RTC values are 0), a WiFi scan will be
performed to find the strongest known SSID.
This will set RTC.lastBSSID and RTC.lastWiFiChannel
Quick reconnect (using BSSID/channel of last connection) when both apply:
- If wifi_connect_attempt < 3
- RTC.lastBSSID is known
- RTC.lastWiFiChannel != 0
Change of wifi settings when both apply:
- "other" settings valid
- (wifi_connect_attempt % 2) == 0
Reset of wifi_connect_attempt to 0 when both apply:
- connection successful
- Connection stable (connected for > 5 minutes)
*/
// ********************************************************************************
// Check WiFi connected status
// This is basically the state machine to switch between states:
// - Initiate WiFi reconnect
// - Start/stop of AP mode
// ********************************************************************************
bool WiFiConnected() {
START_TIMER;
static bool recursiveCall = false;
if (WiFiEventData.unprocessedWifiEvents()) { return false; }
bool wifi_isconnected = false;
#ifdef ESP8266
// Perform check on SDK function, see: https://github.com/esp8266/Arduino/issues/7432
station_status_t status = wifi_station_get_connect_status();
switch(status) {
case STATION_GOT_IP:
wifi_isconnected = true;
break;
case STATION_NO_AP_FOUND:
case STATION_CONNECT_FAIL:
case STATION_WRONG_PASSWORD:
wifi_isconnected = false;
break;
case STATION_IDLE:
case STATION_CONNECTING:
wifi_isconnected = WiFiEventData.WiFiServicesInitialized();
break;
default:
wifi_isconnected = false;
break;
}
#endif
#ifdef ESP32
if (WiFi.isConnected()) {
wifi_isconnected = true;
}
#endif
if (recursiveCall) return wifi_isconnected;
recursiveCall = true;
// For ESP82xx, do not rely on WiFi.status() with event based wifi.
const int32_t wifi_rssi = WiFi.RSSI();
bool validWiFi = (wifi_rssi < 0) && wifi_isconnected && hasIPaddr();
/*
if (validWiFi && WiFi.channel() != WiFiEventData.usedChannel) {
validWiFi = false;
}
*/
if (validWiFi != WiFiEventData.WiFiServicesInitialized()) {
// else wifiStatus is no longer in sync.
if (checkAndResetWiFi()) {
// Wifi has been reset, so no longer valid WiFi
validWiFi = false;
}
}
if (validWiFi) {
// Connected, thus disable any timer to start AP mode. (except when in WiFi setup mode)
if (!WiFiEventData.wifiSetupConnect) {
WiFiEventData.timerAPstart.clear();
}
STOP_TIMER(WIFI_ISCONNECTED_STATS);
recursiveCall = false;
// Only return true after some time since it got connected.
SetWiFiTXpower();
return WiFiEventData.wifi_considered_stable || WiFiEventData.lastConnectMoment.timeoutReached(100);
}
if ((WiFiEventData.timerAPstart.isSet()) && WiFiEventData.timerAPstart.timeReached()) {
// Timer reached, so enable AP mode.
if (!WifiIsAP(WiFi.getMode())) {
if (!Settings.DoNotStartAP()) {
setAP(true);
}
}
WiFiEventData.timerAPstart.clear();
}
// When made this far in the code, we apparently do not have valid WiFi connection.
if (!WiFiEventData.timerAPstart.isSet() && !WifiIsAP(WiFi.getMode())) {
// First run we do not have WiFi connection any more, set timer to start AP mode
// Only allow the automatic AP mode in the first N minutes after boot.
if (getUptimeMinutes() < WIFI_ALLOW_AP_AFTERBOOT_PERIOD) {
WiFiEventData.timerAPstart.setMillisFromNow(WIFI_RECONNECT_WAIT);
// Fixme TD-er: Make this more elegant as it now needs to know about the extra time needed for the AP start timer.
WiFiEventData.timerAPoff.setMillisFromNow(WIFI_RECONNECT_WAIT + WIFI_AP_OFF_TIMER_DURATION);
}
}
if (wifiConnectTimeoutReached() && !WiFiEventData.wifiSetup) {
// It took too long to make a connection, set flag we need to try again
//if (!wifiAPmodeActivelyUsed()) {
WiFiEventData.wifiConnectAttemptNeeded = true;
//}
WiFiEventData.wifiConnectInProgress = false;
}
delay(0);
STOP_TIMER(WIFI_NOTCONNECTED_STATS);
recursiveCall = false;
return false;
}
void WiFiConnectRelaxed() {
if (!WiFiEventData.WiFiConnectAllowed() || WiFiEventData.wifiConnectInProgress) {
return; // already connected or connect attempt in progress need to disconnect first
}
if (!WiFiEventData.processedScanDone) {
// Scan is still active, so do not yet connect.
return;
}
if (WiFiEventData.unprocessedWifiEvents()) {
// Still need to process WiFi events
return;
}
if (!WiFiEventData.wifiSetupConnect && wifiAPmodeActivelyUsed()) {
return;
}
// FIXME TD-er: Should not try to prepare when a scan is still busy.
// This is a logic error which may lead to strange issues if some kind of timeout happens and/or RF calibration was not OK.
// Split this function into separate parts, with the last part being the actual connect attempt either after a scan is complete or quick connect is possible.
AttemptWiFiConnect();
}
void AttemptWiFiConnect() {
if (!WiFiEventData.wifiConnectAttemptNeeded) {
return;
}
if (WiFiEventData.wifiSetupConnect) {
// wifiSetupConnect is when run from the setup page.
RTC.clearLastWiFi(); // Force slow connect
WiFiEventData.wifi_connect_attempt = 0;
WiFiEventData.wifiSetupConnect = false;
if (WiFiEventData.timerAPoff.isSet()) {
WiFiEventData.timerAPoff.setMillisFromNow(WIFI_RECONNECT_WAIT + WIFI_AP_OFF_TIMER_DURATION);
}
}
if (WiFi_AP_Candidates.getNext(WiFiScanAllowed())) {
const WiFi_AP_Candidate& candidate = WiFi_AP_Candidates.getCurrent();
if (loglevelActiveFor(LOG_LEVEL_INFO)) {
String log = F("WIFI : Connecting ");
log += candidate.toString();
log += F(" attempt #");
log += WiFiEventData.wifi_connect_attempt;
addLog(LOG_LEVEL_INFO, log);
}
WiFiEventData.markWiFiBegin();
if (prepareWiFi()) {
float tx_pwr = 0; // Will be set higher based on RSSI when needed.
// FIXME TD-er: Must check WiFiEventData.wifi_connect_attempt to increase TX power
if (Settings.UseMaxTXpowerForSending()) {
tx_pwr = Settings.getWiFi_TX_power();
}
SetWiFiTXpower(tx_pwr, candidate.rssi);
if (candidate.allowQuickConnect()) {
WiFi.begin(candidate.ssid.c_str(), candidate.key.c_str(), candidate.channel, candidate.bssid);
} else {
WiFi.begin(candidate.ssid.c_str(), candidate.key.c_str());
}
// Start connect attempt now, so no longer needed to attempt new connection.
WiFiEventData.wifiConnectAttemptNeeded = false;
}
} else {
if (!wifiAPmodeActivelyUsed() || WiFiEventData.wifiSetupConnect) {
if (!prepareWiFi()) {
return;
}
// Maybe not scan async to give the ESP some slack in power consumption?
const bool async = true;
WifiScan(async);
}
}
logConnectionStatus();
}
// ********************************************************************************
// Set Wifi config
// ********************************************************************************
bool prepareWiFi() {
if (!WiFi_AP_Candidates.hasKnownCredentials()) {
if (!WiFiEventData.warnedNoValidWiFiSettings) {
addLog(LOG_LEVEL_ERROR, F("WIFI : No valid wifi settings"));
WiFiEventData.warnedNoValidWiFiSettings = true;
}
WiFiEventData.last_wifi_connect_attempt_moment.clear();
WiFiEventData.wifi_connect_attempt = 1;
WiFiEventData.wifiConnectAttemptNeeded = false;
// No need to wait longer to start AP mode.
if (!Settings.DoNotStartAP()) {
setAP(true);
}
return false;
}
WiFiEventData.warnedNoValidWiFiSettings = false;
setSTA(true);
char hostname[40];
safe_strncpy(hostname, NetworkCreateRFCCompliantHostname().c_str(), sizeof(hostname));
#if defined(ESP8266)
wifi_station_set_hostname(hostname);
#endif // if defined(ESP8266)
#if defined(ESP32)
WiFi.setHostname(hostname);
WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE);
#endif // if defined(ESP32)
setConnectionSpeed();
setupStaticIPconfig();
return true;
}
bool checkAndResetWiFi() {
#ifdef ESP8266
station_status_t status = wifi_station_get_connect_status();
switch(status) {
case STATION_GOT_IP:
if (WiFi.RSSI() < 0 && NetworkLocalIP().isSet()) {
//if (WiFi.channel() == WiFiEventData.usedChannel || WiFiEventData.usedChannel == 0) {
// This is a valid status, no need to reset
return false;
//}
}
break;
case STATION_NO_AP_FOUND:
case STATION_CONNECT_FAIL:
case STATION_WRONG_PASSWORD:
// Reason to reset WiFi
break;
case STATION_IDLE:
case STATION_CONNECTING:
if (!WiFiEventData.last_wifi_connect_attempt_moment.timeoutReached(15000)) {
return false;
}
break;
}
#endif
#ifdef ESP32
if (WiFi.isConnected()) {
//if (WiFi.channel() == WiFiEventData.usedChannel || WiFiEventData.usedChannel == 0) {
return false;
//}
}
if (!WiFiEventData.last_wifi_connect_attempt_moment.timeoutReached(15000)) {
return false;
}
#endif
String log = F("WiFi : WiFiConnected() out of sync: ");
log += ESPeasyWifiStatusToString();
log += F(" RSSI: ");
log += String(WiFi.RSSI());
#ifdef ESP8266
log += F(" status: ");
log += SDKwifiStatusToString(status);
#endif
// Call for reset first, to make sure a syslog call will not try to send.
resetWiFi();
addLog(LOG_LEVEL_INFO, log);
return true;
}
void resetWiFi() {
//if (wifiAPmodeActivelyUsed()) return;
if (WiFiEventData.lastWiFiResetMoment.isSet() && !WiFiEventData.lastWiFiResetMoment.timeoutReached(1000)) {
// Don't reset WiFi too often
return;
}
FeedSW_watchdog();
WiFiEventData.clearAll();
WifiDisconnect();
// Send this log only after WifiDisconnect() or else sending to syslog may cause issues
addLog(LOG_LEVEL_INFO, String(F("Reset WiFi.")));
// setWifiMode(WIFI_OFF);
initWiFi();
}
void initWiFi()
{
#ifdef ESP8266
// See https://github.com/esp8266/Arduino/issues/5527#issuecomment-460537616
// FIXME TD-er: Do not destruct WiFi object, it may cause crashes with queued UDP traffic.
WiFi.~ESP8266WiFiClass();
WiFi = ESP8266WiFiClass();
#endif // ifdef ESP8266
WiFi.persistent(false); // Do not use SDK storage of SSID/WPA parameters
// The WiFi.disconnect() ensures that the WiFi is working correctly. If this is not done before receiving WiFi connections,
// those WiFi connections will take a long time to make or sometimes will not work at all.
WiFi.disconnect(true);
setWifiMode(WIFI_OFF);
#if defined(ESP32)
wm_event_id = WiFi.onEvent(WiFiEvent);
#endif
#ifdef ESP8266
// WiFi event handlers
stationConnectedHandler = WiFi.onStationModeConnected(onConnected);
stationDisconnectedHandler = WiFi.onStationModeDisconnected(onDisconnect);
stationGotIpHandler = WiFi.onStationModeGotIP(onGotIP);
stationModeDHCPTimeoutHandler = WiFi.onStationModeDHCPTimeout(onDHCPTimeout);
stationModeAuthModeChangeHandler = WiFi.onStationModeAuthModeChanged(onStationModeAuthModeChanged);
APModeStationConnectedHandler = WiFi.onSoftAPModeStationConnected(onConnectedAPmode);
APModeStationDisconnectedHandler = WiFi.onSoftAPModeStationDisconnected(onDisconnectedAPmode);
#endif
}
// ********************************************************************************
// Configure WiFi TX power
// ********************************************************************************
void SetWiFiTXpower() {
SetWiFiTXpower(0.0f); // Just some minimal value, will be adjusted in SetWiFiTXpower
}
void SetWiFiTXpower(float dBm) {
SetWiFiTXpower(dBm, WiFi.RSSI());
}
void SetWiFiTXpower(float dBm, float rssi) {
const WiFiMode_t cur_mode = WiFi.getMode();
if (cur_mode == WIFI_OFF) {
return;
}
if (Settings.UseMaxTXpowerForSending()) {
dBm = 30; // Just some max, will be limited later
}
// Range ESP32 : 2dBm - 20dBm
// Range ESP8266: 0dBm - 20.5dBm
float maxTXpwr;
float threshold = GetRSSIthreshold(maxTXpwr);
float minTXpwr = 0;
threshold += Settings.WiFi_sensitivity_margin; // Margin in dBm on top of threshold
// Assume AP sends with max set by ETSI standard.
// 2.4 GHz: 100 mWatt (20 dBm)
// US and some other countries allow 1000 mW (30 dBm)
// We cannot send with over 20 dBm, thus it makes no sense to force higher TX power all the time.
const float newrssi = rssi - 20;
if (newrssi < threshold) {
minTXpwr = threshold - newrssi;
}
if (minTXpwr > maxTXpwr) {
minTXpwr = maxTXpwr;
}
if (dBm > maxTXpwr) {
dBm = maxTXpwr;
} else if (dBm < minTXpwr) {
dBm = minTXpwr;
}
#ifdef ESP32
wifi_power_t val = WIFI_POWER_MINUS_1dBm;
if (dBm < 0) {
val = WIFI_POWER_MINUS_1dBm;
dBm = -1;
} else if (dBm < 3.5) {
val = WIFI_POWER_2dBm;
dBm = 2;
} else if (dBm < 6) {
val = WIFI_POWER_5dBm;
dBm = 5;
} else if (dBm < 8) {
val = WIFI_POWER_7dBm;
dBm = 7;
} else if (dBm < 10) {
val = WIFI_POWER_8_5dBm;
dBm = 8.5;
} else if (dBm < 12) {
val = WIFI_POWER_11dBm;
dBm = 11;
} else if (dBm < 14) {
val = WIFI_POWER_13dBm;
dBm = 13;
} else if (dBm < 16) {
val = WIFI_POWER_15dBm;
dBm = 15;
} else if (dBm < 17.75) {
val = WIFI_POWER_17dBm;
dBm = 17;
} else if (dBm < 18.75) {
val = WIFI_POWER_18_5dBm;
dBm = 18.5;
} else if (dBm < 19.25) {
val = WIFI_POWER_19dBm;
dBm = 19;
} else {
val = WIFI_POWER_19_5dBm;
dBm = 19.5;
}
esp_wifi_set_max_tx_power(val);
//esp_wifi_get_max_tx_power(&val);
// dBm = static_cast<float>(val);
// dBm /= 4.0f;
#endif
#ifdef ESP8266
WiFi.setOutputPower(dBm);
#endif
if (WiFiEventData.wifi_TX_pwr < dBm) {
// Will increase the TX power, give power supply of the unit some rest
delay(1);
}
WiFiEventData.wifi_TX_pwr = dBm;
delay(0);
#ifndef BUILD_NO_DEBUG
if (loglevelActiveFor(LOG_LEVEL_DEBUG)) {
const int TX_pwr_int = WiFiEventData.wifi_TX_pwr * 4;
const int maxTXpwr_int = maxTXpwr * 4;
if (TX_pwr_int != maxTXpwr_int) {
static int last_log = -1;
if (TX_pwr_int != last_log) {
last_log = TX_pwr_int;
String log = F("WiFi : Set TX power to ");
log += String(dBm, 0);
log += F("dBm");
log += F(" sensitivity: ");
log += String(threshold, 0);
log += F("dBm");
if (rssi < 0) {
log += F(" RSSI: ");
log += String(rssi, 0);
log += F("dBm");
}
addLog(LOG_LEVEL_DEBUG, log);
}
}
}
#endif
}
float GetRSSIthreshold(float& maxTXpwr) {
maxTXpwr = Settings.getWiFi_TX_power();
float threshold = -72;
switch (getConnectionProtocol()) {
case WiFiConnectionProtocol::WiFi_Protocol_11b:
threshold = -91;
break;
case WiFiConnectionProtocol::WiFi_Protocol_11g:
threshold = -75;
if (maxTXpwr > 17) maxTXpwr = 17;
break;
case WiFiConnectionProtocol::WiFi_Protocol_11n:
threshold = -72;
if (maxTXpwr > 14) maxTXpwr = 14;
break;
case WiFiConnectionProtocol::Unknown:
break;
}
return threshold;
}
WiFiConnectionProtocol getConnectionProtocol() {
if (WiFi.RSSI() < 0) {
#ifdef ESP8266
switch (wifi_get_phy_mode()) {
case PHY_MODE_11B:
return WiFiConnectionProtocol::WiFi_Protocol_11b;
case PHY_MODE_11G:
return WiFiConnectionProtocol::WiFi_Protocol_11g;
case PHY_MODE_11N:
return WiFiConnectionProtocol::WiFi_Protocol_11n;
}
#endif
#ifdef ESP32
uint8_t protocol;
esp_wifi_get_protocol(WIFI_IF_STA, &protocol);
if (protocol & WIFI_PROTOCOL_11N) {
return WiFiConnectionProtocol::WiFi_Protocol_11n;
}
if (protocol & WIFI_PROTOCOL_11G) {
return WiFiConnectionProtocol::WiFi_Protocol_11g;
}
if (protocol & WIFI_PROTOCOL_11B) {
return WiFiConnectionProtocol::WiFi_Protocol_11b;
}
#endif
}
return WiFiConnectionProtocol::Unknown;
}
// ********************************************************************************
// Disconnect from Wifi AP
// ********************************************************************************
void WifiDisconnect()
{
#if defined(ESP32)
WiFi.disconnect();
WiFi.removeEvent(wm_event_id);
#else // if defined(ESP32)
ETS_UART_INTR_DISABLE();
wifi_station_disconnect();
ETS_UART_INTR_ENABLE();
#endif // if defined(ESP32)
WiFiEventData.setWiFiDisconnected();
WiFiEventData.markDisconnect(WIFI_DISCONNECT_REASON_ASSOC_LEAVE);
delay(1);
}
// ********************************************************************************
// Scan WiFi network
// ********************************************************************************
void WiFiScanPeriodical() {
WiFi_AP_Candidates.purge_expired();
if (!Settings.PeriodicalScanWiFi()) {
return;
}
if (active_network_medium == NetworkMedium_t::Ethernet) {
return;
}
const bool async = true;
WifiScan(async);
}
bool WiFiScanAllowed() {
if (WiFi_AP_Candidates.scanComplete() == WIFI_SCAN_RUNNING) {
return false;
}
if (!WiFiEventData.processedScanDone) {
processScanDone();
}
if (WiFiEventData.unprocessedWifiEvents()) {
handle_unprocessedNetworkEvents();
}
if (WiFiEventData.unprocessedWifiEvents()) {
if (loglevelActiveFor(LOG_LEVEL_ERROR)) {
String log = F("WiFi : Scan not allowed, unprocessed WiFi events: ");
if (!WiFiEventData.processedConnect) {
log += F(" conn");
}
if (!WiFiEventData.processedDisconnect) {
log += F(" disconn");
}
if (!WiFiEventData.processedGotIP) {
log += F(" gotIP");
}
if (!WiFiEventData.processedDHCPTimeout) {
log += F(" DHCP_t/o");
}
addLog(LOG_LEVEL_ERROR, log);
}
return false;
}
/*
if (!wifiAPmodeActivelyUsed() && !NetworkConnected()) {
return true;
}
*/
WiFi_AP_Candidates.purge_expired();
if (WiFiEventData.wifiConnectInProgress) {
return false;
}
if (NetworkConnected() && WiFi_AP_Candidates.getBestCandidate().usable()) {
addLog(LOG_LEVEL_ERROR, F("WiFi : Scan not needed, good candidate present"));
return false;
}
if (WiFiEventData.lastDisconnectMoment.isSet() && WiFiEventData.lastDisconnectMoment.millisPassedSince() < WIFI_RECONNECT_WAIT) {
if (!NetworkConnected()) {
return true;
}
}
if (WiFiEventData.lastScanMoment.isSet()) {
const LongTermTimer::Duration scanInterval = wifiAPmodeActivelyUsed() ? WIFI_SCAN_INTERVAL_AP_USED : WIFI_SCAN_INTERVAL_MINIMAL;
if (WiFiEventData.lastScanMoment.millisPassedSince() < scanInterval) {
return false;
}
}
return true;
}
void WifiScan(bool async, uint8_t channel) {
if (!WiFiScanAllowed()) {
return;
}
START_TIMER;
WiFiEventData.lastScanMoment.setNow();
if (loglevelActiveFor(LOG_LEVEL_INFO)) {
if (channel == 0) {
addLog(LOG_LEVEL_INFO, F("WiFi : Start network scan all channels"));
} else {
String log;
log = F("WiFi : Start network scan channel ");
log += channel;
addLog(LOG_LEVEL_INFO, log);
}
}
bool show_hidden = true;
WiFiEventData.processedScanDone = false;
WiFiEventData.lastGetScanMoment.setNow();
WiFiEventData.lastScanChannel = channel;
unsigned int nrScans = 1 + (async ? 0 : Settings.NumberExtraWiFiScans);
while (nrScans > 0) {
if (!async) {
WiFi_AP_Candidates.begin_sync_scan();
FeedSW_watchdog();
}
--nrScans;
#ifdef ESP8266
WiFi.scanNetworks(async, show_hidden, channel);
#endif
#ifdef ESP32
const bool passive = false;
const uint32_t max_ms_per_chan = 300;
WiFi.scanNetworks(async, show_hidden, passive, max_ms_per_chan /*, channel */);
#endif
if (!async) {
FeedSW_watchdog();
processScanDone();
}
}
STOP_TIMER(async ? WIFI_SCAN_ASYNC : WIFI_SCAN_SYNC);
}
// ********************************************************************************
// Scan all Wifi Access Points
// ********************************************************************************
void WifiScan()
{
// Direct Serial is allowed here, since this function will only be called from serial input.
serialPrintln(F("WIFI : SSID Scan start"));
if (WiFi_AP_Candidates.scanComplete() <= 0) {
WiFiMode_t cur_wifimode = WiFi.getMode();
WifiScan(false);
setWifiMode(cur_wifimode);
}
const int8_t scanCompleteStatus = WiFi_AP_Candidates.scanComplete();
if (scanCompleteStatus <= 0) {
serialPrintln(F("WIFI : No networks found"));
}
else
{
serialPrint(F("WIFI : "));
serialPrint(String(scanCompleteStatus));
serialPrintln(F(" networks found"));
int i = 0;
for (auto it = WiFi_AP_Candidates.scanned_begin(); it != WiFi_AP_Candidates.scanned_end(); ++it)
{
++i;
// Print SSID and RSSI for each network found
serialPrint(F("WIFI : "));
serialPrint(String(i));
serialPrint(": ");
serialPrintln(it->toString());
delay(10);
}
}
serialPrintln("");
}
// ********************************************************************************
// Manage Wifi Modes
// ********************************************************************************
void setSTA(bool enable) {
switch (WiFi.getMode()) {
case WIFI_OFF:
if (enable) { setWifiMode(WIFI_STA); }
break;
case WIFI_STA:
if (!enable) { setWifiMode(WIFI_OFF); }
break;
case WIFI_AP:
if (enable) { setWifiMode(WIFI_AP_STA); }
break;
case WIFI_AP_STA:
if (!enable) { setWifiMode(WIFI_AP); }
break;
default:
break;
}
}
void setAP(bool enable) {
WiFiMode_t wifimode = WiFi.getMode();
switch (wifimode) {
case WIFI_OFF:
if (enable) {
WifiScan(false);
setWifiMode(WIFI_AP);
}
break;
case WIFI_STA:
if (enable) { setWifiMode(WIFI_AP_STA); }
break;
case WIFI_AP:
if (!enable) { setWifiMode(WIFI_OFF); }
break;
case WIFI_AP_STA:
if (!enable) { setWifiMode(WIFI_STA); }
break;
default:
break;
}
}
// Only internal scope
void setAPinternal(bool enable)
{
if (enable) {
// create and store unique AP SSID/PW to prevent ESP from starting AP mode with default SSID and No password!
// setup ssid for AP Mode when needed
String softAPSSID = NetworkCreateRFCCompliantHostname();
String pwd = SecuritySettings.WifiAPKey;
IPAddress subnet(DEFAULT_AP_SUBNET);
if (!WiFi.softAPConfig(apIP, apIP, subnet)) {
addLog(LOG_LEVEL_ERROR, F("WIFI : [AP] softAPConfig failed!"));
}
if (WiFi.softAP(softAPSSID.c_str(), pwd.c_str())) {
if (loglevelActiveFor(LOG_LEVEL_INFO)) {
eventQueue.add(F("WiFi#APmodeEnabled"));
String log(F("WIFI : AP Mode ssid will be "));
log += softAPSSID;
log += F(" with address ");
log += WiFi.softAPIP().toString();
addLog(LOG_LEVEL_INFO, log);
}
} else {
if (loglevelActiveFor(LOG_LEVEL_ERROR)) {
String log(F("WIFI : Error while starting AP Mode with SSID: "));
log += softAPSSID;
log += F(" IP: ");
log += apIP.toString();
addLog(LOG_LEVEL_ERROR, log);
}
}
#ifdef ESP32
#else // ifdef ESP32
if (wifi_softap_dhcps_status() != DHCP_STARTED) {
if (!wifi_softap_dhcps_start()) {
addLog(LOG_LEVEL_ERROR, F("WIFI : [AP] wifi_softap_dhcps_start failed!"));
}
}
#endif // ifdef ESP32
WiFiEventData.timerAPoff.setMillisFromNow(WIFI_AP_OFF_TIMER_DURATION);
} else {
#ifdef FEATURE_DNS_SERVER
if (dnsServerActive) {
dnsServerActive = false;
dnsServer.stop();
}
#endif
}
}
String getWifiModeString(WiFiMode_t wifimode)
{
switch (wifimode) {
case WIFI_OFF: return F("OFF");
case WIFI_STA: return F("STA");
case WIFI_AP: return F("AP");
case WIFI_AP_STA: return F("AP+STA");
default:
break;
}
return F("Unknown");
}
void setWifiMode(WiFiMode_t wifimode) {
const WiFiMode_t cur_mode = WiFi.getMode();
if (cur_mode == wifimode) {
return;
}
if (cur_mode == WIFI_OFF) {
#if defined(ESP32)
esp_wifi_set_ps(WIFI_PS_NONE);
#endif
#ifdef ESP8266
// See: https://github.com/esp8266/Arduino/issues/6172#issuecomment-500457407
WiFi.forceSleepWake(); // Make sure WiFi is really active.
#endif // ifdef ESP8266
delay(100);
}
addLog(LOG_LEVEL_INFO, String(F("WIFI : Set WiFi to ")) + getWifiModeString(wifimode));
int retry = 2;
while (!WiFi.mode(wifimode) && retry > 0) {
addLog(LOG_LEVEL_INFO, F("WIFI : Cannot set mode!!!!!"));
delay(100);
--retry;
}
retry = 2;
while (WiFi.getMode() != wifimode && retry > 0) {
addLog(LOG_LEVEL_INFO, F("WIFI : mode not yet set"));
delay(100);
--retry;
}
if (wifimode == WIFI_OFF) {
delay(100);
#if defined(ESP32)
esp_wifi_set_ps(WIFI_PS_MAX_MODEM);
#endif
#ifdef ESP8266
WiFi.forceSleepBegin();
#endif // ifdef ESP8266
delay(1);
} else {
// Only set power mode when AP is not enabled
// When AP is enabled, the sleep mode is already set to WIFI_NONE_SLEEP
if (!WifiIsAP(wifimode)) {
if (Settings.WifiNoneSleep()) {
#ifdef ESP8266
WiFi.setSleepMode(WIFI_NONE_SLEEP);
#endif
#ifdef ESP32
WiFi.setSleep(WIFI_PS_NONE);
#endif
} else if (Settings.EcoPowerMode()) {
// Allow light sleep during idle times
#ifdef ESP8266
WiFi.setSleepMode(WIFI_LIGHT_SLEEP);
#endif
#ifdef ESP32
// Maximum modem power saving.
// In this mode, interval to receive beacons is determined by the listen_interval parameter in wifi_sta_config_t
// FIXME TD-er: Must test if this is desired behavior in ESP32.
WiFi.setSleep(WIFI_PS_MAX_MODEM);
#endif
} else {
// Default
#ifdef ESP8266
WiFi.setSleepMode(WIFI_MODEM_SLEEP);
#endif
#ifdef ESP32
// Minimum modem power saving.
// In this mode, station wakes up to receive beacon every DTIM period
WiFi.setSleep(WIFI_PS_MIN_MODEM);
#endif
}
}
SetWiFiTXpower();
if (WifiIsSTA(wifimode)) {
if (!WiFi.getAutoConnect()) {
WiFi.setAutoConnect(true);
}
}
delay(100); // Must allow for some time to init.
}
const bool new_mode_AP_enabled = WifiIsAP(wifimode);
if (WifiIsAP(cur_mode) && !new_mode_AP_enabled) {
eventQueue.add(F("WiFi#APmodeDisabled"));
}
if (WifiIsAP(cur_mode) != new_mode_AP_enabled) {
// Mode has changed
setAPinternal(new_mode_AP_enabled);
}
#ifdef FEATURE_MDNS
#ifdef ESP8266
// notifyAPChange() is not present in the ESP32 MDNSResponder
MDNS.notifyAPChange();
#endif
#endif
}
bool WifiIsAP(WiFiMode_t wifimode)
{
#if defined(ESP32)
return (wifimode == WIFI_MODE_AP) || (wifimode == WIFI_MODE_APSTA);