-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathWifi.ino
501 lines (458 loc) · 13.9 KB
/
Wifi.ino
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
//********************************************************************************
// Determine Wifi AP name to set. (also used for mDNS)
//********************************************************************************
String WifiGetAPssid()
{
String ssid(Settings.Name);
ssid+=F("-");
ssid+=Settings.Unit;
return (ssid);
}
//********************************************************************************
// Determine hostname: basically WifiGetAPssid with spaces changed to -
//********************************************************************************
String WifiGetHostname()
{
String hostname(WifiGetAPssid());
hostname.replace(F(" "), F("-"));
return (hostname);
}
//********************************************************************************
// Set Wifi AP Mode config
//********************************************************************************
void WifiAPconfig()
{
// 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=WifiGetAPssid();
String pwd = SecuritySettings.WifiAPKey;
WiFi.softAP(softAPSSID.c_str(),pwd.c_str());
// We start in STA mode
WifiAPMode(false);
String log("WIFI : AP Mode ssid will be ");
log=log+WifiGetAPssid();
log=log+F(" with address ");
log=log+apIP.toString();
addLog(LOG_LEVEL_INFO, log);
}
bool WifiIsAP()
{
#if defined(ESP8266)
byte wifimode = wifi_get_opmode();
#endif
#if defined(ESP32)
byte wifimode = WiFi.getMode();
#endif
return(wifimode == 2 || wifimode == 3); //apmode is enabled
}
//********************************************************************************
// Set Wifi AP Mode
//********************************************************************************
void WifiAPMode(boolean state)
{
if (WifiIsAP())
{
//want to disable?
if (!state)
{
WiFi.mode(WIFI_STA);
addLog(LOG_LEVEL_INFO, F("WIFI : AP Mode disabled"));
}
}
else
{
//want to enable?
if (state)
{
WiFi.mode(WIFI_AP_STA);
addLog(LOG_LEVEL_INFO, F("WIFI : AP Mode enabled"));
}
}
}
//********************************************************************************
// Set Wifi config
//********************************************************************************
bool prepareWiFi() {
String log = "";
char hostname[40];
strncpy(hostname, WifiGetHostname().c_str(), sizeof(hostname));
#if defined(ESP8266)
wifi_station_set_hostname(hostname);
#endif
#if defined(ESP32)
WiFi.setHostname(hostname);
#endif
//use static ip?
if (Settings.IP[0] != 0 && Settings.IP[0] != 255)
{
const IPAddress ip = Settings.IP;
log = F("IP : Static IP :");
log += ip;
addLog(LOG_LEVEL_INFO, log);
const IPAddress gw = Settings.Gateway;
const IPAddress subnet = Settings.Subnet;
const IPAddress dns = Settings.DNS;
WiFi.config(ip, gw, subnet, dns);
}
return selectValidWiFiSettings();
}
//********************************************************************************
// Configure network and connect to Wifi SSID and SSID2
//********************************************************************************
boolean WifiConnect(byte connectAttempts)
{
if (prepareWiFi()) {
//try to connect to one of the access points
bool connected = WifiConnectAndWait(connectAttempts);
if (!connected) {
if (selectNextWiFiSettings()) {
connected = WifiConnectAndWait(connectAttempts);
}
}
if (connected) {
return(true);
}
}
addLog(LOG_LEVEL_ERROR, F("WIFI : Could not connect to AP!"));
//everything failed, activate AP mode (will deactivate automatically after a while if its connected again)
WifiAPMode(true);
return(false);
}
//********************************************************************************
// Start connect to WiFi and check later to see if connected.
//********************************************************************************
void WiFiConnectRelaxed() {
wifiConnected = false;
wifi_connect_attempt = 0;
if (prepareWiFi()) {
tryConnectWiFi();
return;
}
addLog(LOG_LEVEL_ERROR, F("WIFI : Could not connect to AP, no valid WiFi settings!"));
//everything failed, activate AP mode (will deactivate automatically after a while if its connected again)
WifiAPMode(true);
}
//********************************************************************************
// Manage WiFi credentials
//********************************************************************************
const char* getLastWiFiSettingsSSID() {
return lastWiFiSettings == 0 ? SecuritySettings.WifiSSID : SecuritySettings.WifiSSID2;
}
const char* getLastWiFiSettingsPassphrase() {
return lastWiFiSettings == 0 ? SecuritySettings.WifiKey : SecuritySettings.WifiKey2;
}
bool anyValidWifiSettings() {
if (wifiSettingsValid(SecuritySettings.WifiSSID, SecuritySettings.WifiKey))
return true;
if (wifiSettingsValid(SecuritySettings.WifiSSID2, SecuritySettings.WifiKey2))
return true;
addLog(LOG_LEVEL_ERROR, F("WIFI : No valid WiFi settings!"));
return false;
}
bool selectNextWiFiSettings() {
uint8_t tmp = lastWiFiSettings;
lastWiFiSettings = (lastWiFiSettings + 1) % 2;
if (!wifiSettingsValid(getLastWiFiSettingsSSID(), getLastWiFiSettingsPassphrase())) {
// other settings are not correct, switch back.
lastWiFiSettings = tmp;
return false; // Nothing changed.
}
return true;
}
bool selectValidWiFiSettings() {
if (wifiSettingsValid(getLastWiFiSettingsSSID(), getLastWiFiSettingsPassphrase()))
return true;
return selectNextWiFiSettings();
}
bool wifiSettingsValid(const char* ssid, const char* pass) {
if (ssid[0] == 0 || (strcasecmp(ssid, "ssid") == 0)) {
return false;
}
if (pass[0] == 0) return false;
if (strlen(ssid) > 32) return false;
if (strlen(pass) > 64) return false;
return true;
}
bool wifiConnectTimeoutReached() {
if (wifi_connect_attempt == 0) return true;
if (wifiSetupConnect) {
// Initial setup of WiFi, may take much longer since accesspoint is still active.
return timeOutReached(wifi_connect_timer + 20000);
}
// wait until it connects + add some device specific random offset to prevent
// all nodes overloading the accesspoint when turning on at the same time.
#if defined(ESP8266)
const unsigned int randomOffset_in_sec = wifi_connect_attempt == 1 ? 0 : 1000 * ((ESP.getChipId() & 0xF));
#endif
#if defined(ESP32)
const unsigned int randomOffset_in_sec = wifi_connect_attempt == 1 ? 0 : 1000 * ((ESP.getEfuseMac() & 0xF));
#endif
return timeOutReached(wifi_connect_timer + DEFAULT_WIFI_CONNECTION_TIMEOUT + randomOffset_in_sec);
}
//********************************************************************************
// Simply start the WiFi connection sequence
//********************************************************************************
bool tryConnectWiFi() {
if (wifiSetup && !wifiSetupConnect)
return false;
if (WiFi.status() == WL_CONNECTED)
return(true); //already connected, need to disconnect first
if (!wifiConnectTimeoutReached())
return true; // timeout not reached yet, thus no need to retry again.
if (!anyValidWifiSettings())
return false;
if (wifi_connect_attempt != 0 && ((wifi_connect_attempt % 3) == 0)) {
// Change to other wifi settings.
if (selectNextWiFiSettings())
WiFi.disconnect();
}
if (wifi_connect_attempt > 6) {
//everything failed, activate AP mode (will deactivate automatically after a while if its connected again)
WifiAPMode(true);
}
String ssid;
ssid.reserve(32);
String passphrase;
passphrase.reserve(64);
ssid = getLastWiFiSettingsSSID();
passphrase = getLastWiFiSettingsPassphrase();
String log = F("WIFI : Connecting ");
log += ssid;
log += F(" attempt #");
log += wifi_connect_attempt;
addLog(LOG_LEVEL_INFO, log);
wifi_connect_timer = millis();
switch (wifi_connect_attempt) {
case 0:
if (lastBSSID[0] == 0)
WiFi.begin(ssid.c_str(), passphrase.c_str());
else
WiFi.begin(ssid.c_str(), passphrase.c_str(), 0, &lastBSSID[0]);
break;
default:
WiFi.begin(ssid.c_str(), passphrase.c_str());
}
++wifi_connect_attempt;
switch (WiFi.status()) {
case WL_NO_SSID_AVAIL: {
log = F("WIFI : No SSID found matching: ");
log += ssid;
addLog(LOG_LEVEL_INFO, log);
return false;
}
case WL_CONNECT_FAILED: {
log = F("WIFI : Connection failed to: ");
log += ssid;
addLog(LOG_LEVEL_INFO, log);
return false;
}
case WL_CONNECTED:
checkWifiJustConnected();
break;
default:
break;
}
return true; // Sent
}
//********************************************************************************
// Connect to Wifi specific SSID
//********************************************************************************
boolean WifiConnectAndWait(byte connectAttempts)
{
String log;
wifiConnected = false;
wifi_connect_attempt = 0;
for (byte tryConnect = 0; tryConnect < connectAttempts; tryConnect++)
{
if (tryConnectWiFi()) {
do {
if (checkWifiJustConnected())
return true;
delay(50);
} while (!wifiConnectTimeoutReached());
}
// log = F("WIFI : Disconnecting!");
// addLog(LOG_LEVEL_INFO, log);
#if defined(ESP8266)
ETS_UART_INTR_DISABLE();
wifi_station_disconnect();
ETS_UART_INTR_ENABLE();
#endif
for (byte x = 0; x < 20; x++)
{
statusLED(true);
delay(50);
}
}
return false;
}
bool checkWifiJustConnected() {
if (wifiConnected) return true;
delay(1);
if (WiFi.status() != WL_CONNECTED) {
statusLED(false);
return false;
}
wifiConnected = true;
String log = F("WIFI : WiFi connect attempt took: ");
log += timePassedSince(wifi_connect_timer);
log += F(" ms");
addLog(LOG_LEVEL_INFO, log);
// fix octet?
if (Settings.IP_Octet != 0 && Settings.IP_Octet != 255)
{
IPAddress ip = WiFi.localIP();
IPAddress gw = WiFi.gatewayIP();
IPAddress subnet = WiFi.subnetMask();
ip[3] = Settings.IP_Octet;
log = F("IP : Fixed IP octet:");
log += ip;
addLog(LOG_LEVEL_INFO, log);
WiFi.config(ip, gw, subnet);
}
#ifdef FEATURE_MDNS
String log = F("WIFI : ");
if (MDNS.begin(WifiGetHostname().c_str(), WiFi.localIP())) {
log += F("mDNS started, with name: ");
log += WifiGetHostname();
log += F(".local");
}
else{
log += F("mDNS failed");
}
addLog(LOG_LEVEL_INFO, log);
#endif
// First try to get the time, since that may be used in logs
if (Settings.UseNTP) {
initTime();
}
uint8_t* curBSSID = WiFi.BSSID();
bool changed = false;
for (byte i=0; i < 6; ++i) {
if (lastBSSID[i] != *(curBSSID + i)) {
changed = true;
lastBSSID[i] = *(curBSSID + i);
}
}
if (Settings.UseRules)
{
if (changed) {
String event = F("WiFi#ChangedAccesspoint");
rulesProcessing(event);
}
String event = F("WiFi#Connected");
rulesProcessing(event);
}
log = F("WIFI : Connected! IP: ");
log += formatIP(WiFi.localIP());
log += F(" (");
log += WifiGetHostname();
log += F(") AP: ");
log += WiFi.SSID();
log += F(" AP BSSID: ");
log += WiFi.BSSIDstr();
addLog(LOG_LEVEL_INFO, log);
statusLED(true);
return true;
}
//********************************************************************************
// Disconnect from Wifi AP
//********************************************************************************
void WifiDisconnect()
{
WiFi.disconnect();
wifiConnected = false;
}
//********************************************************************************
// Scan all Wifi Access Points
//********************************************************************************
void WifiScan()
{
// Direct Serial is allowed here, since this function will only be called from serial input.
Serial.println(F("WIFI : SSID Scan start"));
int n = WiFi.scanNetworks();
if (n == 0)
Serial.println(F("WIFI : No networks found"));
else
{
Serial.print(F("WIFI : "));
Serial.print(n);
Serial.println(F(" networks found"));
for (int i = 0; i < n; ++i)
{
// Print SSID and RSSI for each network found
Serial.print(F("WIFI : "));
Serial.print(i + 1);
Serial.print(": ");
Serial.print(WiFi.SSID(i));
Serial.print(" (");
Serial.print(WiFi.RSSI(i));
Serial.print(")");
Serial.println("");
delay(10);
}
}
Serial.println("");
}
//********************************************************************************
// Check if we are still connected to a Wifi AP
//********************************************************************************
void WifiCheck()
{
if(wifiSetup)
return;
if (WiFi.status() != WL_CONNECTED)
{
NC_Count++;
//give it time to automatically reconnect
if (NC_Count > 2)
{
if (wifiConnected) {
wifi_connect_attempt = 0;
wifiConnected = false;
WiFiConnectRelaxed();
}
C_Count=0;
NC_Count = 0;
}
}
//connected
else
{
C_Count++;
NC_Count = 0;
if (C_Count > 2) // disable AP after timeout if a Wifi connection is established...
{
WifiAPMode(false);
}
}
if (!wifiConnected) {
if (tryConnectWiFi())
checkWifiJustConnected();
}
}
//********************************************************************************
// Return subnet range of WiFi.
//********************************************************************************
bool getSubnetRange(IPAddress& low, IPAddress& high)
{
if (WifiIsAP()) {
// WiFi is active as accesspoint, do not check.
return false;
}
if (WiFi.status() != WL_CONNECTED) {
return false;
}
const IPAddress ip = WiFi.localIP();
const IPAddress subnet = WiFi.subnetMask();
low = ip;
high = ip;
// Compute subnet range.
for (byte i=0; i < 4; ++i) {
if (subnet[i] != 255) {
low[i] = low[i] & subnet[i];
high[i] = high[i] | ~subnet[i];
}
}
return true;
}