forked from earlephilhower/psychoplug
-
Notifications
You must be signed in to change notification settings - Fork 0
/
psychoplug.ino
765 lines (659 loc) · 26.8 KB
/
psychoplug.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
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
/*
PsychoPlug
ESP8266 based remote outlet with standalone timer and MQTT integration
Copyright (C) 2017 Earle F. Philhower, III
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPUpdateServer.h>
#include "psychoplug.h"
#include "settings.h"
#include "schedule.h"
#include "mqtt.h"
#include "ntp.h"
#include "button.h"
#include "log.h"
#include "power.h"
#include "password.h"
#include "relay.h"
#include "led.h"
#include "timezone.h"
#include "dns.h"
#include "web.h"
bool isSetup = false;
// Our setup IP
static IPAddress setupIP = {192, 168, 4, 1};
static IPAddress setupMask = {255, 255, 255, 0};
// All it does is redirect to https://<given url>
static WiFiServer redirector(80);
// OTA updates on the cheap...
static ESP8266WebServer *otaServer = NULL;
static ESP8266HTTPUpdateServer *otaUpdateServer = NULL;
// HTTPS interface
static const uint8_t rsakey[] ICACHE_RODATA_ATTR = {
#include "key.h"
};
static const uint8_t x509[] ICACHE_RODATA_ATTR = {
#include "x509.h"
};
// Create an instance of the server
// specify the port to listen on as an argument
static WiFiServerSecure https(443);
// Return a *static* char * to an IP formatted string, so DO NOT USE MORE THAN ONCE PER LINE
const char *FormatIP(const byte ip[4], char *buff, int buffLen)
{
snprintf_P(buff, buffLen, PSTR("%d.%d.%d.%d"), ip[0], ip[1], ip[2], ip[3]);
return buff;
}
const char *FormatBool(bool b)
{
return b ? "True" : "False";
}
void PrintSettings(WiFiClient *client)
{
char buff[16];
WebPrintf(client, "<br><h1>WiFi Network</h1>\n");
WebPrintf(client, "SSID: %s<br>\n", settings.ssid);
WebPrintf(client, "PSK: %s<br>\n", settings.psk);
WebPrintf(client, "Hostname: %s<br>\n", settings.hostname);
WebPrintf(client, "DHCP: %s<br>\n", FormatBool(settings.useDHCP));
if (!settings.useDHCP) {
WebPrintf(client, "IP: %s<br>\n", FormatIP(settings.ip, buff, sizeof(buff)));
WebPrintf(client, "Gateway: %s<br>\n", FormatIP(settings.gateway, buff, sizeof(buff)));
WebPrintf(client, "Netmask: %s<br>\n", FormatIP(settings.netmask, buff, sizeof(buff)));
WebPrintf(client, "DNS: %s<br>\n", FormatIP(settings.dns, buff, sizeof(buff)));
}
WebPrintf(client, "UDP Log Server: %s:9911 (nc -l -u 9911)<br>\n", FormatIP(settings.logsvr, buff, sizeof(buff)));
WebPrintf(client, "<br><h1>Timekeeping</h1>\n");
WebPrintf(client, "NTP: %s<br>\n", settings.ntp);
WebPrintf(client, "Timezone: %s<br>\n", settings.timezone);
WebPrintf(client, "12 hour time format: %s<br>\n", FormatBool(settings.use12hr));
WebPrintf(client, "DD/MM/YY date format: %s<br>\n", FormatBool(settings.usedmy));
WebPrintf(client, "<br><h1>Power Settings</h1>\n");
// WebPrintf(client, "System Voltage: %d<br>\n", settings.voltage);
WebPrintf(client, "On after power failure: %s<br>\n", FormatBool(settings.onAfterPFail));
WebPrintf(client, "<br><H1>MQTT</h1>\n");
WebPrintf(client, "Enabled: %s<br>\n", FormatBool(settings.mqttEnable));
WebPrintf(client, "Host: %s<br>\n", settings.mqttHost);
WebPrintf(client, "Port: %d<br>\n", settings.mqttPort);
WebPrintf(client, "Use SSL: %s<br>\n", FormatBool(settings.mqttSSL));
WebPrintf(client, "ClientID: %s<br>\n", settings.mqttClientID);
WebPrintf(client, "Topic: %s<br>\n", settings.mqttTopic);
WebPrintf(client, "User: %s<br>\n", settings.mqttUser);
WebPrintf(client, "Pass: %s<br>\n", settings.mqttPass);
WebPrintf(client, "<br><h1>Web UI</h1>\n");
WebPrintf(client, "Admin User: %s<br>\n", settings.uiUser);
WebPrintf(client, "Admin Pass: *HIDDEN*<br>\n");
}
void MakeSSID(char *ssid, int len)
{
byte mac[6];
WiFi.macAddress(mac);
snprintf_P(ssid, len, PSTR("PSYCHOPLUG-%02X%02X%02X"), mac[3], mac[4], mac[5]);
}
void StartSetupAP()
{
char ssid[32];
LogPrintf("Starting Setup AP Mode\n");
WiFi.mode(WIFI_AP);
isSetup = false;
MakeSSID(ssid, sizeof(ssid));
WiFi.softAPConfig(setupIP, setupIP, setupMask);
WiFi.softAP(ssid);
// StartDNS(&setupIP);
LogPrintf("Waiting for connection\n");
https.begin();
https.setNoDelay(true);
redirector.begin();
redirector.setNoDelay(true);
}
void StartSTA()
{
LogPrintf("Starting STA Mode\n");
WiFi.mode(WIFI_STA);
if (settings.hostname[0])
WiFi.hostname(settings.hostname);
if (!settings.useDHCP) {
WiFi.config(settings.ip, settings.gateway, settings.netmask, settings.dns);
} else {
//byte zero[] = {0,0,0,0};
//WiFi.config(zero, zero, zero, zero);
// Above lines cause DHCP failure on 2.4-rc2.
// TODO -ensure that w/o anything it will request a dynamic address
}
if (settings.psk[0]) WiFi.begin(settings.ssid, settings.psk);
else WiFi.begin(settings.ssid);
// Try forever
while (WiFi.status() != WL_CONNECTED) {
LogPrintf("Trying to connect to '%s' key '%s'\n", settings.ssid, settings.psk );
ManageLED(LED_CONNECTING);
ManageButton();
delay(100);
}
if (WiFi.status() != WL_CONNECTED) {
Reset(); // Punt, maybe we're in a weird way. Reboot and try it again
}
IPAddress ip = WiFi.localIP();
LogPrintf("IP:%d.%d.%d.%d\n", ip[0], ip[1], ip[2], ip[3]);
StartMQTT();
// Start standard interface
https.begin();
https.setNoDelay(true);
redirector.begin();
redirector.setNoDelay(true);
StartNTP();
StartLog();
SetTZ(settings.timezone);
char atime[64];
LogPrintf("Local time is now: %s\n", AscTime(now(), settings.use12hr, settings.usedmy, atime, sizeof(atime)));
}
// Setup web page
void SendSetupHTML(WiFiClient *client)
{
char buff[16];
LogPrintf("+SendSetupHTML\n");
WebHeaders(client, NULL);
WebPrintf(client, DOCTYPE);
WebPrintf(client, "<html><head><title>PsychoPlug Setup</title>" ENCODING "</head>\n");
WebPrintf(client, "<body><h1>PsychoPlug Setup</h1>\n");
WebPrintf(client, "<form action=\"config.html\" method=\"POST\">\n");
WebPrintf(client, "<br><h1>WiFi Network</h1>\n");
WebFormText(client, PSTR("SSID"), "ssid", settings.ssid, true);
int cnt = WiFi.scanNetworks();
if (cnt==0) {
WebPrintf(client, "Discovered networks: No WIFI networks detected.<br>\n");
} else {
WebPrintf(client, "Discovered networks: <select onchange=\"setval(this)\">");
WebPrintf(client, "<option></option>");
for (byte i=0; i<cnt; i++) {
WebPrintf(client, "<option>%s</option>", WiFi.SSID(i).c_str());
}
WebPrintf(client, "</select><br>\n");
WebPrintf(client, "<script language=\"javascript\">function setval(i) { document.getElementById(\"ssid\").value = i.options[i.selectedIndex].text;}</script>\n");
}
WebFormText(client, PSTR("Password"), "pass", settings.psk, true);
WebFormText(client, PSTR("Hostname"), "hn", settings.hostname, true);
const char *ary1[] = {"ip", "nm", "gw", "dns", ""};
WebFormCheckboxDisabler(client, PSTR("DHCP Networking"), "dh", false, settings.useDHCP, true, ary1 );
WebFormText(client, PSTR("IP"), "ip", FormatIP(settings.ip, buff, sizeof(buff)), !settings.useDHCP);
WebFormText(client, PSTR("Netmask"), "nm", FormatIP(settings.netmask, buff, sizeof(buff)), !settings.useDHCP);
WebFormText(client, PSTR("Gateway"), "gw", FormatIP(settings.gateway, buff, sizeof(buff)), !settings.useDHCP);
WebFormText(client, PSTR("DNS"), "dns", FormatIP(settings.dns, buff, sizeof(buff)), !settings.useDHCP);
WebFormText(client, PSTR("UDP Log Server"), "logsvr", FormatIP(settings.logsvr, buff, sizeof(buff)), true);
WebPrintf(client, "<br><h1>Timekeeping</h1>\n");
WebFormText(client, PSTR("NTP Server"), "ntp", settings.ntp, true);
WebTimezonePicker(client, settings.timezone);
WebFormCheckbox(client, PSTR("12hr Time Format"), "use12hr", settings.use12hr, true);
WebFormCheckbox(client, PSTR("DD/MM/YY Date Format"), "usedmy", settings.usedmy, true);
WebPrintf(client, "<br><h1>Power</h1>\n");
//WebFormText(client, PSTR("Mains Voltage"), "voltage", settings.voltage, true);
WebFormCheckbox(client, PSTR("Start powered up after power loss"), "pf", settings.onAfterPFail, true);
WebPrintf(client, "<br><H1>MQTT</h1>\n");
const char *ary2[] = { "mhost", "mport", "mssl", "muser", "mpass", "mtopic", "mclientid", "" };
WebFormCheckboxDisabler(client, PSTR("Enable MQTT"), "mEn", true, settings.mqttEnable, true, ary2 );
WebFormText(client, PSTR("Host"), "mhost", settings.mqttHost, settings.mqttEnable);
WebFormText(client, PSTR("Port"), "mport", settings.mqttPort, settings.mqttEnable);
WebFormCheckbox(client, PSTR("Use SSL"), "mssl", settings.mqttSSL, settings.mqttEnable);
WebFormText(client, PSTR("User"), "muser", settings.mqttUser, settings.mqttEnable);
WebFormText(client, PSTR("Pass"), "mpass", settings.mqttPass, settings.mqttEnable);
WebFormText(client, PSTR("ClientID"), "mclientid", settings.mqttClientID, settings.mqttEnable);
WebFormText(client, PSTR("Topic"), "mtopic", settings.mqttTopic, settings.mqttEnable);
WebPrintf(client, "<br><h1>Web UI</h1>\n");
WebFormText(client, PSTR("Admin User"), "uiuser", settings.uiUser, true);
WebFormText(client, PSTR("Admin Password"), "uipass", "*****", true);
WebPrintf(client, "<input type=\"submit\" value=\"Submit\">\n");
WebPrintf(client, "</form></body></html>\n");
LogPrintf("-SendSetupHTML\n");
}
// Status Web Page
void SendStatusHTML(WiFiClient *client)
{
bool curPower = GetRelay();
char tmp[64];
WebHeaders(client, NULL);
WebPrintf(client, DOCTYPE);
WebPrintf(client, "<html><head><title>%s Status</title>" ENCODING "</head>\n", settings.hostname);
WebPrintf(client, "<body>\n");
WebPrintf(client, "Hostname: %s<br>\n", settings.hostname);
MakeSSID(tmp, sizeof(tmp));
WebPrintf(client, "SSID: %s<br>\n", tmp);
WebPrintf(client, "Current Time: %s<br>\n", AscTime(now(), settings.use12hr, settings.usedmy, tmp, sizeof(tmp)));
unsigned long ms = millis();
unsigned long days = ms / (24L * 60L * 60L * 1000L);
ms -= days * (24L * 60L * 60L * 1000L);
unsigned long hours = ms / (60L * 60L * 1000L);
ms -= hours * (60L * 60L * 1000L);
unsigned long mins = ms / (60L * 1000L);
ms -= mins * (60L * 1000L);
unsigned long secs = ms / (1000L);
WebPrintf(client, "Uptime: %d days, %d hours, %d minutes, %d seconds<br>\n", days, hours, mins, secs);
WebPrintf(client, "Power: %s <a href=\"%s\">Toggle</a><br><br>\n",curPower?"ON":"OFF", curPower?"off.html":"on.html");
// WebPrintf(client, "Current: %dmA (%dW @ %dV)<br>\n", GetCurrentMA(), (GetCurrentMA()* settings.voltage) / 1000, settings.voltage);
WebPrintf(client, "<table border=\"1px\">\n");
WebPrintf(client, "<tr><th>#</th><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th><th>Time</th><th>Action</th><th>EDIT</th></tr>\n");
char *buff = (char *)alloca(500); // By construction this will fit a row of the table
for (byte i=0; i<MAXEVENTS; i++) {
int len = 0;
sprintf_P(buff+len, PSTR("<tr><td>%d.</td>"), i+1);
len += strlen(buff+len);
for (byte j=0; j<7; j++) {
sprintf_P(buff+len, PSTR("<td>%s</td>"), (settings.event[i].dayMask & (1<<j))?"[X]":"[ ]");
len += strlen(buff+len);
}
if (settings.use12hr) {
int prthr = settings.event[i].hour%12;
if (!prthr) prthr = 12;
sprintf_P(buff+len, PSTR("<td>%d:%02d %s</td>"), prthr, settings.event[i].minute, (settings.event[i].hour<12)?"AM":"PM");
len += strlen(buff+len);
} else {
sprintf_P(buff+len, PSTR("<td>%d:%02d</td>"), settings.event[i].hour, settings.event[i].minute);
len += strlen(buff+len);
}
char str[16];
sprintf_P(buff+len, PSTR("<td>%s</td>"), GetActionString(settings.event[i].action, str, sizeof(str)));
len += strlen(buff+len);
sprintf_P(buff+len, PSTR("<td><a href=\"edit.html?id=%d\">Edit</a></td></tr>\r\n"), i);
client->print(buff);
}
WebPrintf(client, "</table><br>\n");
WebPrintf(client, "<a href=\"reconfig.html\">Change System Configuration</a><br><br>\n");
WebPrintf(client, "CGI Action URLs: <a href=\"on.html\">On</a> <a href=\"off.html\">Off</a> <a href=\"toggle.html\">Toggle</a> <a href=\"pulseoff.html\">Pulse Off</a> ");
WebPrintf(client, "<a href=\"pulseon.html\">Pulse On</a> <a href=\"status.html\">Status</a> <a href=\"hang.html\">Reset</a><br>\n");
WebPrintf(client, "<br>\n<a href=\"enableupdate.html\">Enable HTTP update of firmware for 10 minutes</a>\n");
WebPrintf(client, "</body>\n");
}
// Edit Rule
void SendEditHTML(WiFiClient *client, int id)
{
WebHeaders(client, NULL);
WebPrintf(client, DOCTYPE);
WebPrintf(client, "<html><head><title>PsychoPlug Rule Edit</title>" ENCODING "</head>\n");
WebPrintf(client, "<body>\n");
WebPrintf(client, "<h1>Editing rule %d</h1>\n", id+1);
WebPrintf(client, "<form action=\"update.html\" method=\"POST\">\n");
WebPrintf(client, "<input type=\"hidden\" name=\"id\" value=\"%d\">\n", id);
WebPrintf(client, "<table border=\"1px\">\n");
WebPrintf(client, "<tr><th>#</th><th>All</th><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th><th>Time</th><th>Action</th></tr>\n");
WebPrintf(client, "<tr><td>%d.</td>\n", id+1);
WebPrintf(client, "<td><button type=\"button\" onclick=\"x=document.getElementById('a').checked?false:true; ");
for (byte j=0; j<7; j++) {
WebPrintf(client, "document.getElementById('%c').checked = x; ", 'a'+j);
}
WebPrintf(client, "\">All</button></td>\n");
for (byte j=0; j<7; j++) {
WebPrintf(client, "<td><input type=\"checkbox\" id=\"%c\" name=\"%c\" %s></td>\n", 'a'+j, 'a'+j, settings.event[id].dayMask & (1<<j)?"checked":"");
}
WebPrintf(client, "<td><select name=\"hr\">");
if (settings.use12hr) {
int selhr = settings.event[id].hour%12;
if (!selhr) selhr = 12;
for (int j=1; j<=12; j++) {
WebPrintf(client, "<option %s>%d</option>", selhr==j?"selected":"", j)
}
} else {
for (int j=0; j<24; j++) {
WebPrintf(client, "<option %s>%d</option>", settings.event[id].hour==j?"selected":"", j)
}
}
WebPrintf(client, "</select>:<select name=\"mn\">");
char *buff = (char *)alloca(20*60+10);
int len=0;
for (int j=0; j<60; j++) {
sprintf_P(buff+len, PSTR("<option %s>%02d</option>"), (settings.event[id].minute==j)?"selected":"", j);
len += strlen(buff+len);
}
client->print(buff);
WebPrintf(client, "</select> ");
if (settings.use12hr)
WebPrintf(client, "<select name=\"ampm\"><option %s>AM</option><option %s>PM</option></select></td>", settings.event[id].hour<12?"selected":"", settings.event[id].hour>=12?"selected":"");
WebPrintf(client, "<td>\n<select name=\"action\">");
char str[16];
for (int j=0; j<=ACTION_MAX; j++) WebPrintf(client, "<option %s>%s</option>", settings.event[id].action==j?"selected":"", GetActionString(j, str, sizeof(str)));
WebPrintf(client, "</select></td></table><br>\n");
WebPrintf(client, "<input type=\"submit\" value=\"Submit\">\n");
WebPrintf(client, "</form></body></html>\n");
}
// Success page, auto-refresh in 1 sec to index
void SendSuccessHTML(WiFiClient *client)
{
WebHeaders(client, PSTR("Refresh: 1; url=index.html\r\n"));
WebPrintf(client, DOCTYPE);
WebPrintf(client, "<html><head><title>Success</title>" ENCODING "</head><body><h1><a href=\"index.html\">Success. Click here if not auto-refreshed</a></h1></body></html>\n");
}
void setup()
{
Serial.begin(115200);
Serial.flush();
delay(100);
LogPrintf("Starting up...\n");
delay(10);
LogPrintf("Settings size=%d\n", sizeof(settings));
StartButton();
StartLED();
StartPowerMonitor();
LogPrintf("Loading Settings\n");
bool ok = LoadSettings(RawButton());
StartRelay(settings.onAfterPFail?true:false);
// Load our certificate and key from FLASH before we start
https.setServerKeyAndCert_P(rsakey, sizeof(rsakey), x509, sizeof(x509));
// Make sure ESP isn't doing any wifi operations. Sometimes starts back up in AP mode, for example
WiFi.disconnect();
WiFi.softAPdisconnect(true);
if (ok) {
isSetup = true;
StartSTA();
} else {
isSetup = false;
StartSetupAP();
}
LogPrintf("End setup()\n");
}
void ParseSetupForm(char *params)
{
char *valPtr;
char *namePtr;
// Checkboxes don't actually return values if they're unchecked, so by default these get false
settings.useDHCP = false;
settings.onAfterPFail = false;
settings.mqttEnable = false;
settings.mqttSSL = false;
settings.use12hr = false;
settings.usedmy = false;
while (ParseParam(¶ms, &namePtr, &valPtr)) {
ParamText("ssid", settings.ssid);
ParamText("pass", settings.psk);
ParamText("hn", settings.hostname);
ParamCheckbox("dh", settings.useDHCP);
Param4Int("ip", settings.ip);
Param4Int("nm", settings.netmask);
Param4Int("gw", settings.gateway);
Param4Int("dns", settings.dns);
Param4Int("logsvr", settings.logsvr);
ParamText("ntp", settings.ntp);
ParamText("tz", settings.timezone);
ParamCheckbox("use12hr", settings.use12hr);
ParamCheckbox("usedmy", settings.usedmy);
ParamCheckbox("pf", settings.onAfterPFail);
ParamCheckbox("mEn", settings.mqttEnable);
ParamText("mhost", settings.mqttHost);
ParamInt("mport", settings.mqttPort);
// int v;
// ParamInt("voltage", v);
// if ((v<80) || (v>255)) v=120; // Sanity-check
// settings.voltage = v;
ParamCheckbox("mssl", settings.mqttSSL);
ParamText("mtopic", settings.mqttTopic);
ParamText("mclientid", settings.mqttClientID);
ParamText("muser", settings.mqttUser);
ParamText("mpass", settings.mqttPass);
ParamText("uiuser", settings.uiUser);
char tempPass[64];
ParamText("uipass", tempPass);
if (strcmp_P(tempPass, PSTR("*****"))) {
// Was changed, regenerate salt and store it
HashPassword(tempPass, settings.uiSalt, settings.uiPassEnc);
}
memset(tempPass, 0, sizeof(tempPass)); // I think I'm paranoid
}
}
void SendRebootHTML(WiFiClient *client)
{
WebHeaders(client, NULL);
WebPrintf(client, DOCTYPE);
WebPrintf(client, "<html><head><title>Setting Configuration</title>" ENCODING "</head><body>\n");
WebPrintf(client, "<h1>Setting Configuration</h1>");
WebPrintf(client, "<br>\n");
PrintSettings(client);
if (isSetup) WebPrintf(client, "<hr><h1><a href=\"index.html\">Click here to reconnect after 5 seconds.</a></h1>\n")
else WebPrintf(client, "<br><h1>PsychoPlug will now reboot and connect to given network</h1>");
WebPrintf(client, "</body>");
}
void SendResetHTML(WiFiClient *client)
{
WebHeaders(client, NULL);
WebPrintf(client, DOCTYPE);
WebPrintf(client, "<html><head><title>Resetting PsychoPlug</title>" ENCODING "</head><body>\n");
WebPrintf(client, "<h1>Resetting the plug, please manually reconnect in 5 seconds.</h1>");
WebPrintf(client, "</body>");
}
void SendGoToConfigureHTTPS(WiFiClient *client)
{
LogPrintf("+SendGoToConfigureHTTPS\n");
WebHeaders(client, NULL);
LogPrintf("SendGoToConfigureHTTPS: Sent headers\n");
WebPrintf(client, DOCTYPE);
WebPrintf(client, "<html><head><title>Configure PsychoPlug</title>" ENCODING "</head><body>\n");
WebPrintf(client, "<h1><a href=\"https://%d.%d.%d.%d/index.html\">Go to configuration</a></h1>", setupIP[0], setupIP[1], setupIP[2], setupIP[3]);
WebPrintf(client, "</body>");
}
void Reset()
{
SaveSettings();
StopSettings();
// Will hang if you just did serial upload. Needs powercycle once after upload to function properly.
ESP.restart();
// Should never hit here...
delay(1000000);
}
void HandleConfigSubmit(WiFiClient *client, char *params)
{
ParseSetupForm(params);
SaveSettings();
SendRebootHTML(client);
Reset(); // Restarting safer than trying to change wifi/mqtt/etc.
}
void HandleUpdateSubmit(WiFiClient *client, char *params)
{
char *namePtr;
char *valPtr;
// Any of these not defined in the submit, error
int id = -1;
int hr = -1;
int mn = -1;
int ampm = -1;
int action = -1;
byte mask = 0; // Day bitmap
while (ParseParam(¶ms, &namePtr, &valPtr)) {
ParamInt("id", id);
ParamInt("hr", hr);
ParamInt("mn", mn);
if (settings.use12hr) {
if (!strcmp_P(namePtr, PSTR("ampm"))) {
if (!strcmp_P(valPtr, PSTR("AM"))) ampm=0;
else ampm=1;
}
} else {
ampm = 0;
}
if (!strcmp_P(namePtr, PSTR("action"))) {
char str[16];
for (int i=0; i<=ACTION_MAX; i++)
if (!strcmp(valPtr, GetActionString(i, str, sizeof(str)))) action = i;
}
if (namePtr[0]>='a' && namePtr[0]<='g' && namePtr[1]==0) {
if (!strcmp_P(valPtr, PSTR("on"))) mask |= 1<<(namePtr[0]-'a');
}
}
bool err = false;
// Check settings are good
if (id < 0 || id >= MAXEVENTS) err = true;
if (settings.use12hr) {
if (hr < 0 || hr > 12) err = true;
} else {
if (hr < 0 || hr > 23) err = true;
}
if (mn < 0 || mn >= 60) err = true;
if (ampm < 0 || ampm > 1) err = true;
if (action < 0 || action > ACTION_MAX ) err = true;
if (hr==12 && ampm==0 && settings.use12hr) { hr = 0; }
if (err) {
WebError(client, 400, NULL);
} else {
// Update the entry, send refresh page to send back to index
settings.event[id].dayMask = mask;
settings.event[id].hour = hr + 12 * ampm; // !use12hr => ampm=0, so safe
settings.event[id].minute = mn;
settings.event[id].action = action;
SaveSettings(); // Store in flash
SendSuccessHTML(client);
}
}
void HandleEditHTML(WiFiClient *client, char *params)
{
int id = -1;
char *namePtr;
char *valPtr;
while (ParseParam(¶ms, &namePtr, &valPtr)) {
ParamInt("id", id);
}
if (id >=0 && id < MAXEVENTS) {
SendEditHTML(client, id);
} else {
WebError(client, 400, NULL);
}
}
void SendOTARedirect(WiFiClient *client)
{
LogPrintf("+SendOTARedirect\n");
IPAddress ip = WiFi.localIP();
WebHeaders(client, NULL);
WebPrintf(client, DOCTYPE);
WebPrintf(client, "<html><head><title>OTA Enabled</title>" ENCODING "</head><body>\n");
WebPrintf(client, "<h1><a href=\"http://%d.%d.%d.%d:8080/update\">Go to OTA page</a></h1>", ip[0], ip[1], ip[2], ip[3]);
WebPrintf(client, "</body>");
}
void loop()
{
static unsigned long lastMS = 0;
static unsigned long killUpdateTime = 0;
// Time to restart the plug if the update window is over
if (killUpdateTime && (millis() > killUpdateTime) ) {
LogPrintf("Restarting ESP due to update timeout\n");
ESP.restart();
} else if (otaServer) {
otaServer->handleClient();
}
if (lastMS>millis() || (millis()-lastMS)>5000) {
lastMS = millis();
LogPrintf("@%d: ESP Heap Free=%d\n", lastMS, ESP.getFreeHeap());
}
// Let the button toggle the relay always
ManageButton();
// Blink the LED appropriate to the state
ManageLED(isSetup ? LED_CONNECTED : LED_AWAITSETUP);
// Pump DNS queue
if (!isSetup) {
// ManageDNS();
}
char *url;
char *params;
// Any HTTP request, send it to https:// on our IP
WiFiClient redir = redirector.available();
if (redir) {
LogPrintf("HTTP Redirector available\n");
if (WebReadRequest(&redir, &url, ¶ms, false)) {
LogPrintf("HTTP Redirector request: %s\n", url);
char newLoc[64];
if (isSetup) {
IPAddress ip = WiFi.localIP();
snprintf_P(newLoc, sizeof(newLoc), PSTR("Location: https://%d.%d.%d.%d/%s"), ip[0], ip[1], ip[2], ip[3], url[0]?url:"index.html");
WebError(&redir, 301, newLoc, false);
} else {
if (!strcmp_P(url, PSTR("favicon.ico"))) {
WebError(&redir, 404, NULL);
// } else if (!strcmp_P(url, PSTR("generate_204"))) {
// LogPrintf("Sending 301 redirector to https://<>/configure.html\n");
// snprintf_P(newLoc, sizeof(newLoc), PSTR("Location: https://%d.%d.%d.%d/configure.html"), setupIP[0], setupIP[1], setupIP[2], setupIP[3]);
// WebError(&redir, 301, newLoc, false);
} else {
LogPrintf("Sending redirector web page listing config https link\n");
SendGoToConfigureHTTPS(&redir);
LogPrintf("Sent\n");
}
}
redir.flush();
redir.stop();
LogPrintf("redir.stop()\n");
}
} else if (!isSetup) {
WiFiClientSecure client = https.available();
if (client) {
LogPrintf("+HTTPS setup request\n");
if (WebReadRequest(&client, &url, ¶ms, false)) {
if (IsIndexHTML(url)) {
SendSetupHTML(&client);
} else if (!strcmp_P(url, PSTR("config.html")) && *params) {
HandleConfigSubmit(&client, params);
} else {
WebError(&client, 404, NULL);
}
}
client.flush();
client.stop();
LogPrintf("-HTTPS setup request\n");
}
} else {
if (!otaServer) ManageMQTT();
ManageSchedule();
ManagePowerMonitor();
WiFiClientSecure client = https.available();
if (client) {
StopMQTT(); //
if (WebReadRequest(&client, &url, ¶ms, true, settings.uiUser, settings.uiSalt, settings.uiPassEnc)) {
if (IsIndexHTML(url)) {
SendStatusHTML(&client);
} else if (!strcmp_P(url, PSTR("on.html"))) {
PerformAction(ACTION_ON);
SendSuccessHTML(&client);
} else if (!strcmp_P(url, PSTR("off.html"))) {
PerformAction(ACTION_OFF);
SendSuccessHTML(&client);
} else if (!strcmp_P(url, PSTR("toggle.html"))) {
PerformAction(ACTION_TOGGLE);
SendSuccessHTML(&client);
} else if (!strcmp_P(url, PSTR("pulseoff.html"))) {
PerformAction(ACTION_PULSEOFF);
SendSuccessHTML(&client);
} else if (!strcmp_P(url, PSTR("pulseon.html"))) {
PerformAction(ACTION_PULSEON);
SendSuccessHTML(&client);
} else if (!strcmp_P(url, PSTR("status.html"))) {
WebPrintf(&client, "%d", GetRelay()?1:0);
} else if (!strcmp_P(url, PSTR("hang.html"))) {
SendResetHTML(&client);
Reset(); // Restarting safer than trying to change wifi/mqtt/etc.
} else if (!strcmp_P(url, PSTR("edit.html")) && *params) {
HandleEditHTML(&client, params);
} else if (!strcmp_P(url, PSTR("update.html")) && *params) {
HandleUpdateSubmit(&client, params);
} else if (!strcmp_P(url, PSTR("reconfig.html"))) {
SendSetupHTML(&client);
} else if (!strcmp_P(url, PSTR("config.html")) && *params) {
HandleConfigSubmit(&client, params);
} else if (!strcmp_P(url, PSTR("enableupdate.html"))) {
StopMQTT();
otaUpdateServer = new ESP8266HTTPUpdateServer;
otaServer = new ESP8266WebServer(8080);
otaUpdateServer->setup(otaServer);
otaServer->begin();
killUpdateTime = millis() + 10*60*1000; // now + 10 mins
SendOTARedirect(&client);
} else {
WebError(&client, 404, NULL);
}
}
client.flush();
client.stop();
}
}
}