-
Notifications
You must be signed in to change notification settings - Fork 4
/
Portal.cpp
768 lines (566 loc) · 20.2 KB
/
Portal.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
/*
Portal.cpp - Handle the webserver interface
Saul bertuccio 11 feb 2017
Released into the public domain.
*/
#include "Portal.h"
Portal::Portal():message(String("")) {}
boolean Portal::setup() {
IPAddress ip = ConnectionManager::getIpAddress();
if (ip.toString() == "0.0.0.0") {
Serial.println("Indirizzo IP non valido");
return false;
}
ap_mode = ConnectionManager::isApMode();
// Avvio captive portal
if (ap_mode) {
dnsServer.reset(new DNSServer());
dnsServer->setErrorReplyCode(DNSReplyCode::NoError);
if (dnsServer->start(DNS_PORT, "*", ip)) {
Serial.println("Avviato servizio DNS");
} else {
Serial.println("Impossibile avviare servizio DNS");
}
}
/* Configuro il webserver */
server.reset(new ESP8266WebServer(SERVER_PORT));
/* Bind delle url alle funzioni */
server->on("/", std::bind(&Portal::handleRootPage, this));
server->on("/setup/wifi", std::bind(&Portal::handleSetupWifi, this));
server->on("/setup/wifilist", std::bind(&Portal::handleWifiList, this));
server->on("/setup/savewifi", std::bind(&Portal::handleSaveWifi, this));
server->on("/sendKey", std::bind(&Portal::handleSendKey, this));
/* For CORS options requests
server->on("/sendKey", HTTP_OPTIONS, [&]() {
server->sendHeader("Access-Control-Max-Age", "10000");
server->sendHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
server->sendHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
server->send(200, "text/plain", "" );
});
*/
if (!ap_mode) {
server->serveStatic("/js", SPIFFS, "/js");
server->on("/setup/devices", std::bind(&Portal::handleSetupDevices, this));
server->on("/setup/editDevice", std::bind(&Portal::handleEditDevice, this));
server->on("/setup/getKeyPanel", std::bind(&Portal::handleGetKeyPanel, this));
server->on("/setup/deleteDevice", std::bind(&Portal::handleDeleteDevice, this));
server->on("/setup/getDeviceInfo", std::bind(&Portal::handleGetDeviceInfo, this));
server->on("/setup/editDeviceKey", std::bind(&Portal::handleEditDeviceKey, this));
server->on("/setup/acquireKeyData", std::bind(&Portal::handleAcquireKeyData, this));
server->on("/setup/deleteDeviceKey", std::bind(&Portal::handleDeleteDeviceKey, this));
}
server->onNotFound (std::bind(&Portal::handleNotFound, this));
server->begin(); // Web server start
dh = DeviceHandler();
Serial.println("Avviato server HTTP");
/*
if (!ap_mode) {
MDNS.begin(AP_SSID);
MDNS.addService("http", "tcp", 80);
delay(1000);
//Serial.println("Avviato servizio mDNS");
}
*/
return true;
}
boolean Portal::needRestart() { return need_restart; }
void Portal::handleRequest() {
if (ap_mode)
dnsServer->processNextRequest();
server->handleClient();
}
void Portal::handleRootPage() {
if (redirect())
return;
String page = this->basePage();
page.replace("{onready}", "");
page.replace("{message}", message);
page.replace("{body}", getMainMenu());
page.replace("{script}","");
server->send(200, "text/html", page);
}
void Portal::handleSaveWifi() {
// get post data
String new_ssid = server->arg("ssid");
String new_pass = server->arg("password");
String msg;
message = getMessageTpl();
boolean success = ConnectionManager::connectWifi(new_ssid, new_pass, true);
if (!success) {
Serial.print("Impossibile collegarsi alla rete Wifi ");
message.replace("{class}", "error");
msg = "Errore impossibile collegarsi alla rete senza fili ";
msg += new_ssid;
} else {
message.replace("{class}", "info");
msg = "Connessione riuscita il dispositivo si riavvierà per completare la configurazione.";
need_restart = true;
}
message.replace("{message}", msg);
redirectHeaders("/setup");
}
void Portal::handleSendKey() {
String device_name="", key_name="", msg="";
boolean error = true;
if(server->hasArg("device_name") && server->hasArg("key_name")) {
device_name = server->arg("device_name");
key_name = server->arg("key_name");
if (
Validation::isValidDeviceName(device_name)
&&Validation::isValidDeviceName(key_name)
) {
if (dh.setDevice( device_name ) ) {
Device & d = dh.getDevice();
if (d.sendKeyData(key_name)) {
msg="Invio tasto riuscito";
error = false;
} else {
msg="Errore: impossibile inviare tasto";
}
} else {
msg="Errore: impossibile selezionare dispositivo";
}
} else {
msg = "Errore: parametri non validi";
}
} else {
msg = "Errore: parametri assenti";
}
String json = "{ \"error\" :";
json += (error ? String("true") : String("false"));
json += String(",\"message\" : \"") + msg + "\" }";
server->send( 200, "text/json", json );
}
void Portal::handleEditDevice() {
String device_name="", device_type="";
String msg;
bool error = true;
if(!server->hasArg("device_name") || !server->hasArg("device_type")) {
msg = "Errore: nome o tipo dispositivo non specificati";
} else {
device_name = server->arg("device_name");
device_type = server->arg("device_type");
if (!Validation::isValidDeviceName(device_name)) {
msg = "Errore: nome dispositivo non valido";
} else if (!Validation::isValidDeviceType(device_type)) {
msg = "Errore: tipo dispositivo non valido";
} else if (dh.setDevice( device_name, device_type )) {
if (server->hasArg("new_device_name")) {
String new_device_name = server->arg("new_device_name");
if (Validation::isValidDeviceName(new_device_name)) {
if (dh.renameDevice(new_device_name)) {
error = false;
msg = "Dispositivo rinominato";
device_name = new_device_name;
} else {
msg = "Errore: impossibile rinominare il dispositivo";
}
} else {
msg = "Errore: nuovo nome del dispositivo non valido";
}
} else {
error = false;
msg = "Dispositivo correttamente configurato";
}
} else {
msg = "Errore: impossibile configurare il dispositivo";
}
}
String json = "{ \"error\" :";
json += (error ? String("true") : String("false"));
json += String(",\"message\":\"") + msg + "\"}";
server->send( 200, "text/json", json );
}
void Portal::handleDeleteDevice() {
String device_name="", msg="\"\"";
bool error = true;
if(!server->hasArg("device_name")) {
msg = "Errore: nome dispositivo non specificato";
} else {
device_name = server->arg("device_name");
if (!Validation::isValidDeviceName(device_name)) {
msg = "Errore: nome dispositivo non valido";
} else if (dh.setDevice(device_name)) {
if (dh.deleteDevice()) {
error = false;
msg = "Dispositivo eliminato correttamente";
} else {
msg = "Errore: impossibile eliminare il dispositivo";
}
}
}
String json = "{\"error\":";
json += (error ? String("true") : String("false"));
json += String(",\"message\":\"") + msg + "\"}";
server->send( 200, "text/json", json );
}
void Portal::handleGetDeviceInfo() {
String device_name="", msg="";
String dev_data;
bool error = true;
if(!server->hasArg("device_name")) {
msg = "Errore: nome dispositivo non specificato";
} else {
device_name = server->arg("device_name");
if (!Validation::isValidDeviceName(device_name)) {
msg = "Errore: nome dispositivo non valido";
} else if (dh.setDevice(device_name)) {
dev_data = getDeviceData(dh.getDevice());
error = false;
} else {
msg = "Errore: impossibile selezionare il dispositivo";
}
}
String json = "{\"error\":";
json += (error ? String("true") : String("false"));
json += String(",\"device\": {") + dev_data + '}';
json += String(",\"message\":\"") + msg + "\"}";
server->send( 200, "text/json", json );
}
void Portal::handleGetKeyPanel() {
String html_tpl;
if(server->hasArg("device_type") && server->hasArg("template_type")) {
String device_type = server->arg("device_type");
String template_type = server->arg("template_type");
device_type.toUpperCase();
template_type.toUpperCase();
// IRDA
if (device_type == Device::TYPES[0]) {
if (template_type == "DEV_PANE")
html_tpl = FPSTR(HTML_DEV_PANE_IRDA_TPL);
else if ( template_type == "FORM_EDIT" )
html_tpl = FPSTR(HTML_FORM_EDIT_IRDA_KEY);
// RF433
} else if (device_type == Device::TYPES[1]) {
if (template_type == "DEV_PANE")
html_tpl = FPSTR(HTML_DEV_PANE_RF433_TPL);
else if ( template_type == "FORM_EDIT" )
html_tpl = FPSTR(HTML_FORM_EDIT_RF433_KEY);
}
}
server->send(200, "text/html", html_tpl);
}
void Portal::handleEditDeviceKey() {
String
msg = "",
device_name = "",
device_key = "{ "
;
bool error = true;
if(!server->hasArg("device_name")) {
msg = "Errore: nome dispositivo non specificato";
} else {
device_name = server->arg("device_name");
if (!Validation::isValidDeviceName(device_name)) {
msg = "Errore: nome dispositivo non valido";
} else if (dh.setDevice(device_name)) {
Device & d = dh.getDevice();
int num = d.getKeysPropertyNum();
String * names = d.getKeysPropertyNames();
String values[num];
error = false;
for (int i = 0; i < num; i++) {
String form_input = "device_key_" + names[i];
if(
server->hasArg(form_input)
&& d.isValidPropertyById(i, server->arg(form_input))
) {
values[i] = server->arg(form_input);
device_key += "\"" + names[i] + "\":\"" + values[i] + "\",";
} else {
error = true;
msg = "Errore parametro " + names[i] + " non valido";
break;
}
}
delete[] names;
device_key.setCharAt(device_key.length() - 1, ' ');
if (!error) {
if (dh.addDeviceKey(values)) {
msg = "Tasto aggiunto al dispositivo";
} else {
msg = "Errore impossibile salvare la configurazione del tasto";
error = true;
}
}
} else {
msg = "Errore: impossibile configurare il dispositivo";
}
}
device_key.setCharAt(device_key.length() - 1, '}');
String json = "{ \"error\" :";
json += (error ? String("true") : String("false"));
json += String(",\"message\":\"") + msg + "\"";
json += String(",\"key\":") + device_key + "}";
server->send( 200, "text/json", json );
}
void Portal::handleDeleteDeviceKey() {
String
msg = "",
device_name = "",
device_key_name = "";
bool error = true;
if(!server->hasArg("device_name")
|| !server->hasArg("device_key_name")
) {
msg = "Errore: paramentri mancanti";
} else {
device_name = server->arg("device_name");
device_key_name = server->arg("device_key_name");
if (!Validation::isValidDeviceName(device_name)) {
msg = "Errore: nome dispositivo non valido";
} else if (!Validation::isValidDeviceKeyName(device_key_name)) {
msg = "Errore: nome tasto non valido";
} else if (!dh.setDevice( device_name )) {
msg = "Errore: impossibile configurare il dispositivo";
} else if (dh.deleteDeviceKey( device_key_name)) {
msg = "Tasto eliminato dal dispositivo";
error = false;
} else {
msg = "Errore: impossibile salvare la configurazione del dispositivo";
}
}
String json = "{ \"error\" :";
json += (error ? String("true") : String("false"));
json += String(",\"message\":\"") + msg + "\"}";
server->send( 200, "text/json", json );
}
void Portal::handleWifiList() {
WifiNetworks nets = ConnectionManager::getNetworkList();
String json = "{\"networks\":[";
String prot;
for (int i = 0; i < nets.netNum(); i++) {
prot = ConnectionManager::encryptionCodeToString(nets.getProtection(i));
json += String("{ \"name\" : \"") + nets.getName(i) + "\",";
json += String("\"protection\":\"") + prot + "\",";
json += String("\"quality\":\"") + nets.getQuality(i) + "\"},";
}
json.setCharAt(json.length() - 1, ' ');
json += "]}";
server->send( 200, "text/json", json );
}
void Portal::handleSetupWifi() {
String body = FPSTR(HTML_PAGE_HEADER);
body.replace("{btext}", "Impostazione dispositivi e tasti");
body.replace("{stext}","");
body += (ap_mode ? FPSTR(HTML_SIMPLE_WIFI_FORM) : FPSTR(HTML_FULL_WIFI_FORM));
body.replace("{ssid}", ConnectionManager::getSsid());
body.replace("{password}", ConnectionManager::getPassword());
String page = basePage();
page.replace("{body}", body);
page.replace("{onready}", FPSTR(JAVASCRIPT_NETLIST));
page.replace("{script}", "");
page.replace("{warn}", FPSTR(HTML_WIFISAVE_WARNING));
server->send(200, "text/html", page);
}
void Portal::handleSetupDevices() {
String body = FPSTR(HTML_PAGE_HEADER);
body.replace("{btext}", "Impostazione dispositivi e tasti");
body.replace("{stext}","");
body += getDevPanel();
String page = basePage();
page.replace("{body}", body);
page.replace("{onready}", FPSTR(JAVASCRIPT_DEVICE_ONLOAD));
page.replace("{script}", FPSTR(JAVASCRIPT_DEVICE_FUNCTIONS));
server->send(200, "text/html", page);
}
void Portal::handleAcquireKeyData() {
String device_name = "", msg = "", kjattr = "{}";
bool error = true;
if(!server->hasArg("device_name")) {
msg = "Errore: nome dispositivo non specificato";
} else {
device_name = server->arg("device_name");
if (!Validation::isValidDeviceName(device_name)) {
msg = "Errore: nome dispositivo non valido";
} else if (dh.setDevice(device_name)) {
Device & d = dh.getDevice();
int num = d.getKeysPropertyNum();
Key * key = NULL;
error = false;
if (key = d.acquireKeyData()) {
kjattr = Portal::keyAttrToJson(num, key);
delete key;
}
} else {
msg = "Errore: impossibile configurare il dispositivo";
}
}
String json = "{ \"error\" :";
json += (error ? String("true") : String("false"));
json += String(",\"message\":\"") + msg + "\",";
json += "\"key_data\":" + kjattr + "}";
server->send( 200, "text/json", json );
}
void Portal::handleNotFound() {
if (redirect())
return;
String page = this->basePage();
page.replace("{onready}", "");
page.replace("{script}","");
String body = FPSTR(HTML_404_TPL);
int sargs = server->args();
body.replace( "{uri}", server->uri() );
body.replace( "{method}", server->method() == HTTP_GET ? String("GET") : String("POST" ) );
body.replace( "{args}", String(sargs) );
String arglist = "";
for ( int i = 0; i < sargs; i++ ) {
arglist += "<li><span class=\"text-muted\">" + server->argName( i ) +": </span>";
arglist += "<span class=\"text-success\">" + server->arg( i ) + "</span></li>";
}
body.replace("{arglist}", arglist);
page.replace("{body}", body);
server->sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
server->sendHeader("Pragma", "no-cache");
server->sendHeader("Expires", "-1");
server->send( 404, "text/html", page );
}
String Portal::basePage() {
String page = FPSTR(ap_mode ? HTML_SIMPLE_TPL : HTML_FULL_TPL);
String appdata = FPSTR(APP_NAME);
appdata += " ver .";
appdata += FPSTR(APP_VER);
page.replace("{title}", appdata);
page.replace("{message}", message);
return page;
}
String Portal::getMessageTpl() {
return FPSTR(ap_mode ? HTML_SIMPLE_ALERT_TPL : HTML_FULL_ALERT_TPL);
}
boolean Portal::redirect() {
if ( ap_mode && !ConnectionManager::isIp(server->hostHeader())) {
Serial.println("Richiesto un hostname redirigo la richiesta verso l'ip locale.");
this->redirectHeaders(String("http://") + server->client().localIP().toString());
return true;
}
return false;
}
void Portal::redirectHeaders(String where) {
Serial.println("Redirigo la richiesta verso ");
Serial.println(where);
server->sendHeader("Location", where, true);
// nessuna intestazione Content-length, perchè non inviamo contenuto
server->send ( 302, "text/plain", "");
// è necessario chiudere la connessione manualmente
server->client().stop();
}
String Portal::getDevPanel() {
String devpane = FPSTR(HTML_DEV_PANEL);
String * list = DeviceHandler::getDevicesName();
int dn = DeviceHandler::getDevicesNum();
devpane += prepareModal(
String("device-edit"),
String("Modifica/Crea dispositivo"),
prepareDeviceForm(),
"saveDeviceData"
);
devpane += prepareModal(
String("device-delete"),
String("Elimina dispositivo"),
String("Eliminare il dispositivo <b class=\"device-name\"></b> e i comandi configurati?"),
"deleteDevice"
);
devpane += prepareModal(
String("device-key-edit"),
String("Tasto dispositivo"),
"",
"saveDeviceKey"
);
devpane += prepareModal(
String("device-key-delete"),
String("Elimina tasto"),
String("Eliminare il tasto <b class=\"device-key-name\"></b> del dispositivo <i class=\"device-name\"></i>"),
"deleteDeviceKey"
);
String panelbody = FPSTR(HTML_DEV_LIST_TPL);
panelbody += "<div id=\"device-template\" class=\"hidden\">";
panelbody += FPSTR(HTML_DEV_LI_TPL);
panelbody += FPSTR(HTML_DEV_PANE_TPL);
panelbody += "</div>";
String alert = FPSTR(HTML_FULL_ALERT_TPL);
alert.replace("{message}", "Nessun dispositivo configurato");
if (dn == 0) {
panelbody.replace("{dev_li_list}", "");
panelbody.replace("{dev_pane_list}","");
alert.replace("{class}", "danger no-device-alert");
panelbody += alert;
devpane.replace("{panel_body}", panelbody);
return devpane;
}
String li = "", pane = "", wrk;
for (int i = 0; i < dn; i++) {
wrk = FPSTR(HTML_DEV_LI_TPL);
wrk.replace("{dev_name}", list[i]);
li += wrk;
wrk = FPSTR(HTML_DEV_PANE_TPL);
wrk.replace("{dev_name}", list[i]);
pane += wrk;
}
delete [] list;
panelbody.replace("{dev_li_list}", li);
panelbody.replace("{dev_pane_list}", pane);
alert.replace("{class}", "danger no-device-alert hidden");
panelbody += alert;
devpane.replace("{panel_body}", panelbody);
return devpane;
}
String Portal::prepareDeviceForm() {
String form = FPSTR(HTML_FORM_EDIT_DEVICE);
int qt = DeviceHandler::getDeviceTypesNum();
String tpl, options = "";
for( int i=0; i < qt; i++){
tpl = FPSTR(HTML_OPTION_TPL);
tpl.replace("{value}", DeviceHandler::getDeviceTypes()[i]);
tpl.replace("{name}", DeviceHandler::getDeviceTypesDescription()[i]);
options += tpl;
}
form.replace("{device_types}", options);
return form;
}
String Portal::prepareModal(String const &id, String const &title, String const &body, String const &ok_callback) {
String modal = FPSTR(HTML_MODAL_TPL);
modal.replace("{id}", id);
modal.replace("{title}", title);
modal.replace("{body}", body);
modal.replace("{ok-callback}", ok_callback);
return modal;
}
String Portal::getDeviceKeyAttrs(Device &d) {
int num = d.getKeysPropertyNum();
Key * key = d.getKeys();
if (!key)
return "";
String pairs = " ";
while (key) {
pairs += Portal::keyAttrToJson(num, key);
pairs += ",";
key = key->getNext();
}
pairs.setCharAt(pairs.length() - 1, ' ');
return pairs;
}
String Portal::getDeviceData(Device &d) {
String json = "\"name\":\"" + d.getName() + "\",";
json += "\"type\":\"" + d.getType() + "\",";
json += "\"keys\":[" + getDeviceKeyAttrs(d) + "]";
return json;
}
String Portal::getMainMenu() {
String tpl = FPSTR(HTML_ROOT_TPL);
String menu = FPSTR(HTML_WIFI_MENU);
if (!ap_mode) {
menu += FPSTR(HTML_DEVICE_MENU);
}
tpl.replace("{menu}", menu);
return tpl;
}
String Portal::keyAttrToJson(int num, Key * key) {
String jattrs = "{";
for (int i = 0; i < num; i++) {
jattrs += String("\"") + key->getPropertyNameById(i) + String("\":");
jattrs += String("\"") + key->getPropertyById(i) + String("\",");
}
jattrs.remove(jattrs.length() - 1);
jattrs += "}";
return jattrs;
}