forked from Juerd/ESP-WiFiSettings
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWiFiSettings.cpp
794 lines (689 loc) · 28.8 KB
/
WiFiSettings.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
#include "WiFiSettings.h"
#ifdef ESP32
#define ESPFS SPIFFS
#define ESPMAC (Sprintf("%06" PRIx32, ((uint32_t)(ESP.getEfuseMac() >> 24))))
#include <SPIFFS.h>
#include <WiFi.h>
#include <WebServer.h>
#include <esp_task_wdt.h>
#elif ESP8266
#define ESPFS LittleFS
#define ESPMAC (Sprintf("%06" PRIx32, ESP.getChipId()))
#include <LittleFS.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#define WebServer ESP8266WebServer
#define esp_task_wdt_reset wdt_reset
#define wifi_auth_mode_t uint8_t // wl_enc_type
#define WIFI_AUTH_OPEN ENC_TYPE_NONE
constexpr auto WIFI_AUTH_WPA2_ENTERPRISE = -1337; // not available on ESP8266
#define setHostname hostname
#define INADDR_NONE IPAddress(0,0,0,0)
#else
#error "This library only supports ESP32 and ESP8266"
#endif
#include <DNSServer.h>
#include <limits.h>
#include <vector>
#include <WiFiSettings_strings.h>
WiFiSettingsLanguage::Texts _WSL_T;
#define Sprintf(f, ...) ({ char* s; asprintf(&s, f, __VA_ARGS__); String r = s; free(s); r; })
namespace { // Helpers
String slurp(const String& fn) {
File f = ESPFS.open(fn, "r");
String r = f.readString();
f.close();
return r;
}
bool spurt(const String& fn, const String& content) {
File f = ESPFS.open(fn, "w");
if (!f) return false;
auto w = f.print(content);
f.close();
return w == content.length();
}
String pwgen() {
const char* passchars = "ABCEFGHJKLMNPRSTUXYZabcdefhkmnorstvxz23456789-#@?!";
String password = "";
for (int i = 0; i < 16; i++) {
// Note: no seed needed for ESP8266 and ESP32 hardware RNG
password.concat( passchars[random(strlen(passchars))] );
}
return password;
}
String secure(const String& raw) {
String r;
for (unsigned int i = 0; i < raw.length(); i++) {
r += ' ';
}
return r;
}
String html_entities(const String& raw) {
String r;
for (unsigned int i = 0; i < raw.length(); i++) {
char c = raw.charAt(i);
if (c < '!' || c == '"' || c == '&' || c == '\'' || c == '<' || c == '>' || c == 0x7f) {
// ascii control characters, html syntax characters, and space
r += Sprintf("&#%d;", c);
} else {
r += c;
}
}
return r;
}
struct WiFiSettingsParameter {
String name;
String label;
String value;
String init;
long min = LONG_MIN;
long max = LONG_MAX;
String filename() { String fn = "/"; fn += name; return fn; }
bool store() { return (name && name.length())? spurt(filename(), value): true; }
void fill() { if (name && name.length()) value = slurp(filename()); }
virtual void set(const String&) = 0;
virtual String html() = 0;
};
struct WiFiSettingsDropdown : WiFiSettingsParameter {
virtual void set(const String& v) { value = v; }
std::vector<String> options;
String html()
{
String h = F("<p><label>{label}:<br><select name='{name}' value='{value}' placeholder='{init}'>");
h.replace("{name}", html_entities(name));
h.replace("{value}", html_entities(value));
h.replace("{init}", html_entities(init));
h.replace("{label}", html_entities(label));
int v = value.toInt();
int i = 0;
for (auto &o : options)
{
String opt = F("<option value='{code}'{sel}>{name}</option>");
opt.replace("{code}", String(i));
opt.replace("{name}", o);
opt.replace("{sel}", v == i ? " selected" : "");
h += opt;
i++;
}
h +=(F("</select></label>"));
return h;
}
};
struct WiFiSettingsString : WiFiSettingsParameter {
virtual void set(const String& v) { value = v; }
String html() {
String h = F("<p><label>{label}:<br><input name='{name}' value='{value}' placeholder='{init}' minlength={min} maxlength={max}></label>");
h.replace("{name}", html_entities(name));
h.replace("{value}", html_entities(value));
h.replace("{init}", html_entities(init));
h.replace("{label}", html_entities(label));
h.replace("{min}", String(min));
h.replace("{max}", String(max));
return h;
}
};
struct WiFiSettingsPassword : WiFiSettingsParameter {
virtual void set(const String& v) {
String trimmed = v;
trimmed.trim();
if (trimmed.length()) value = trimmed;
}
String html() {
String h = F("<p><label>{label}:<br><input type='password' name='{name}' value='{value}' placeholder='{init}' minlength={min} maxlength={max}></label>");
h.replace("{name}", html_entities(name));
h.replace("{value}", html_entities(secure(value)));
h.replace("{init}", html_entities(init));
h.replace("{label}", html_entities(label));
h.replace("{min}", String(min));
h.replace("{max}", String(max));
return h;
}
};
struct WiFiSettingsInt : WiFiSettingsParameter
{
virtual void set(const String& v) { value = v; }
String html() {
String h = F("<p><label>{label}:<br><input type=number step=1 min={min} max={max} name='{name}' value='{value}' placeholder='{init}'></label>");
h.replace("{name}", html_entities(name));
h.replace("{value}", html_entities(value));
h.replace("{init}", html_entities(init));
h.replace("{label}", html_entities(label));
h.replace("{min}", String(min));
h.replace("{max}", String(max));
return h;
}
};
struct WiFiSettingsFloat : WiFiSettingsParameter
{
virtual void set(const String &v) { value = v; }
String html()
{
String h = F("<p><label>{label}:<br><input type=number step=0.01 min={min} max={max} name='{name}' value='{value}' placeholder='{init}'></label>");
h.replace("{name}", html_entities(name));
h.replace("{value}", html_entities(value));
h.replace("{init}", html_entities(init));
h.replace("{label}", html_entities(label));
h.replace("{min}", String(min));
h.replace("{max}", String(max));
return h;
}
};
struct WiFiSettingsBool : WiFiSettingsParameter {
virtual void set(const String& v) { value = v.length() ? "1" : "0"; }
String html() {
String h = F("<p><label class=c><input type=checkbox name='{name}' value=1{checked}> {label} ({default}: {init})</label>");
h.replace("{name}", html_entities(name));
h.replace("{default}", _WSL_T.init);
h.replace("{checked}", value.toInt() ? " checked" : "");
h.replace("{init}", init.toInt() ? "☑" : "☐");
h.replace("{label}", html_entities(label));
return h;
}
};
struct WiFiSettingsHTML : WiFiSettingsParameter {
// Raw HTML, not an actual parameter. The reason for the "if (name)"
// in store and fill. Abuses several member variables for completely
// different functionality.
virtual void set(const String& v) { (void)v; }
String html() {
int space = value.indexOf(" ");
String h =
(value ? "<" + value + ">" : "") +
(min ? html_entities(label) : label) +
(value ? "</" + (space >= 0 ? value.substring(0, space) : value) + ">" : "");
return h;
}
};
struct std::vector<WiFiSettingsParameter*> params;
}
String WiFiSettingsClass::pstring(const String& name, const String& init, const String& label) {
begin();
struct WiFiSettingsPassword* x = new WiFiSettingsPassword();
x->name = name;
x->label = label.length() ? label : name;
x->init = init;
x->fill();
params.push_back(x);
return x->value.length() ? x->value : x->init;
}
String WiFiSettingsClass::string(const String& name, const String& init, const String& label) {
begin();
struct WiFiSettingsString* x = new WiFiSettingsString();
x->name = name;
x->label = label.length() ? label : name;
x->init = init;
x->fill();
params.push_back(x);
return x->value.length() ? x->value : x->init;
}
String WiFiSettingsClass::string(const String& name, unsigned int max_length, const String& init, const String& label) {
String rv = string(name, init, label);
params.back()->max = max_length;
return rv;
}
String WiFiSettingsClass::string(const String& name, unsigned int min_length, unsigned int max_length, const String& init, const String& label) {
String rv = string(name, init, label);
params.back()->min = min_length;
params.back()->max = max_length;
return rv;
}
long WiFiSettingsClass::dropdown(const String &name, std::vector<String> options, long init, const String &label) {
begin();
struct WiFiSettingsDropdown* x = new WiFiSettingsDropdown();
x->name = name;
x->label = label.length() ? label : name;
x->init = init;
x->options = options;
x->fill();
params.push_back(x);
return (x->value.length() ? x->value : x->init).toInt();
}
long WiFiSettingsClass::integer(const String& name, long init, const String& label) {
begin();
struct WiFiSettingsInt *x = new WiFiSettingsInt();
x->name = name;
x->label = label.length() ? label : name;
x->init = init;
x->fill();
params.push_back(x);
return (x->value.length() ? x->value : x->init).toInt();
}
long WiFiSettingsClass::integer(const String& name, long min, long max, long init, const String& label) {
long rv = integer(name, init, label);
params.back()->min = min;
params.back()->max = max;
return rv;
}
float WiFiSettingsClass::floating(const String &name, float init, const String &label)
{
begin();
struct WiFiSettingsFloat *x = new WiFiSettingsFloat();
x->name = name;
x->label = label.length() ? label : name;
x->init = init;
x->fill();
params.push_back(x);
return (x->value.length() ? x->value : x->init).toFloat();
}
float WiFiSettingsClass::floating(const String &name, long min, long max, float init, const String &label)
{
float rv = floating(name, init, label);
params.back()->min = min;
params.back()->max = max;
return rv;
}
bool WiFiSettingsClass::checkbox(const String& name, bool init, const String& label) {
begin();
struct WiFiSettingsBool* x = new WiFiSettingsBool();
x->name = name;
x->label = label.length() ? label : name;
x->init = String((int) init);
x->fill();
// Apply default immediately because a checkbox has no placeholder to
// show the default, and other UI elements aren't sufficiently pretty.
if (! x->value.length()) x->value = x->init;
params.push_back(x);
return x->value.toInt();
}
void WiFiSettingsClass::html(const String& tag, const String& contents, bool escape) {
begin();
struct WiFiSettingsHTML* x = new WiFiSettingsHTML();
x->value = tag;
x->label = contents;
x->min = escape;
params.push_back(x);
}
void WiFiSettingsClass::info(const String& contents, bool escape) {
html(F("p class=i"), contents, escape);
}
void WiFiSettingsClass::warning(const String& contents, bool escape) {
html(F("p class=w"), contents, escape);
}
void WiFiSettingsClass::heading(const String& contents, bool escape) {
html("h2", contents, escape);
}
void WiFiSettingsClass::httpSetup()
{
begin();
http.on("/", HTTP_GET, [this]()
{
http.setContentLength(CONTENT_LENGTH_UNKNOWN);
http.send(200, "text/html");
http.sendContent(F("<!DOCTYPE html>\n<meta charset=UTF-8><title>"));
http.sendContent(html_entities(hostname));
http.sendContent(F("</title>"
"<meta name=viewport content='width=device-width,initial-scale=1'>"
"<style>"
"*{box-sizing:border-box} "
"html{background:#444;font:10pt sans-serif}"
"body{background:#ccc;color:black;max-width:30em;padding:1em;margin:1em auto}"
"a:link{color:#000;text-decoration: none} "
"label{clear:both}"
"select,input:not([type^=c]){display:block;width:100%;border:1px solid #444;padding:.3ex}"
"input[type^=s]{display:inline;width:auto;background:#de1;padding:1ex;border:1px solid #000;border-radius:1ex}"
"[type^=c]{float:left;margin-left:-1.5em}"
":not([type^=s]):focus{outline:2px solid #d1ed1e}"
".w::before{content:'\\26a0\\fe0f'}"
"p::before{margin-left:-2em;float:left;padding-top:1ex}"
".i::before{content:'\\2139\\fe0f'}"
".c{display:block;padding-left:2em}"
".w,.i{display:block;padding:.5ex .5ex .5ex 3em}"
".w,.i{background:#aaa;min-height:3em}"
"</style>"
"<form action=/restart method=post>"));
http.sendContent(F("<input type=submit value=\""));
http.sendContent(_WSL_T.button_restart);
http.sendContent(F("\"></form><hr><h1>"));
http.sendContent(_WSL_T.title);
http.sendContent(F("</h1><form method=post><label>"));
if (WiFiSettingsLanguage::multiple())
{
http.sendContent(F("<label>"));
http.sendContent(_WSL_T.language);
http.sendContent(F(":<br><select name=language>"));
for (auto &lang : WiFiSettingsLanguage::languages)
{
String opt = F("<option value='{code}'{sel}>{name}</option>");
opt.replace("{code}", lang.first);
opt.replace("{name}", lang.second);
opt.replace("{sel}", language == lang.first ? " selected" : "");
http.sendContent(opt);
}
http.sendContent(F("</select></label>"));
}
for (auto &p : params)
{
http.sendContent(p->html());
}
http.sendContent(F(
"<p style='position:sticky;bottom:0;text-align:right'>"
"<input type=submit value=\""));
http.sendContent(_WSL_T.button_save);
http.sendContent(F("\"style='font-size:150%'></form>"));
});
http.on("/", HTTP_POST, [this]()
{
bool ok = true;
if (WiFiSettingsLanguage::multiple())
{
if (!spurt("/WiFiSettings-language", http.arg("language"))) ok = false;
}
for (auto &p : params)
{
p->set(http.arg(p->name));
if (!p->store()) ok = false;
}
if (ok)
{
http.sendHeader("Location", "/");
http.send(302, "text/plain", "ok");
if (onConfigSaved) onConfigSaved();
}
else
{
// Could be missing SPIFFS.begin(), unformatted filesystem, or broken flash.
http.send(500, "text/plain", _WSL_T.error_fs);
}
});
http.on("/restart", HTTP_POST, [this]()
{
http.send(200, "text/plain", _WSL_T.bye);
if (onRestart) onRestart();
ESP.restart();
});
http.onNotFound([this]()
{ http.send(404, "text/plain", "404"); });
http.begin();
}
void WiFiSettingsClass::httpLoop()
{
if (!httpBegun)
{
httpBegun = true;
httpSetup();
}
http.handleClient();
}
void WiFiSettingsClass::portal()
{
int num_networks = -1;
begin();
#ifdef ESP32
WiFi.disconnect(true, true); // reset state so .scanNetworks() works
#else
WiFi.disconnect(true);
#endif
WiFi.mode(WIFI_AP);
Serial.println(F("Starting access point for configuration portal."));
if (secure && password.length()) {
Serial.printf("SSID: '%s', Password: '%s'\n", hostname.c_str(), password.c_str());
if (!WiFi.softAP(hostname.c_str(), password.c_str()))
Serial.println("Failed to start access point!");
} else {
Serial.printf("SSID: '%s'\n", hostname.c_str());
if (!WiFi.softAP(hostname.c_str()))
Serial.println("Failed to start access point!");
}
delay(500);
DNSServer dns;
dns.setTTL(0);
dns.start(53, "*", WiFi.softAPIP());
if (onPortal) onPortal();
String ip = WiFi.softAPIP().toString();
Serial.printf("IP: %s\n", ip.c_str());
auto redirect = [this, &ip]()
{
// iPhone doesn't deal well with redirects to http://hostname/ and
// will wait 40 to 60 seconds before succesful retry. Works flawlessly
// with http://ip/ though.
if (http.hostHeader() == ip) return false;
http.sendHeader("Location", "http://" + ip + "/");
// Anecdotally, some devices require a non-empty response body
http.send(302, "text/plain", ip);
return true;
};
const char* headers[] = {"User-Agent"};
http.collectHeaders(headers, sizeof(headers) / sizeof(char*));
http.on("/", HTTP_GET, [this, &num_networks, &redirect]()
{
if (redirect()) return;
String ua = http.header("User-Agent");
bool interactive = !ua.startsWith(F("CaptiveNetworkSupport"));
if (interactive && onPortalView) onPortalView();
if (onUserAgent) onUserAgent(ua);
http.setContentLength(CONTENT_LENGTH_UNKNOWN);
http.send(200, "text/html");
http.sendContent(F("<!DOCTYPE html>\n<meta charset=UTF-8><title>"));
http.sendContent(html_entities(hostname));
http.sendContent(F("</title>"
"<meta name=viewport content='width=device-width,initial-scale=1'>"
"<style>"
"*{box-sizing:border-box} "
"html{background:#444;font:10pt sans-serif}"
"body{background:#ccc;color:black;max-width:30em;padding:1em;margin:1em auto}"
"a:link{color:#000;text-decoration: none} "
"label{clear:both}"
"select,input:not([type^=c]){display:block;width:100%;border:1px solid #444;padding:.3ex}"
"input[type^=s]{display:inline;width:auto;background:#de1;padding:1ex;border:1px solid #000;border-radius:1ex}"
"[type^=c]{float:left;margin-left:-1.5em}"
":not([type^=s]):focus{outline:2px solid #d1ed1e}"
".w::before{content:'\\26a0\\fe0f'}"
"p::before{margin-left:-2em;float:left;padding-top:1ex}"
".i::before{content:'\\2139\\fe0f'}"
".c{display:block;padding-left:2em}"
".w,.i{display:block;padding:.5ex .5ex .5ex 3em}"
".w,.i{background:#aaa;min-height:3em}"
"</style>"
"<form action=/restart method=post>"));
http.sendContent(F("<input type=submit value=\""));
http.sendContent(_WSL_T.button_restart);
http.sendContent(F("\"></form><hr><h1>"));
http.sendContent(_WSL_T.title);
http.sendContent(F("</h1><form method=post><label>"));
http.sendContent(_WSL_T.ssid);
http.sendContent(F(":<br><b class=s>"));
http.sendContent(_WSL_T.scanning_long);
http.sendContent("</b>");
// Don't waste time scanning in captive portal detection (Apple)
if (interactive)
{
if (num_networks < 0) num_networks = WiFi.scanNetworks();
Serial.print(num_networks, DEC);
Serial.println(F(" WiFi networks found."));
}
http.sendContent(F(
"<style>.s{display:none}</style>" // hide "scanning"
"<select name=ssid onchange=\"document.getElementsByName('password')[0].value=''\">"));
String current = slurp("/wifi-ssid");
bool found = false;
for (int i = 0; i < num_networks; i++)
{
String opt = F("<option value='{ssid}'{sel}>{ssid} {lock} {1x}</option>");
String ssid = WiFi.SSID(i);
wifi_auth_mode_t mode = WiFi.encryptionType(i);
opt.replace("{sel}", ssid == current && !found ? " selected" : "");
opt.replace("{ssid}", html_entities(ssid));
opt.replace("{lock}", mode != WIFI_AUTH_OPEN ? "🔒" : "");
opt.replace("{1x}", mode == WIFI_AUTH_WPA2_ENTERPRISE ? _WSL_T.dot1x : F(""));
http.sendContent(opt);
if (ssid == current) found = true;
}
if (!found && current.length())
{
String opt = F("<option value='{ssid}' selected>{ssid} (⚠ not in range)</option>");
opt.replace("{ssid}", html_entities(current));
http.sendContent(opt);
}
http.sendContent(F("</select></label> <a href=/rescan onclick=\"this.innerHTML='"));
http.sendContent(_WSL_T.scanning_short);
http.sendContent("';\">");
http.sendContent(_WSL_T.rescan);
http.sendContent(F("</a><p><label>"));
http.sendContent(_WSL_T.wifi_password);
http.sendContent(F(":<br><input name=password value='"));
if (slurp("/wifi-password").length()) http.sendContent("##**##**##**");
http.sendContent(F("'></label><hr>"));
if (WiFiSettingsLanguage::multiple())
{
http.sendContent(F("<label>"));
http.sendContent(_WSL_T.language);
http.sendContent(F(":<br><select name=language>"));
for (auto &lang : WiFiSettingsLanguage::languages)
{
String opt = F("<option value='{code}'{sel}>{name}</option>");
opt.replace("{code}", lang.first);
opt.replace("{name}", lang.second);
opt.replace("{sel}", language == lang.first ? " selected" : "");
http.sendContent(opt);
}
http.sendContent(F("</select></label>"));
}
for (auto &p : params)
{
http.sendContent(p->html());
}
http.sendContent(F(
"<p style='position:sticky;bottom:0;text-align:right'>"
"<input type=submit value=\""));
http.sendContent(_WSL_T.button_save);
http.sendContent(F("\"style='font-size:150%'></form>"));
});
http.on("/", HTTP_POST, [this]()
{
bool ok = true;
if (!spurt("/wifi-ssid", http.arg("ssid"))) ok = false;
if (WiFiSettingsLanguage::multiple())
{
if (!spurt("/WiFiSettings-language", http.arg("language"))) ok = false;
// Don't update immediately, because there is currently
// no mechanism for reloading param strings.
//language = http.arg("language");
//WiFiSettingsLanguage::select(T, language);
}
String pw = http.arg("password");
if (pw != "##**##**##**")
{
if (!spurt("/wifi-password", pw)) ok = false;
}
for (auto &p : params)
{
p->set(http.arg(p->name));
if (!p->store()) ok = false;
}
if (ok) {
http.sendHeader("Location", "/");
http.send(302, "text/plain", "ok");
if (onConfigSaved) onConfigSaved();
}
else
{
// Could be missing SPIFFS.begin(), unformatted filesystem, or broken flash.
http.send(500, "text/plain", _WSL_T.error_fs);
}
});
http.on("/restart", HTTP_POST, [this]()
{
http.send(200, "text/plain", _WSL_T.bye);
if (onRestart) onRestart();
ESP.restart();
});
http.on("/rescan", HTTP_GET, [this, &num_networks]()
{
http.sendHeader("Location", "/");
http.send(302, "text/plain", _WSL_T.wait);
num_networks = WiFi.scanNetworks();
});
http.onNotFound([this, &redirect]()
{
if (redirect()) return;
http.send(404, "text/plain", "404");
});
http.begin();
for (;;) {
http.handleClient();
dns.processNextRequest();
if (onPortalWaitLoop) onPortalWaitLoop();
esp_task_wdt_reset();
delay(1);
}
}
bool WiFiSettingsClass::connect(bool portal, int wait_seconds) {
begin();
WiFi.mode(WIFI_STA);
String ssid = slurp("/wifi-ssid");
String pw = slurp("/wifi-password");
if (ssid.length() == 0) {
Serial.println(F("First contact!\n"));
this->portal();
}
Serial.print(F("Connecting to WiFi SSID '"));
Serial.print(ssid);
Serial.print(F("'"));
if (onConnect) onConnect();
#if defined(ARDUINO) && ARDUINO < 200 // https://github.com/Juerd/ESP-WiFiSettings/issues/24#issuecomment-995661965
WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE); // arduino-esp32 #2537
#endif
WiFi.setHostname(hostname.c_str());
WiFi.begin(ssid.c_str(), pw.c_str());
unsigned long starttime = millis();
while (WiFi.status() != WL_CONNECTED && (wait_seconds < 0 || (millis() - starttime) < (unsigned)wait_seconds * 1000)) {
Serial.print(".");
delay(onWaitLoop ? onWaitLoop() : 100);
}
if (WiFi.status() != WL_CONNECTED) {
Serial.println(F(" failed."));
if (onFailure) onFailure();
if (portal) this->portal();
return false;
}
Serial.println(WiFi.localIP().toString());
if (onSuccess) onSuccess();
return true;
}
void WiFiSettingsClass::begin() {
if (begun) return;
begun = true;
// These things can't go in the constructor because the constructor runs
// before ESPFS.begin()
String user_language = slurp("/WiFiSettings-language");
user_language.trim();
if (user_language.length() && WiFiSettingsLanguage::available(user_language)) {
language = user_language;
}
WiFiSettingsLanguage::select(_WSL_T, language); // can update language
#ifdef PORTAL_PASSWORD
if (!secure) {
secure = checkbox(
F("WiFiSettings-secure"),
false,
_WSL_T.portal_wpa
);
}
if (!password.length()) {
password = string(
F("WiFiSettings-password"),
8, 63,
"",
_WSL_T.portal_password
);
if (password == "") {
// With regular 'init' semantics, the password would be changed
// all the time.
password = pwgen();
params.back()->set(password);
params.back()->store();
}
}
#endif
if (hostname.endsWith("-")) hostname += ESPMAC;
}
WiFiSettingsClass::WiFiSettingsClass() : http(80)
{
#ifdef ESP32
hostname = F("esp32-");
#else
hostname = F("esp8266-");
#endif
language = "en";
}
WiFiSettingsClass WiFiSettings;