Repository navigation
Expand file tree
/
Copy pathWiFiManagerOTA.cpp
More file actions
636 lines (560 loc) · 15.5 KB
/
Copy pathWiFiManagerOTA.cpp
File metadata and controls
636 lines (560 loc) · 15.5 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
#include "WiFiManagerOTA.h"
#include <LittleFS.h>
#include <Preferences.h>
#include "gpad_utility.h"
namespace
{
const char *WIFI_CREDENTIALS_PATH = "/wifi.json";
const char *WIFI_PREFERENCES_NAMESPACE = "krake-wifi";
const char *WIFI_PREFERENCES_KEY = "networks";
const unsigned long WIFI_PORTAL_TIMEOUT_SECONDS = 60;
const unsigned long WIFI_STORED_CREDENTIALS_BUDGET_MS = 15000;
const unsigned long WIFI_STORED_CREDENTIAL_ATTEMPT_MS = 5000;
bool littleFsMounted = false;
bool saveCredentialsToPreferences(const String &payload)
{
Preferences preferences;
if (!preferences.begin(WIFI_PREFERENCES_NAMESPACE, false))
{
return false;
}
const size_t written = preferences.putString(WIFI_PREFERENCES_KEY, payload);
preferences.end();
return written > 0;
}
String loadCredentialsFromPreferences()
{
Preferences preferences;
if (!preferences.begin(WIFI_PREFERENCES_NAMESPACE, true))
{
return String();
}
const String payload = preferences.getString(WIFI_PREFERENCES_KEY, "");
preferences.end();
return payload;
}
bool clearCredentialsFromPreferences()
{
Preferences preferences;
if (!preferences.begin(WIFI_PREFERENCES_NAMESPACE, false))
{
return false;
}
const bool cleared = !preferences.isKey(WIFI_PREFERENCES_KEY) || preferences.remove(WIFI_PREFERENCES_KEY);
preferences.end();
return cleared;
}
String jsonEscape(const String &value)
{
String escaped;
escaped.reserve(value.length() + 8);
for (size_t i = 0; i < value.length(); ++i)
{
const char ch = value.charAt(i);
if (ch == '\\' || ch == '"')
{
escaped += '\\';
}
escaped += ch;
}
return escaped;
}
bool parseJsonStringAt(const String &json, int keyPos, String &value, int *valueEndPos = nullptr)
{
if (keyPos < 0)
{
return false;
}
const int colonPos = json.indexOf(':', keyPos);
if (colonPos < 0)
{
return false;
}
int quoteStart = json.indexOf('"', colonPos + 1);
if (quoteStart < 0)
{
return false;
}
String parsed;
bool escaped = false;
for (int i = quoteStart + 1; i < json.length(); ++i)
{
const char ch = json.charAt(i);
if (escaped)
{
parsed += ch;
escaped = false;
continue;
}
if (ch == '\\')
{
escaped = true;
continue;
}
if (ch == '"')
{
value = parsed;
if (valueEndPos != nullptr)
{
*valueEndPos = i;
}
return true;
}
parsed += ch;
}
return false;
}
bool extractJsonString(const String &json, const char *key, String &value, int startPos = 0, int *valueEndPos = nullptr)
{
const String keyToken = String("\"") + key + "\"";
const int keyPos = json.indexOf(keyToken, startPos);
if (keyPos < 0)
{
return false;
}
return parseJsonStringAt(json, keyPos + keyToken.length(), value, valueEndPos);
}
}
const char *DEFAULT_SSID = "ESP32-Setup"; // Default AP Name
String ssid_wf = "";
String password_wf = "";
String ledState = "";
int WiFiLed = 2; // Modify based on actual LED pin
using namespace WifiOTA;
Manager::Manager(WiFiClass &wifi, Print &print)
: wifi(wifi), print(print), connectedCallback(nullptr), apStartedCallback(nullptr)
{
}
void Manager::initialize()
{
// According to WifiManager's documentation, best practice is still to set the WiFi mode manually
// https://github.com/tzapu/WiFiManager/blob/master/examples/Basic/Basic.ino#L5
this->wifi.mode(WIFI_STA);
// Never leave setup blocked forever if credentials were erased or invalid.
this->wifiManager.setConfigPortalTimeout(WIFI_PORTAL_TIMEOUT_SECONDS);
}
Manager::~Manager() {}
void Manager::connect(const char *const accessPointSsid)
{
if (this->connectSavedCredentials(WIFI_STORED_CREDENTIALS_BUDGET_MS))
{
return;
}
this->print.println(F("Starting bounded WiFi recovery portal."));
this->startPortal(accessPointSsid);
}
bool Manager::connectSavedCredentials(unsigned long budgetMs)
{
CredentialList credentials;
if (!this->loadCredentialsList(credentials) || credentials.count == 0)
{
return false;
}
const unsigned long credentialsStartMs = millis();
for (size_t index = 0; index < credentials.count; ++index)
{
const uint32_t elapsedMs = elapsedMillis(millis(), credentialsStartMs);
if (elapsedMs >= budgetMs)
{
this->print.println(F("Stored WiFi retry budget exhausted."));
return false;
}
const unsigned long remainingMs = budgetMs - elapsedMs;
const unsigned long attemptMs = (remainingMs < WIFI_STORED_CREDENTIAL_ATTEMPT_MS)
? remainingMs
: WIFI_STORED_CREDENTIAL_ATTEMPT_MS;
#if (DEBUG_LEVEL > 0)
this->print.print(F("Trying saved WiFi "));
this->print.print(index + 1);
this->print.print(F("/"));
this->print.print(credentials.count);
this->print.print(F(": "));
this->print.println(credentials.items[index].ssid);
#endif
if (this->connectStoredCredentials(credentials.items[index].ssid, credentials.items[index].password, attemptMs))
{
this->print.println(F("Connected using stored WiFi credentials."));
this->ipSet();
return true;
}
}
return false;
}
void Manager::startPortal(const char *const accessPointSsid)
{
auto saveConfigCallback = [this]()
{
this->ssidSaved();
};
this->wifiManager.setSaveConfigCallback(saveConfigCallback);
auto apStartedCallback = [this](WiFiManager *wifiManager)
{
this->apStarted();
};
this->wifiManager.setAPCallback(apStartedCallback);
auto staGotIpCallback = [this](arduino_event_id_t event, arduino_event_info_t info)
{
if ((this->wifi.localIP() == INADDR_NONE) && (this->getMode() == wifi_mode_t::WIFI_MODE_STA))
{
return;
}
this->ipSet();
};
this->wifi.onEvent(staGotIpCallback, arduino_event_id_t::ARDUINO_EVENT_WIFI_STA_GOT_IP);
bool connectSuccess = false;
if (accessPointSsid == nullptr || accessPointSsid[0] == '\0')
{
connectSuccess = this->wifiManager.autoConnect(DEFAULT_SSID);
}
else
{
connectSuccess = this->wifiManager.autoConnect(accessPointSsid);
}
if (!connectSuccess)
{
this->print.println(F("WiFiManager recovery portal timed out; continuing device startup."));
}
}
void Manager::setConnectedCallback(Callback callback)
{
this->connectedCallback = callback;
}
void Manager::setApStartedCallback(Callback callback)
{
this->apStartedCallback = callback;
}
wifi_mode_t Manager::getMode()
{
return this->wifi.getMode();
}
void Manager::startConfigPortal(const char *const accessPointSsid, unsigned long timeoutSeconds)
{
this->wifiManager.setConfigPortalTimeout(timeoutSeconds);
this->startPortal(accessPointSsid);
}
bool Manager::forgetSavedCredentials()
{
this->wifiManager.resetSettings();
const bool preferencesCleared = clearCredentialsFromPreferences();
bool mirrorCleared = true;
if (littleFsMounted && LittleFS.exists(WIFI_CREDENTIALS_PATH))
{
mirrorCleared = LittleFS.remove(WIFI_CREDENTIALS_PATH);
}
return preferencesCleared && mirrorCleared;
}
IPAddress Manager::getAddress()
{
switch (this->getMode())
{
case wifi_mode_t::WIFI_MODE_AP:
return this->wifi.softAPIP();
case wifi_mode_t::WIFI_MODE_STA:
return this->wifi.localIP();
case wifi_mode_t::WIFI_MODE_APSTA:
return (this->wifi.status() == WL_CONNECTED) ? this->wifi.localIP() : this->wifi.softAPIP();
default:
return INADDR_NONE;
}
}
bool Manager::saveCredentials(const String &ssid, const String &password)
{
String trimmedSsid = ssid;
String checkedPassword = password;
trimmedSsid.trim();
checkedPassword.trim();
if (trimmedSsid.length() == 0 || checkedPassword.length() == 0)
{
this->print.println(F("SSID and password are required."));
return false;
}
CredentialList credentials;
this->loadCredentialsList(credentials);
CredentialList updated;
updated.count = 0;
updated.items[updated.count++] = {trimmedSsid, password};
for (size_t i = 0; i < credentials.count; ++i)
{
if (credentials.items[i].ssid != trimmedSsid && updated.count < MAX_SAVED_WIFI_NETWORKS)
{
updated.items[updated.count++] = credentials.items[i];
}
}
String payload = "{\"networks\":[";
for (size_t i = 0; i < updated.count; ++i)
{
if (i > 0)
{
payload += ",";
}
payload += "{\"ssid\":\"";
payload += jsonEscape(updated.items[i].ssid);
payload += "\",\"password\":\"";
payload += jsonEscape(updated.items[i].password);
payload += "\"}";
}
payload += "]}";
if (!saveCredentialsToPreferences(payload))
{
this->print.println(F("Failed to save WiFi credentials to NVS."));
return false;
}
// Keep a LittleFS mirror for backward compatibility and diagnostics. The NVS
// copy remains authoritative because uploading a filesystem image erases this file.
if (littleFsMounted)
{
File file = LittleFS.open(WIFI_CREDENTIALS_PATH, "w");
if (!file)
{
this->print.println(F("Warning: failed to mirror WiFi credentials to wifi.json."));
}
else
{
file.print(payload);
file.close();
}
}
return true;
}
bool Manager::hasSavedCredentials()
{
return loadCredentialsFromPreferences().length() > 0 ||
(littleFsMounted && LittleFS.exists(WIFI_CREDENTIALS_PATH));
}
bool Manager::loadCredentials(String &ssid, String &password)
{
CredentialList credentials;
if (!this->loadCredentialsList(credentials) || credentials.count == 0)
{
return false;
}
ssid = credentials.items[0].ssid;
password = credentials.items[0].password;
return true;
}
bool Manager::loadCredentialsList(CredentialList &credentials)
{
credentials.count = 0;
String content = loadCredentialsFromPreferences();
if (content.length() == 0 && littleFsMounted && LittleFS.exists(WIFI_CREDENTIALS_PATH))
{
File file = LittleFS.open(WIFI_CREDENTIALS_PATH, "r");
if (!file)
{
this->print.println(F("Failed to open wifi.json for reading."));
return false;
}
content = file.readString();
file.close();
if (content.length() > 0)
{
saveCredentialsToPreferences(content);
}
}
if (content.length() == 0)
{
return false;
}
int searchPos = 0;
while (credentials.count < MAX_SAVED_WIFI_NETWORKS)
{
const int ssidKeyPos = content.indexOf("\"ssid\"", searchPos);
if (ssidKeyPos < 0)
{
break;
}
String loadedSsid;
int ssidEndPos = -1;
if (!extractJsonString(content, "ssid", loadedSsid, ssidKeyPos, &ssidEndPos))
{
break;
}
const int passwordKeyPos = content.indexOf("\"password\"", ssidEndPos);
if (passwordKeyPos < 0)
{
break;
}
String loadedPassword;
int passwordEndPos = -1;
if (!extractJsonString(content, "password", loadedPassword, passwordKeyPos, &passwordEndPos))
{
break;
}
loadedSsid.trim();
String checkedPassword = loadedPassword;
checkedPassword.trim();
if (loadedSsid.length() > 0 && checkedPassword.length() > 0)
{
bool alreadyExists = false;
for (size_t i = 0; i < credentials.count; ++i)
{
if (credentials.items[i].ssid == loadedSsid)
{
alreadyExists = true;
break;
}
}
if (!alreadyExists)
{
credentials.items[credentials.count++] = {loadedSsid, loadedPassword};
}
}
searchPos = passwordEndPos + 1;
}
if (credentials.count > 0)
{
return true;
}
// Backward compatibility with legacy single-network format.
String legacySsid;
String legacyPassword;
if (!extractJsonString(content, "ssid", legacySsid) || !extractJsonString(content, "password", legacyPassword))
{
this->print.println(F("Stored WiFi credentials are missing required keys."));
return false;
}
legacySsid.trim();
String checkedLegacyPassword = legacyPassword;
checkedLegacyPassword.trim();
if (legacySsid.length() == 0 || checkedLegacyPassword.length() == 0)
{
this->print.println(F("Stored WiFi credentials have an invalid SSID/password."));
return false;
}
credentials.items[credentials.count++] = {legacySsid, legacyPassword};
return true;
}
bool Manager::connectStoredCredentials(const String &ssid, const String &password, unsigned long timeoutMs)
{
#if (DEBUG_LEVEL > 0)
this->print.print(F("Attempting connection using saved WiFi SSID: "));
this->print.println(ssid);
#endif
this->wifi.begin(ssid.c_str(), password.c_str());
const unsigned long startMs = millis();
while (!millisIntervalElapsed(millis(), startMs, timeoutMs))
{
if (this->wifi.status() == WL_CONNECTED)
{
return true;
}
delay(250);
}
this->print.println(F("Stored WiFi credentials failed to connect."));
this->wifi.disconnect(false, false);
return false;
}
void Manager::ssidSaved()
{
const String savedSsid = this->wifi.SSID();
const String savedPassword = this->wifi.psk();
#if (DEBUG_LEVEL > 0)
this->print.print(F("Network Saved with SSID: "));
this->print.print(savedSsid);
this->print.print(F("\n"));
#endif
if (savedSsid.length() > 0 && savedPassword.length() > 0)
{
this->saveCredentials(savedSsid, savedPassword);
}
else
{
this->print.println(F("WiFi portal saved credentials, but SSID/password were not available for multi-network storage."));
}
}
void Manager::ipSet()
{
#if (DEBUG_LEVEL > 0)
this->print.print(F("Connected to Network: "));
this->print.print(this->wifi.SSID());
this->print.print(F("\n"));
this->print.print(F("Obtained IP Address: "));
this->wifi.localIP().printTo(Serial);
this->print.print(F("\n"));
#endif
if (this->connectedCallback)
{
this->connectedCallback();
}
}
void Manager::apStarted()
{
#if (DEBUG_LEVEL > 0)
this->print.print(F("AP Has Started: "));
this->wifi.softAPIP().printTo(this->print);
this->print.print(F("\n"));
#endif
if (this->apStartedCallback)
{
this->apStartedCallback();
}
}
bool WifiOTA::initLittleFS()
{
littleFsMounted = LittleFS.begin(false);
if (!littleFsMounted)
{
Serial.println(F("LittleFS mount failed. Filesystem unavailable; refusing to auto-format."));
Serial.println(F("Upload the LittleFS image or format explicitly during service."));
return false;
}
printLittleFSDiagnostics(Serial);
return true;
}
bool WifiOTA::isLittleFSMounted()
{
return littleFsMounted;
}
void WifiOTA::printLittleFSDiagnostics(Print &print)
{
print.println(F("=== LittleFS diagnostics ==="));
print.print(F("Mounted: "));
print.println(littleFsMounted ? F("yes") : F("no"));
if (!littleFsMounted)
{
print.println(F("============================"));
return;
}
print.print(F("Total bytes: "));
print.println(LittleFS.totalBytes());
print.print(F("Used bytes: "));
print.println(LittleFS.usedBytes());
File root = LittleFS.open("/");
if (!root || !root.isDirectory())
{
print.println(F("Unable to list filesystem root."));
print.println(F("============================"));
return;
}
File file = root.openNextFile();
if (!file)
{
print.println(F("Filesystem root is empty. Upload the LittleFS image."));
}
while (file)
{
print.print(F(" "));
print.print(file.name());
print.print(F(" ("));
print.print(file.size());
print.println(F(" bytes)"));
file = root.openNextFile();
}
print.println(F("============================"));
}
String WifiOTA::processor(const String &var)
{
if (var == "STATE")
{
if (digitalRead(WiFiLed))
{
ledState = "ON";
}
else
{
ledState = "OFF";
}
return ledState;
}
return String();
}