-
Notifications
You must be signed in to change notification settings - Fork 1
/
DONOFF.ino
1232 lines (1065 loc) · 44.3 KB
/
DONOFF.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
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
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
***************************************************************************
** Program : DONOFF
*/
#define _FW_VERSION "v0.4.1 (23-03-2020)"
/*
** Copyright (c) 2019 - 2020 Willem Aandewiel
**
** TERMS OF USE: MIT License. See bottom of file.
***************************************************************************
** DONOFF: Generic ESP8266 Flash Size 1M (128KB SPIFFS)
** BuiltIn LED GPIO1
** PWM-out GPIO3
**
** DONOFF: Generic ESP8266 Flash Size 4M (1MB or 2MB SPIFFS)
** BuiltIn LED GPIO1
** PWM-out GPIO3
**
** SONOFF: Generic ESP8266 Flash Size 1M (128KB SPIFFS)
** BuiltIn LED 13
** Switch pin 12
**
** NODEMCU: NodeMCU 1.0 Flash Size 4M (1MB or 2MB SPIFFS)
** BuiltIn LED 16
** PWM-out every free pin available
**
** Arduino-IDE settings for ESP01 (black):
**
** - Board: "Generic ESP8266 Module"
** - Flash mode: "DOUT"
** - Flash size: "1M (128K SPIFFS)"
** - Debug port: "Disabled"
** - Debug Level: "None"
** - IwIP Variant: "v2 Lower Memory"
** - Reset Method: "nodemcu" // but will depend on the programmer!
** - Crystal Frequency: "26 MHz"
** - VTables: "Flash"
** - Flash Frequency: "40MHz"
** - CPU Frequency: "80 MHz"
** - Buildin Led: "1" // "1" for ESP-01, 13 for SONOFF
** - Upload Speed: "115200"
** - Erase Flash: "Only Sketch"
** - Port: "ESP01-DSMR at <-- IP address -->"
**
** Compiled and tested with Arduino IDE 1.8.10
** and ESP8266 core 2.6.3
*/
#include "networkStuff.h"
// part of ESP8266 Core https://github.com/esp8266/Arduino
#include <ESP8266HTTPClient.h>
// https://github.com/PaulStoffregen/Time
#include <TimeLib.h>
#define _CONFIG_FILE "/donoff.cfg"
#define _LED_ON LOW
#define _LED_OFF HIGH
#define _MAX_DEVICES 15
#define _HEARTBEAT_INTERVAL (10 * 60) /* 10 minutes -> _HEARTBEAT is in seconds */
#define _MASTERDONOFF "DONOFF"
typedef struct {
String deviceHostName;
String IPaddress;
String Label;
char Type;
int8_t minState;
int8_t maxState;
int8_t State;
int8_t OnOff;
time_t lastSeen;
} device_type;
device_type deviceArray[_MAX_DEVICES];
// Create an instance of the server
// specify the port to listen on as an argument
ESP8266WebServer server(80);
WiFiClient wifiClient;
// A UDP instance to let us send and receive packets over UDP
WiFiUDP Udp;
const char *flashMode[] { "QIO", "QOUT", "DIO", "DOUT", "UnKnown" };
bool deviceIsMaster = false;
//String deviceHostName = "DONOFF"; // defined in networkStuff.h
String deviceIPaddress = "unknown";
String deviceLabel = "?";
char deviceType = 'D';
int8_t deviceDefaultState = 10;
int8_t deviceMinState = 10;
int8_t deviceMaxState = 90;
bool deviceFirstStart = true;
String masterHostName = _MASTERDONOFF;
String masterIPaddress = "0.0.0.0";
int localSwitchGPIO = -1; // -1 = no Switch
bool localSwitchToggle = false;
int localDeviceGPIO = LED_BUILTIN;
int localBuiltInLed = -1; // disable by default
bool localDeviceInverted = false;
int8_t webSocketDevNr = 0;
uint32_t webSocketHeartbeat = 0;
uint16_t localPWMfreq = 250; // Hz
//int device;
int value;
char cMsg[100], cMsg2[100], responseURL[100], APname[50], MAChex[13]; //n1n2n3n4n5n6\0
char inChar; // TelnetStream input
int noOfDevices = 0;
bool statusChanged = true, doUpdateDOM = false;
bool doShowHeap = false;
bool mustReboot = false;
bool animateDimUpDown = false;
uint32_t updateDac, aliveTime, heapInterval;
uint32_t freeHeap, maxHeap=0, minHeap=99999;
IPAddress ipDNS, ipGateWay, ipSubnet;
// NTP Servers:
static const char ntpServerName[] = "nl.pool.ntp.org";
//static const char ntpServerName[] = "time.nist.gov";
//static const char ntpServerName[] = "time-a.timefreq.bldrdoc.gov";
//static const char ntpServerName[] = "time-b.timefreq.bldrdoc.gov";
//static const char ntpServerName[] = "time-c.timefreq.bldrdoc.gov";
const int timeZone = 2; // Central European Time
//const int timeZone = -5; // Eastern Standard Time (USA)
//const int timeZone = -4; // Eastern Daylight Time (USA)
//const int timeZone = -8; // Pacific Standard Time (USA)
//const int timeZone = -7; // Pacific Daylight Time (USA)
unsigned int localPort = 8888; // local port to listen for UDP packets
//===========================================================================================
String macToStr(const uint8_t* mac) {
//===========================================================================================
String result;
for (int i = 0; i < 6; ++i) {
result += String(mac[i], 16);
if (i < 5)
result += ':';
}
return result;
} // macToStr()
//===========================================================================================
int setLocalDevice() {
//===========================================================================================
uint8_t State;
char tmpType;
tmpType = deviceArray[0].Type;
if (deviceArray[0].OnOff == 0) { // switched Off!
State = 0;
tmpType = 'S';
} else {
State = deviceArray[0].State;
}
if (tmpType == 'D') { // it's a dimmer
_dThis = true;
Debugf("New State local Dimmer! GPIO[%d] => State is now [%d], OnOff is now [%d]\n"
, localDeviceGPIO
, deviceArray[0].State
, deviceArray[0].OnOff);
if (localDeviceInverted) {
_dThis = true;
Debugf("analogWrite(%d, %d)\n", localDeviceGPIO, (100 - State));
analogWrite(localDeviceGPIO, (100 - State)); // dimmer
} else {
_dThis = true;
Debugf("analogWrite(%d, %d)\n", localDeviceGPIO, State);
analogWrite(localDeviceGPIO, State); // dimmer
}
} else { // it's a switch
_dThis = true;
Debugf("New State local Switch! GPIO[%d] => State is now [%d], OnOff is now [%d]\n"
, localDeviceGPIO
, deviceArray[0].State
, deviceArray[0].OnOff);
if (localDeviceInverted) {
digitalWrite(localDeviceGPIO, !State); // switch
} else {
digitalWrite(localDeviceGPIO, State); // switch
}
}
} // setLocalDevice()
//===========================================================================================
int isNewSlave(String IPaddress, char Type) {
//===========================================================================================
for (int i=1; i <= noOfDevices; i++) {
if (deviceArray[i].IPaddress == IPaddress) return i;
}
return -1;
} // isNewSlave()
//===========================================================================================
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t lenght) {
//===========================================================================================
String text = String((char *) &payload[0]);
char * textC = (char *) &payload[0];
String pOut[5], pDev[5], pVal[5], jsonString;
int8_t deviceNr;
switch(type) {
case WStype_DISCONNECTED:
_dThis = true;
Debugf("[%u] Disconnected!\n", num);
isConnected = false;
break;
case WStype_CONNECTED:
{
IPAddress ip = webSocket.remoteIP(num);
if (!isConnected) {
_dThis = true;
Debugf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);
isConnected = true;
webSocket.broadcastTXT("{\"msgType\":\"ConnectState\",\"Value\":\"Connected\"}");
sendDevInfo();
}
}
break;
case WStype_TEXT:
_dThis = true;
Debugf("[%u] Got message: [%s]\n", num, payload);
webSocketHeartbeat = millis() + 20000;
// send data to all connected clients
// webSocket.broadcastTXT("message here");
if (text.indexOf("getDevInfo") > -1) {
jsonString = "{";
jsonString += "\"msgType\": \"devInfo\"";
if (deviceIsMaster) {
jsonString += ", \"devName\": \"" + deviceHostName + " \"";
jsonString += ", \"devIPaddress\": \"" + WiFi.localIP().toString() + " \"";
jsonString += ", \"devVersion\": \" [Master " + String(_FW_VERSION) + "]\"";
} else {
jsonString += ", \"devName\": \"" + deviceHostName + " \"";
jsonString += ", \"devIPaddress\": \"" + WiFi.localIP().toString() + " \"";
jsonString += ", \"devVersion\": \" [Slave " + String(_FW_VERSION) + "]\"";
}
jsonString += "}";
_dThis = true;
Debugln(jsonString);
webSocket.broadcastTXT(jsonString);
}
if (text.indexOf("updateDOM") > -1) {
_dThis = true;
Debugln("now updateDOM()!");
updateDOM();
}
if (text.indexOf("DOMloaded") > -1) {
_dThis = true;
Debugln("set doUpdateDOM = false;");
doUpdateDOM = false;
}
if (text.indexOf("dimmer") > -1 || text.indexOf("switch") > -1) {
splitString(text, ',', pOut, 3);
_dThis = true;
Debugf("Found pOut[0] [%s]\n", pOut[0].c_str());
splitString(pOut[0], '=', pDev, 3);
_dThis = true;
Debugf("%s [%s]\n", pDev[0].c_str(), pDev[1].c_str());
deviceNr = pDev[1].toInt();
webSocketDevNr = pDev[1].toInt();
splitString(pOut[1], '=', pVal, 3);
_dThis = true;
Debugf("%s [%s]\n", pVal[0].c_str(), pVal[1].c_str());
if (pVal[0] == "OnOff") {
deviceArray[deviceNr].OnOff = pVal[1].toInt();
if (text.indexOf("switch") > -1) deviceArray[deviceNr].State = pVal[1].toInt();
_dThis = true;
Debugf("deviceArray[%d].OnOff => [%d]\n", deviceNr, deviceArray[deviceNr].OnOff);
}
else if (pVal[0] == "sliderVal") {
deviceArray[deviceNr].State = pVal[1].toInt();
_dThis = true;
Debugf("deviceArray[%d].State => [%d]\n", deviceNr, deviceArray[deviceNr].State);
deviceArray[deviceNr].OnOff = 1;
_dThis = true;
Debugf("deviceArray[%d].OnOff => [%d]\n", deviceNr, deviceArray[deviceNr].OnOff);
}
if (deviceNr == 0) { // local device
deviceArray[deviceNr].lastSeen = now();
setLocalDevice();
animateDimUpDown = false;
}
handleWebSocketState(deviceNr, payload, lenght);
}
break;
} // switch(type)
} // webSocketEvent()
//===========================================================================================
void handleWebSocketState(int16_t deviceNr, uint8_t * webSocketData, size_t lenght) {
//===========================================================================================
String message = "", response;
_dThis = true;
Debugf("[%s] \n", webSocketData);
statusChanged = true;
_dThis = true;
Debugf("webSocketDevNr [%d] - [%s] / [%c] => State[%d] / OnOff[%d]\n", deviceNr
, deviceArray[deviceNr].IPaddress.c_str()
, deviceArray[deviceNr].Type
, deviceArray[deviceNr].State
, deviceArray[deviceNr].OnOff);
if (deviceNr == 0) { // local device
deviceArray[0].lastSeen = now();
setLocalDevice();
}
handleStatus();
if (deviceArray[deviceNr].Type == 'D') response = "dimmer";
else response = "switch";
response += "," + String(deviceNr);
response += "," + String(deviceArray[deviceNr].Type);
response += "," + String(deviceArray[deviceNr].State);
response += "," + String(deviceArray[deviceNr].OnOff);
webSocket.broadcastTXT(response); // tell all other browser-clients
if (deviceIsMaster)
sendHTTPrequest(deviceArray[deviceNr].IPaddress.c_str(), deviceNr);
else sendHTTPrequest(masterIPaddress.c_str(), deviceNr);
} // handleWebSocketState()
//===========================================================================================
void handleSlaveState() {
//===========================================================================================
String message = "", response;
String IPaddress, sendIPaddress, Label, Type;
int16_t minState, maxState, State, OnOff, deviceNr;
bool hasIPaddress = false, hasType = false, hasLabel = false, hasState = false;
bool hasOnOff = false, hasMinS = false, hasMaxS = false;
_dThis = true;
Debug("");
message = "";
//Debugf(" %s.length(): [%d]\n", message.c_str(), message.length());
for (uint8_t i = 0; i < server.args(); i++) {
message += ", " + server.argName(i) + ":'" + server.arg(i) + "'";
}
Debugf("[%s] => [%d][%s]\n", server.uri().c_str(), server.args(), message.c_str());
DebugFlush();
statusChanged = true;
if (!deviceIsMaster) {
if (server.arg("IPaddress") != deviceIPaddress) {
_dThis = true;
Debugf("received status update Slave @%s .. but I'm not a Master! Bailout!", server.arg("IPaddress").c_str());
return;
}
}
if (server.hasArg("IPaddress")) {
IPaddress = server.arg("IPaddress");
Debugf("IPaddress [%s] ", IPaddress.c_str());
hasIPaddress = true;
}
if (server.hasArg("Label")) {
Label = server.arg("Label");
Debugf(", Label [%s] ", Label.c_str());
hasLabel = true;
}
if (server.hasArg("Type")) {
Type = server.arg("Type");
Debugf(", Type [%c]", Type[0]);
hasType = true;
}
if (server.hasArg("State")) {
State = server.arg("State").toInt();
Debugf(", State [%d]", State);
hasState = true;
}
if (server.hasArg("OnOff")) {
OnOff = server.arg("OnOff").toInt();
Debugf(", OnOff [%d]", OnOff);
hasOnOff = true;
}
if (server.hasArg("minState")) {
minState = server.arg("minState").toInt();
Debugf(", minState [%d]", minState);
hasMinS = true;
}
if (server.hasArg("maxState")) {
maxState = server.arg("maxState").toInt();
Debugf(", maxState [%d]", maxState);
hasMaxS = true;
}
Debugln();
DebugFlush();
if (!hasIPaddress || !hasType) {
message = "handleSlaveState(): no IPaddress or Type!\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += ", " + server.argName(i) + ":'" + server.arg(i) + "'";
}
message += server.args();
webSocket.broadcastTXT("{\"msgType\":\"slaveState\", \"Value\":\"Error: " + message + "\"}");
server.send(404, "text/plain", message);
_dThis = true;
Debugln(message);
return;
}
if (deviceIsMaster) {
deviceNr = isNewSlave(IPaddress, Type[0]);
_dThis = true;
Debugf("Found deviceNr [%d]\n", deviceNr);
sendIPaddress = IPaddress;
if (deviceNr < 0) { // it's a new device!
noOfDevices++;
deviceNr = noOfDevices;
deviceArray[deviceNr].IPaddress = IPaddress;
deviceArray[deviceNr].Label = Label;
deviceArray[deviceNr].Type = Type[0];
deviceArray[deviceNr].minState = minState;
deviceArray[deviceNr].maxState = maxState;
deviceArray[deviceNr].State = State;
deviceArray[deviceNr].OnOff = OnOff;
deviceArray[deviceNr].lastSeen = now();
_dThis = true;
Debugf("new deviceNr [%d] => [%s] [%s] [%c]\n", deviceNr
, deviceArray[deviceNr].IPaddress.c_str()
, deviceArray[deviceNr].Label.c_str()
, deviceArray[deviceNr].Type);
server.send(200, "text/html", server.uri() + server.args());
handleRoot();
} else { // update known device
if (hasState) { deviceArray[deviceNr].State = State; }
if (hasOnOff) { deviceArray[deviceNr].OnOff = OnOff; }
_dThis = true;
if (hasLabel && (Label != deviceArray[deviceNr].Label)) { deviceArray[deviceNr].Label = Label; doUpdateDOM = true; }
_dThis = true;
if (hasType && (Type[0] != deviceArray[deviceNr].Type)) { deviceArray[deviceNr].Type = Type[0]; doUpdateDOM = true; Debugln("new Type"); }
_dThis = true;
if (hasMinS && (minState != deviceArray[deviceNr].minState)) { deviceArray[deviceNr].minState = minState; doUpdateDOM = true; Debugln("new minState"); }
_dThis = true;
if (hasMaxS && (maxState != deviceArray[deviceNr].maxState)) { deviceArray[deviceNr].maxState = maxState; doUpdateDOM = true; Debugln("new maxState"); }
deviceArray[deviceNr].lastSeen = now();
_dThis = true;
Debugf("Update deviceNr [%d] => [%s] [%s] [%c] [%d] [%d]\n", deviceNr
, deviceArray[deviceNr].IPaddress.c_str()
, deviceArray[deviceNr].Label.c_str()
, deviceArray[deviceNr].Type
, deviceArray[deviceNr].minState
, deviceArray[deviceNr].maxState);
}
if (doUpdateDOM) {
updateDOM();
}
} else { // Slave, so it must be a local device
deviceNr = 0;
sendIPaddress = masterIPaddress;
if (hasLabel) { deviceArray[0].Label = Label; }
if (hasState) { deviceArray[0].State = State; }
if (hasOnOff) { deviceArray[0].OnOff = OnOff; }
if (deviceArray[0].Type == 'S')
deviceArray[0].State = deviceArray[0].OnOff;
deviceArray[0].lastSeen = now();
setLocalDevice();
}
handleStatus();
server.send(200, "text/html", server.uri() + server.args());
} // handleSlaveState()
//===========================================================================================
void updateDevices() {
//===========================================================================================
String updateDevice;
for(int D=0; D <= noOfDevices; D++) {
if (deviceArray[D].Type == 'D') updateDevice = "dimmer";
else updateDevice = "switch";
updateDevice += "," + String(D);
updateDevice += "," + String(deviceArray[D].Type);
updateDevice += "," + String(deviceArray[D].State);
updateDevice += "," + String(deviceArray[D].OnOff);
_dThis = true;
Debugf("[%s]\n", updateDevice.c_str());
webSocket.broadcastTXT(updateDevice); // tell all other browser-clients
}
} // updateDevices()
//===========================================================================================
void updateDOM() {
//===========================================================================================
String message, newDOM, updateDevice;
message = server.uri();
for (uint8_t i = 0; i < server.args(); i++) {
message += ", " + server.argName(i) + ":'" + server.arg(i) + "'";
}
_dThis = true;
Debugf("[%d] [%s]\n", noOfDevices, message.c_str());
newDOM = "";
for (int i=0; i<=noOfDevices; i++) {
if (deviceArray[i].Type == 'D') {
_dThis = true;
Debugf("Add Dimmer: device[%d] - [%s]: type[%c] (%d)\n", i
, deviceArray[i].Label.c_str()
, deviceArray[i].Type
, now() - deviceArray[i].lastSeen);
newDOM += dimmerHTML(i, deviceArray[i].IPaddress, deviceArray[i].Label
, deviceArray[i].minState
, deviceArray[i].maxState
, deviceArray[i].OnOff
, deviceArray[i].State);
}
}
for (int i=0; i<=noOfDevices; i++) {
if (deviceArray[i].Type == 'S') {
_dThis = true;
Debugf("Add Switch: device[%d] - [%s]: type[%c] (%d)\n", i
, deviceArray[i].Label.c_str()
, deviceArray[i].Type
, now() - deviceArray[i].lastSeen);
newDOM += switchHTML(i, deviceArray[i].IPaddress, deviceArray[i].Label, deviceArray[i].State);
}
}
doUpdateDOM = false;
//Debugln(newDOM);
webSocket.broadcastTXT("updateDOM:" + newDOM);
updateDevices();
//server.send(200, "text/html", newDOM);
} // updateDOM()
//===========================================================================================
String deviceToJson(int8_t deviceNr) {
//===========================================================================================
String jsonDev = "";
jsonDev += "\"Slave\":\"" + String(deviceNr) + "\""; // 0
jsonDev += ",\"IP\":\"" + String(deviceArray[deviceNr].IPaddress) + "\""; // 1
jsonDev += ",\"Label\":\"" + String(deviceArray[deviceNr].Label) + "\""; // 2
jsonDev += ",\"Type\":\"" + String(deviceArray[deviceNr].Type) + "\""; // 3
jsonDev += ",\"minState\":\"" + String(deviceArray[deviceNr].minState) + "\""; // 4
jsonDev += ",\"maxState\":\"" + String(deviceArray[deviceNr].maxState) + "\""; // 5
jsonDev += ",\"State\":\"" + String(deviceArray[deviceNr].State) + "\""; // 6
jsonDev += ",\"OnOff\":\"" + String(deviceArray[deviceNr].OnOff) + "\""; // 7
jsonDev += ",\"HB\":\"" + String(now() - deviceArray[deviceNr].lastSeen) + "\""; // 8
return jsonDev;
} // deviceToJson()
//===========================================================================================
void handleStatus() {
//===========================================================================================
String message, jsonString = "";
int16_t strIndex;
static uint16_t count = 0;
bool firstSlave;
message = "";
for (uint8_t i = 0; i < server.args(); i++) {
message += ", " + server.argName(i) + ":'" + server.arg(i) + "'";
}
_dThis = true;
Debugf("[%s] => [%d][%s]\n", server.uri().c_str(), server.args(), message.c_str());
if (!statusChanged) {
return;
}
firstSlave = true;
jsonString = "{";
jsonString += " \"msgType\": \"Status\"";
jsonString += ",\"Slaves\" : [";
for (int thisDevice = 0; thisDevice <= noOfDevices; thisDevice++) {
if (deviceArray[thisDevice].Type != 'S') continue;
if (firstSlave) {
jsonString += " {";
firstSlave = false;
} else {
jsonString += ",{";
}
jsonString += deviceToJson(thisDevice);
jsonString += "}";
}
for (int thisDevice = 0; thisDevice <= noOfDevices; thisDevice++) {
if (deviceArray[thisDevice].Type != 'D') continue;
if (firstSlave) {
jsonString += " {";
firstSlave = false;
} else {
jsonString += ",{";
}
jsonString += deviceToJson(thisDevice);
jsonString += "}";
}
jsonString += "]}";
_dThis = true;
Debugln("broadcastTXT(status of all devices)");
webSocket.broadcastTXT(jsonString);
} // handleStatus()
//===========================================================================================
void sendDevInfo() {
//===========================================================================================
String jsonString = "";
jsonString = "{";
jsonString += "\"msgType\": \"devInfo\"";
if (deviceIsMaster) {
jsonString += ", \"devName\": \"" + deviceHostName + " \"";
jsonString += ", \"devVersion\": \" [Master " + String(_FW_VERSION) + "]\"";
} else {
jsonString += ", \"devName\": \"" + deviceHostName + " \"";
jsonString += ", \"devVersion\": \" [Slave " + String(_FW_VERSION) + "]\"";
}
jsonString += "}";
_dThis = true;
Debugf("broadcastTXT(%s)\n", jsonString.c_str());
webSocket.broadcastTXT(jsonString);
} // sendDevInfo()
//===========================================================================================
void handleRoot() {
//===========================================================================================
if (deviceFirstStart) {
handleAdmin();
}
_dThis = true;
Debugln("Send index.html ..");
//server.send(200, "text/html", indexHTML);
doUpdateDOM = true;
} // handleRoot()
//===========================================================================================
void handleNotFound() {
//===========================================================================================
String message = "handleNotFound(): URL not valid!\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += ", " + server.argName(i) + ":'" + server.arg(i) + "'";
}
server.send(404, "text/plain", message);
_dThis = true;
Debugln(message);
} // handleNotFount()
//===========================================================================================
String listAllSlaves(bool doHtml) {
//===========================================================================================
String slavesInfo = "";
//(--)MDNS.begin(deviceHostName.c_str());
int n = MDNS.queryService("dooSlave", "tcp"); // Send out query for esp tcp services
if (!doHtml) {
_dThis = true;
Debugln("sending mDNS query for [DONOFF Slave] (http)");
}
if (n == 0) {
if (doHtml) {
slavesInfo = ",\"slaveInfo\": [";
slavesInfo += "{\"Slave\": \"No Slaves\"";
slavesInfo += ",\"IP\":\"Found\"}]";
} else {
_dThis = true;
Debugln("no Slaves found");
}
} else { // n > 0
_dThis = true;
if (!doHtml) {
Debug(n);
Debugln(" Slave(s) found:");
}
for (int i = 0; i < n; ++i) {
_dThis = true;
if (!doHtml) {
Debug((i + 1));
Debug(" ");
Debug(MDNS.hostname(i));
Debug("\tIPaddress: ");
Debugln(MDNS.IP(i).toString());
} else {
if (i == 0) slavesInfo = ",\"slaveInfo\": [";
else slavesInfo += ",";
slavesInfo += "{\"Slave\":\"" + MDNS.hostname(i) + ".local\"";
slavesInfo += ",\"IP\":\"" + MDNS.IP(i).toString() + "\"}";
}
}
slavesInfo += "]";
}
return slavesInfo;
} // listAllSlaves()
//===========================================================================================
String getServerIP(uint8_t maxTries) {
//===========================================================================================
String first3NumServer, first3NumSlave;
int n, tryCount = 0;
_dThis = true;
Debugln("sending mDNS query for [DONOFF.local] (http)");
MDNS.update();
first3NumServer = masterIPaddress.substring(0, masterIPaddress.lastIndexOf(".") - 1);
first3NumSlave = deviceIPaddress.substring(0, deviceIPaddress.lastIndexOf(".") - 1);
while (tryCount < maxTries) {
tryCount++;
n = MDNS.queryService("dooMaster", "tcp"); // Send out query for esp tcp services
_dThis = true;
Debugf("[%d] mDNS query done", tryCount);
if (n == 0) {
Debugln(" no services found!");
} else {
Debug(" service(s) found ");
for (int i = 0; i < n; ++i) {
_dThis = true;
// Print details for each service found
Debug(i + 1);
Debug(": ");
Debug(MDNS.hostname(i));
Debug(" (");
Debug(MDNS.IP(i));
Debug(":");
Debug(MDNS.port(i));
Debugln(")");
return MDNS.IP(i).toString();
}
}
} // tryCount
//if (first3NumServer == first3NumSlave) return masterIPaddress;
//return String(masterHostName + ".local");
return "0.0.0.0";
} // getServerIP()
//===========================================================================================
void checkHeartBeat() {
//===========================================================================================
static uint32_t checkInterval = millis() + (_HEARTBEAT_INTERVAL * 1000);
int8_t d;
if (deviceIsMaster && millis() > checkInterval) {
checkInterval += (_HEARTBEAT_INTERVAL * 1000); // _HEARTBEAT is in seconds!
deviceArray[0].lastSeen = now(); // local Device
for(d=1; d <= noOfDevices; d++) {
_dThis = true;
Debugf("Now testing [%d] (%s) => now()[%ld] -/- lastSeen[%ld] == [%ld] > [%ld]?\n"
, d, deviceArray[d].Label.c_str()
, now(), deviceArray[d].lastSeen
,(now() - deviceArray[d].lastSeen)
, (2 * _HEARTBEAT_INTERVAL));
if ((now() - deviceArray[d].lastSeen) > (2 * _HEARTBEAT_INTERVAL)) {
doUpdateDOM = true;
for(int8_t r=d; r < noOfDevices; r++) {
_dThis = true;
Debugf("[%d] (%s) := [%d] (%s)\n", r, deviceArray[r].Label.c_str()
, (r+1), deviceArray[r+1].Label.c_str());
deviceArray[r] = deviceArray[r+1];
}
d--;
noOfDevices--;
}
}
_dThis = true;
Debugf("number of devices left [%d]\n", (noOfDevices + 1));
}
if (doUpdateDOM) updateDOM();
} // checkHeartBeat()
//===========================================================================================
void sendHTTPrequest(String serverIP, int8_t deviceInx) {
//===========================================================================================
HTTPClient httpClient;
statusChanged = false;
if (deviceIsMaster && deviceInx == 0) { // master's local device, no need to request
_dThis = true;
Debugln("==> master's local device, Skip!");
return;
}
if (serverIP == "0.0.0.0") { // not a valid IP address
masterIPaddress = getServerIP(1);
if (masterIPaddress == "0.0.0.0") { // still not valid, no use requesting
_dThis = true;
Debugln("==> no DONOFF master, Skip! ");
return;
}
writeConfig(); // save masterIP to config
serverIP = masterIPaddress; // use new found masterIP to request
}
sprintf(cMsg,"IPaddress=%s&Label=%s&Type=%c&minState=%d&maxState=%d&State=%d&OnOff=%d"
, deviceArray[deviceInx].IPaddress.c_str()
, deviceArray[deviceInx].Label.c_str()
, deviceArray[deviceInx].Type
, deviceArray[deviceInx].minState
, deviceArray[deviceInx].maxState
, deviceArray[deviceInx].State
, deviceArray[deviceInx].OnOff);
String URL = "http://" + serverIP + "/slaveState";
_dThis = true;
Debug(URL);
Debug("?");
Debugln(cMsg);
httpClient.begin(wifiClient, URL); // Specify request destination
httpClient.addHeader("Content-Type", "application/x-www-form-urlencoded"); //Specify content-type header
int16_t httpCode = httpClient.POST(cMsg); //Send the request
String cMsg = httpClient.getString(); //Get the response payload
_dThis = true;
Debugf("httpCode [%d]", httpCode); //Print HTTP return code
if (httpCode == 200) {
Debugln(" OK");
deviceArray[deviceInx].lastSeen = now();
} else {
Debugln(" Error!!!");
deviceArray[deviceInx].lastSeen -= 60;
if (!deviceIsMaster) {
masterIPaddress = getServerIP(2);
if (masterIPaddress != "0.0.0.0") { // found a valid master-IP
_dThis = true;
Debugln("==> DONOFF master found! Save config .. ");
writeConfig(); // save masterIP to config
}
}
}
httpClient.end(); //Close connection server.send(200, "text/plain", responseURL);
} // sendHTTPrequest()
//===========================================================================================
void setup() {
//===========================================================================================
Serial.begin(115200);
delay(10);
_dThis = true;
Debugln("\nStart DONOFF system");
localDeviceGPIO = LED_BUILTIN;
localBuiltInLed = -1;
startWiFi();
Debugf("SSID:[%s], IP:[%s], Gateway:[%s]\r\n", WiFi.SSID().c_str()
, WiFi.localIP().toString().c_str()
, WiFi.gatewayIP().toString().c_str());
//================ SPIFFS =========================================
if (!SPIFFS.begin()) {
_dThis = true;
Debugln("SPIFFS Mount failed"); // Serious problem with SPIFFS
SPIFFSmounted = false;
} else {
_dThis = true;
Debugln("SPIFFS Mount succesfull");
SPIFFSmounted = true;
}
//=============end SPIFFS =========================================
readConfig();
Debugln("Done reading Config");
noOfDevices = 0;
deviceArray[0].deviceHostName = deviceHostName;
deviceArray[0].IPaddress = deviceIPaddress;
deviceArray[0].Label = deviceLabel;
deviceArray[0].Type = deviceType;
deviceArray[0].minState = deviceMinState;
deviceArray[0].maxState = deviceMaxState;
deviceArray[0].State = deviceDefaultState;
deviceArray[0].OnOff = 0;
Debug("Done setup deviceArray[0] with hostname[");
Debug(deviceHostName); Debugln("]");
//writeConfig();
if (localSwitchGPIO >= 0) {
pinMode(localSwitchGPIO, INPUT);
}
pinMode(localDeviceGPIO, OUTPUT);
if (localBuiltInLed >= 0) {
pinMode(localBuiltInLed, OUTPUT);
for(int I=0; I<3; I++) {
digitalWrite(localBuiltInLed, !digitalRead(localBuiltInLed));
delay(2000);
}
digitalWrite(localBuiltInLed, _LED_OFF); // HIGH is OFF
}
snprintf(cMsg, sizeof(cMsg), "Last reset reason: [%s]", ESP.getResetReason().c_str());
_dThis = true;
Debugln(cMsg);
DebugFlush();
if (localBuiltInLed >= 0) {
digitalWrite(localBuiltInLed, _LED_ON);
}
/*
startWiFi();
Debugf("SSID:[%s], IP:[%s], Gateway:[%s]\r\n", WiFi.SSID().c_str()
, WiFi.localIP().toString().c_str()
, WiFi.gatewayIP().toString().c_str());
*/
if (localBuiltInLed >= 0) {
for (int L=0; L < 10; L++) {
digitalWrite(localBuiltInLed, !digitalRead(localBuiltInLed));
delay(200);
}
digitalWrite(localBuiltInLed, _LED_OFF);
}
startTelnet();
/*
* list all services with the cammand:
* dns-sd -B _dooSlave .
* dns-sd -B _dooMaster .
*/
_dThis = true;
Debugf("[1] mDNS setup as [%s.local]\r\n", deviceHostName.c_str());
if (MDNS.begin(deviceHostName.c_str())) { // Start the mDNS responder for thisDevice.local
_dThis = true;
Debugf("[2] mDNS responder started as [%s.local]\n", deviceHostName.c_str());