-
Notifications
You must be signed in to change notification settings - Fork 15
/
ESPimatic.ino
2835 lines (2520 loc) · 84.2 KB
/
ESPimatic.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
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>
#include <SPI.h>
#include "LedControlSPIESP8266.h"
#include <Base64.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <IRremoteESP8266.h>
#include "DHT.h"
#include <FS.h>
//holds the current upload
File UploadFile;
String fileName;
//-------------- FSBrowser application -----------
//format bytes
String formatBytes(size_t bytes) {
if (bytes < 1024) {
return String(bytes) + "B";
} else if (bytes < (1024 * 1024)) {
return String(bytes / 1024.0) + "KB";
} else if (bytes < (1024 * 1024 * 1024)) {
return String(bytes / 1024.0 / 1024.0) + "MB";
} else {
return String(bytes / 1024.0 / 1024.0 / 1024.0) + "GB";
}
}
DHT dht = DHT(0, DHT11);
IRsend irsend(5); //an IR led is connected to GPIO pin 0
int TelnetMenu = -1;
String sep = "____";
String ESPimaticVersion = "0.1.26";
String DS18B20Enabled = "0";
String DHTEnabled = "0";
String MatrixEnabled = "0";
String LastDS18B20 = "";
String LastDHTtemp = "";
String LastDHThum = "";
String ShowOnMatrix = "";
String WMode = "";
int FSTotal;
int FSUsed;
String MatrixIntensity;
String DeviceName;
String EnableWebAuth;
String BSlocal;
String ADCEnabled;
int ADC;
int userdone;
int passworddone;
String kwhintEnabled;
int curWatts = 0;
int totalWh = 0;
int kwhintc;
unsigned long pulseCountS = 0;
unsigned long prevPulseS = 0;
unsigned long pulseTimeS = 0;
// EEPROM Adress & Length
#define ssid_Address 0
#define password_Address 32
#define pimhost_Address 97
#define pimport_Address 129
#define pimuser_Address 134
#define pimpass_Address 145
#define enablematrix_Address 165
#define matrixpin_Address 166
#define enableds18b20_Address 168
#define ds18b20pin_Address 169
#define enabledht_Address 171
#define dhttype_Address 172
#define dhtpin_Address 173
#define enabledsleep_Address 175
#define ds18b20var_Address 176
#define ds18b20interval_Address 206
#define ds18b20resolution_Address 208
#define enableir_Address 210
#define irpin_Address 211
#define enablerelay_Address 213
#define relay1pin_Address 214
#define relay2pin_Address 216
#define relay3pin_Address 218
#define dhttempvar_Address 220
#define dhthumvar_Address 250
#define dhtinterval_Address 280
#define relay4pin_Address 282
#define eeprommd5_Address 284
#define version_Address 316
#define availablegpio_Address 324
#define showonmatrix_Address 341
#define matrixintensity_Address 342
#define relay1type_Address 344
#define relay2type_Address 345
#define relay3type_Address 346
#define relay4type_Address 347
#define devicename_Address 348
#define webuser_Address 378
#define webpass_Address 403
#define enablewebauth_Address 429
#define espimaticapikey_Address 430
#define bslocal_Address 445
#define enableadc_Address 446
#define adcinterval_Address 447
#define adcvar_Address 449
#define enableled_Address 479
#define led1pin_Address 480
#define led2pin_Address 482
#define led3pin_Address 484
#define led4pin_Address 486
#define dsleepaction_Address 488
#define kwhintenable_Address 490
#define kwhintpin_Address 491
#define kwhintinterval_Address 493
#define kwhintc_Address 495
#define kwhintvar_Address 500
#define dsleepinterval_Address 530
#define dsleepbackdoor_Address 532
int EepromAdress[] = {ssid_Address, password_Address, pimhost_Address, pimport_Address, pimuser_Address, pimpass_Address, enablematrix_Address, matrixpin_Address, enableds18b20_Address, ds18b20pin_Address, enabledht_Address, dhttype_Address, dhtpin_Address, enabledsleep_Address, ds18b20var_Address, ds18b20interval_Address, ds18b20resolution_Address, enableir_Address, irpin_Address, enablerelay_Address, relay1pin_Address, relay2pin_Address, relay3pin_Address, dhttempvar_Address, dhthumvar_Address, dhtinterval_Address, relay4pin_Address, eeprommd5_Address, version_Address, availablegpio_Address, showonmatrix_Address, matrixintensity_Address, relay1type_Address, relay2type_Address, relay3type_Address, relay4type_Address, devicename_Address, webuser_Address, webpass_Address, enablewebauth_Address, espimaticapikey_Address, bslocal_Address, enableadc_Address, adcinterval_Address, adcvar_Address, enableled_Address, led1pin_Address, led2pin_Address, led3pin_Address, dsleepaction_Address, kwhintenable_Address, kwhintpin_Address, kwhintinterval_Address, kwhintc_Address, kwhintvar_Address, dsleepinterval_Address, dsleepbackdoor_Address};
int EepromLength[] = {31, 65, 32, 5, 11, 20, 1, 2, 1, 2, 1, 1, 2, 1, 30, 2, 2, 1, 2, 1, 2, 2, 2, 30, 30, 2, 2, 32, 8, 17, 1, 2, 1, 1 ,1 ,1, 30, 25, 25, 1, 15, 1, 1, 2, 30, 1, 2, 2, 2, 2, 1, 2, 2, 5, 30, 2, 30};
int StartAddress = 0;
#define ErrorWifi 0
#define ErrorEeprom 1
#define ErrorDs18b20 2
#define ErrorUpgrade 3
#define ErrorDht 4
int ErrorList[] = {0, 0, 0, 0, 0};
// Timer stuff
//elapsedMillis timeElapsed; //declare global if you don't want it reset every time loop runs
#define BASE64_LEN 40
char unameenc[BASE64_LEN];
uint8_t ONE_WIRE_BUS;
OneWire oneWire = OneWire(ONE_WIRE_BUS); // Setup a oneWire instance
DallasTemperature sensors(&oneWire); // Pass our oneWire reference to Dallas Temperature
DeviceAddress insideThermometer;
uint8_t LEDpin;
//LedControl lc=LedControl(2,2); // Load pin, number of LED displays
LedControl lc = LedControl(LEDpin, 2); // Load pin, number of LED displays
/* we always wait a bit between updates of the display */
unsigned long delaytime = 100;
const char* APssid = "ESPimatic";
const char* APpassword = "espimatic";
long ds18b20_sendInterval = 60000; //in millis
long ds18b20_lastInterval = 0;
long dht_sendInterval = 60000; //in millis
long dht_lastInterval = 0;
long adc_sendInterval = 60000; //in millis
long adc_lastInterval = 0;
long kwhint_sendInterval = 60000; //in millis
long kwhint_lastInterval = 0;
#define MAX_SRV_CLIENTS 1
WiFiServer telnet(23);
WiFiClient serverClients[MAX_SRV_CLIENTS];
ESP8266WebServer server(80);
WiFiClient client;
const static byte alphabetBitmap[41][8] = {
{0x0, 0x0, 0x7E, 0x81, 0x81, 0x81, 0x7E, 0x0}, //0
{0x0, 0x0, 0x4, 0x82, 0xFF, 0x80, 0x0, 0x0}, //1
{0x0, 0x0, 0xE2, 0x91, 0x91, 0x91, 0x8E, 0x0}, //2
{0x0, 0x0, 0x42, 0x89, 0x89, 0x89, 0x76, 0x0}, //3
{0x0, 0x0, 0x1F, 0x10, 0x10, 0xFF, 0x10, 0x0}, //4
{0x0, 0x0, 0x8F, 0x89, 0x89, 0x89, 0x71, 0x0}, //5
{0x0, 0x0, 0x7E, 0x89, 0x89, 0x89, 0x71, 0x0}, //6
{0x0, 0x0, 0x1, 0x1, 0xF9, 0x5, 0x3, 0x0}, //7
{0x0, 0x0, 0x76, 0x89, 0x89, 0x89, 0x76, 0x0}, //8
{0x0, 0x0, 0x8E, 0x91, 0x91, 0x91, 0x7E, 0x0}, //9
{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, // blank space
{0x0, 0x0, 0x0, 0x0, 0x90, 0x0, 0x0, 0x0}, //:
{0x0, 0x0, 0x0, 0x10, 0x10, 0x10, 0x10, 0x0}, // -
{0x0, 0x0, 0x0, 0x0, 0x80, 0x0, 0x0, 0x0}, // .
{0x0, 0x0, 0xFC, 0x9, 0x11, 0x21, 0xFC, 0x0}, //Ñ
{0x0, 0x0, 0xFE, 0x11, 0x11, 0x11, 0xFE, 0x0}, //A
{0x0, 0x0, 0xFF, 0x89, 0x89, 0x89, 0x76, 0x0}, //B
{0x0, 0x0, 0x7E, 0x81, 0x81, 0x81, 0x42, 0x0}, //C
{0x0, 0x0, 0xFF, 0x81, 0x81, 0x81, 0x7E, 0x0}, //D
{0x0, 0x0, 0xFF, 0x89, 0x89, 0x89, 0x81, 0x0}, //E
{0x0, 0x0, 0xFF, 0x9, 0x9, 0x9, 0x1, 0x0}, //F
{0x0, 0x0, 0x7E, 0x81, 0x81, 0x91, 0x72, 0x0}, //G
{0x0, 0x0, 0xFF, 0x8, 0x8, 0x8, 0xFF, 0x0}, //H
{0x0, 0x0, 0x0, 0x81, 0xFF, 0x81, 0x0, 0x0}, //I
{0x0, 0x0, 0x60, 0x80, 0x80, 0x80, 0x7F, 0x0}, //J
{0x0, 0x0, 0xFF, 0x18, 0x24, 0x42, 0x81, 0x0}, //K
{0x0, 0x0, 0xFF, 0x80, 0x80, 0x80, 0x80, 0x0}, //L
{0x0, 0x0, 0xFF, 0x2, 0x4, 0x2, 0xFF, 0x0}, //M
{0x0, 0x0, 0xFF, 0x2, 0x4, 0x8, 0xFF, 0x0}, //N
{0x0, 0x0, 0x7E, 0x81, 0x81, 0x81, 0x7E, 0x0}, //O
{0x0, 0x0, 0xFF, 0x11, 0x11, 0x11, 0xE, 0x0}, //P
{0x0, 0x0, 0x7E, 0x81, 0x81, 0xA1, 0x7E, 0x80}, //Q
{0x0, 0x0, 0xFF, 0x11, 0x31, 0x51, 0x8E, 0x0}, //R
{0x0, 0x0, 0x46, 0x89, 0x89, 0x89, 0x72, 0x0}, //S
{0x0, 0x0, 0x1, 0x1, 0xFF, 0x1, 0x1, 0x0}, //T
{0x0, 0x0, 0x7F, 0x80, 0x80, 0x80, 0x7F, 0x0}, //U
{0x0, 0x0, 0x3F, 0x40, 0x80, 0x40, 0x3F, 0x0}, //V
{0x0, 0x0, 0x7F, 0x80, 0x60, 0x80, 0x7F, 0x0}, //W
{0x0, 0x0, 0xE3, 0x14, 0x8, 0x14, 0xE3, 0x0}, //X
{0x0, 0x0, 0x3, 0x4, 0xF8, 0x4, 0x3, 0x0}, //Y
{0x0, 0x0, 0xE1, 0x91, 0x89, 0x85, 0x83, 0x0} //Z
};
String HandleEeprom (int StartAddress, String action, String value = "")
{
int ArrPos;
int SizeOfArr = (sizeof(EepromAdress) / 4 ) - 1 ;
String Eeprom_Content;
for (int i = 0; i < (SizeOfArr + 1); i++)
{
if (EepromAdress[i] == StartAddress)
{
ArrPos = i;
break;
}
}
if (action == "read")
{
for (int i = StartAddress; i < (StartAddress + EepromLength[ArrPos]); ++i)
{
if (EEPROM.read(i) != 0 && EEPROM.read(i) != 255)
//if (EEPROM.read(i) != 0)
{
Eeprom_Content += char(EEPROM.read(i));
}
}
return Eeprom_Content;
}
if (action == "write")
{
//Clear EEPROM first
for (int i = StartAddress; i < (StartAddress + EepromLength[ArrPos]); ++i) {
EEPROM.write(i, 0);
}
int bytesCnt = StartAddress;
for (int i = 0; i < value.length(); ++i)
{
EEPROM.write(bytesCnt, value[i]);
++bytesCnt;
}
// Commit changes to EEPROM
EEPROM.commit();
// Calculate new MD5 and write to EEPROM
if (StartAddress != eeprommd5_Address)
{
EepromMD5();
}
}
}
int CheckEeprom()
{
// Calculate MD5 of ALL eeprom values and compare with MD5 written in eeprom
MD5Builder md5;
md5.begin();
int SizeOfArr = (sizeof(EepromAdress) / 4 ) - 1 ;
String Eeprom_Content;
String CurrentMD5 = HandleEeprom(eeprommd5_Address, "read");
for (int i = 0; i < (SizeOfArr + 1); i++)
{
if (EepromAdress[i] != eeprommd5_Address)
{
Eeprom_Content += HandleEeprom(EepromAdress[i], "read");
}
}
md5.add(Eeprom_Content);
md5.calculate();
if (md5.toString() != CurrentMD5)
{
return 0;
}
else
{
return 1;
}
}
void EepromMD5()
{
MD5Builder md5;
md5.begin();
int SizeOfArr = (sizeof(EepromAdress) / 4 ) - 1 ;
String Eeprom_Content;
for (int i = 0; i < (SizeOfArr + 1); i++)
{
if (EepromAdress[i] != eeprommd5_Address)
{
Eeprom_Content += HandleEeprom(EepromAdress[i], "read");
}
}
md5.add(Eeprom_Content);
md5.calculate();
String value = md5.toString();
int ArrPos;
// find eeprommd5_Address in array
for (int i = 0; i < (SizeOfArr + 1); i++)
{
if (EepromAdress[i] == eeprommd5_Address)
{
ArrPos = i;
break;
}
}
//Clear EEPROM first
for (int i = eeprommd5_Address; i < (eeprommd5_Address + EepromLength[ArrPos]); ++i) {
EEPROM.write(i, 0);
}
int bytesCnt = eeprommd5_Address;
for (int i = 0; i < value.length(); ++i)
{
EEPROM.write(bytesCnt, value[i]);
++bytesCnt;
}
// Commit changes to EEPROM
EEPROM.commit();
}
void setup()
{
Serial.begin(115200);
delay(500);
int SizeOfArr = (sizeof(EepromAdress) / 4 ) - 1 ;
int eeprom_alloc = EepromAdress[SizeOfArr] + EepromLength[SizeOfArr];
EEPROM.begin(eeprom_alloc);
String eepromVersion = HandleEeprom(version_Address, "read");
if (eepromVersion != ESPimaticVersion)
{
ErrorList[ErrorUpgrade] = 1;
HandleEeprom(version_Address, "write", ESPimaticVersion);
}
// Check if EEPROM is valid
int EepromStatus = CheckEeprom();
if (EepromStatus != 1 && ErrorList[ErrorUpgrade] != 1)
{
ErrorList[ErrorEeprom] = 1;
}
// Check if SPIFFS is OK
if (!SPIFFS.begin())
{
Serial.println("SPIFFS failed, needs formatting");
handleFormat();
delay(500);
ESP.restart();
}
else
{
FSInfo fs_info;
if (!SPIFFS.info(fs_info))
{
Serial.println("fs_info failed");
}
else
{
FSTotal = fs_info.totalBytes;
FSUsed = fs_info.usedBytes;
}
}
BSlocal = HandleEeprom(bslocal_Address, "read");
String IREnabled = HandleEeprom(enableir_Address, "read");
if (IREnabled == "1")
{
irsend.begin();
}
DeviceName = HandleEeprom(devicename_Address, "read");
MatrixEnabled = HandleEeprom(enablematrix_Address, "read");
if (MatrixEnabled == "1")
{
String MatrixPin = HandleEeprom(matrixpin_Address, "read");
ShowOnMatrix = HandleEeprom(showonmatrix_Address, "read");
MatrixIntensity = HandleEeprom(matrixintensity_Address, "read");
LEDpin = MatrixPin.toInt();
lc = LedControl(LEDpin, 2);
/*
The MAX72XX is in power-saving mode on startup,
we have to do a wakeup call
*/
lc.shutdown(0, false);
lc.shutdown(1, false);
/* Set the brightness to a medium values */
lc.setIntensity(0, MatrixIntensity.toInt());
lc.setIntensity(1, MatrixIntensity.toInt());
/* and clear the display */
lc.clearDisplay(0);
lc.clearDisplay(1);
}
String ssidStored = HandleEeprom(ssid_Address, "read");
String passStored = HandleEeprom(password_Address, "read");
if (ssidStored == "" || passStored == "")
{
Serial.println("No wifi configuration found, starting in AP mode");
Serial.println("SSID: ");
Serial.println(APssid);
Serial.println("password: ");
Serial.println(APpassword);
WiFi.mode(WIFI_AP);
WiFi.softAP(APssid, APpassword);
WMode = "AP";
Serial.print("Connected to ");
Serial.println(APssid);
Serial.print("IP address: ");
Serial.println(WiFi.softAPIP());
if (MatrixEnabled == "1")
{
// Display 'AP' on LED's
CharOnLED(30, 0);
CharOnLED(15, 1);
}
}
else
{
int i = 0;
int row = 0;
int col = 0;
Serial.println("Connecting to :");
Serial.println(ssidStored);
WiFi.mode(WIFI_STA);
WiFi.begin(ssidStored.c_str(), passStored.c_str());
while (WiFi.status() != WL_CONNECTED && i < 31 && MatrixEnabled == "1")
{
delay(1000);
Serial.print(".");
lc.setLed(0, row, col, true);
lc.setLed(1, row, col, true);
++i;
++row;
// if (col == 8) { ++col; }
if (row == 8) {
row = 0;
++col;
}
}
while (WiFi.status() != WL_CONNECTED && i < 31 && MatrixEnabled != "0")
{
delay(1000);
Serial.print(".");
++i;
}
if (WiFi.status() != WL_CONNECTED && i >= 30)
{
WiFi.disconnect();
delay(1000);
Serial.println("");
Serial.println("Couldn't connect to network :( ");
Serial.println("Setting up access point");
Serial.println("SSID: ");
Serial.println(APssid);
Serial.println("password: ");
Serial.println(APpassword);
WiFi.mode(WIFI_AP);
WiFi.softAP(APssid, APpassword);
WMode = "AP";
Serial.print("Connected to ");
Serial.println(APssid);
IPAddress myIP = WiFi.softAPIP();
Serial.print("IP address: ");
Serial.println(myIP);
if (MatrixEnabled == "1")
{
// Display 'AP' on LED's
CharOnLED(30, 0);
CharOnLED(15, 1);
}
}
else
{
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssidStored);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (MatrixEnabled == "1")
{
// Display 'OK' on LED's
CharOnLED(25, 0);
CharOnLED(29, 1);
}
}
}
String RelayEnabled = HandleEeprom(enablerelay_Address, "read");
if (RelayEnabled == "1")
{
String relay1pin = HandleEeprom(relay1pin_Address, "read");
String relay1type = HandleEeprom(relay1type_Address, "read");
String relay2pin = HandleEeprom(relay2pin_Address, "read");
String relay2type = HandleEeprom(relay2type_Address, "read");
String relay3pin = HandleEeprom(relay3pin_Address, "read");
String relay3type = HandleEeprom(relay3type_Address, "read");
String relay4pin = HandleEeprom(relay4pin_Address, "read");
String relay4type = HandleEeprom(relay4type_Address, "read");
pinMode(relay1pin.toInt(), OUTPUT);
if (relay1type == "0")
{
digitalWrite(relay1pin.toInt(), HIGH);
}
else
{
digitalWrite(relay1pin.toInt(), LOW);
}
pinMode(relay2pin.toInt(), OUTPUT);
if (relay2type == "0")
{
digitalWrite(relay2pin.toInt(), HIGH);
}
else
{
digitalWrite(relay2pin.toInt(), LOW);
}
pinMode(relay3pin.toInt(), OUTPUT);
if (relay3type == "0")
{
digitalWrite(relay3pin.toInt(), HIGH);
}
else
{
digitalWrite(relay3pin.toInt(), LOW);
}
pinMode(relay4pin.toInt(), OUTPUT);
if (relay4type == "0")
{
digitalWrite(relay4pin.toInt(), HIGH);
}
else
{
digitalWrite(relay4pin.toInt(), LOW);
}
}
// If no root page && AP mode, set root to simple upload page
if (!SPIFFS.exists("/root.html") && WMode != "AP")
{
server.on("/", handle_fupload_html);
}
// If connected to AP mode, set root to simple wifi settings page
if (WMode == "AP")
{
server.on("/", handle_wifim_html);
}
// Format Flash ROM - dangerous! Remove if you dont't want this option!
server.on ( "/format", handleFormat );
server.on("/ping", handle_ping);
server.on("/loginm", handle_loginm_html);
server.on("/login_ajax", handle_login_ajax);
server.on("/root_ajax", handle_root_ajax);
server.on("/ds18b20_ajax", handle_ds18b20_ajax);
server.on("/wifi_ajax", handle_wifi_ajax);
server.on("/pimatic_ajax", handle_pimatic_ajax);
server.on("/ledmatrix_ajax", handle_ledmatrix_ajax);
server.on("/irled_ajax", handle_irled_ajax);
server.on("/relay_ajax", handle_relay_ajax);
server.on("/dht_ajax", handle_dht_ajax);
server.on("/esp_ajax", handle_esp_ajax);
server.on("/adc_ajax", handle_adc_ajax);
server.on("/kwhint_ajax", handle_kwhint_ajax);
//server.on("/led_ajax", handle_led_ajax);
server.on("/api", handle_api);
server.on("/updatefwm", handle_updatefwm_html);
server.on("/fupload", handle_fupload_html);
server.on("/filemanager_ajax", handle_filemanager_ajax);
server.on("/delete", handleFileDelete);
// Upload firmware:
server.on("/updatefw2", HTTP_POST, []() {
server.sendHeader("Connection", "close");
server.sendHeader("Access-Control-Allow-Origin", "*");
server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
ESP.restart();
}, []() {
HTTPUpload& upload = server.upload();
if (upload.status == UPLOAD_FILE_START)
{
fileName = upload.filename;
Serial.setDebugOutput(true);
Serial.printf("Update: %s\n", upload.filename.c_str());
uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
if (!Update.begin(maxSketchSpace)) { //start with max available size
Update.printError(Serial);
}
}
else if (upload.status == UPLOAD_FILE_WRITE)
{
if (Update.write(upload.buf, upload.currentSize) != upload.currentSize)
{
Update.printError(Serial);
}
}
else if (upload.status == UPLOAD_FILE_END)
{
if (Update.end(true)) //true to set the size to the current progress
{
Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
}
else
{
Update.printError(Serial);
}
Serial.setDebugOutput(false);
}
yield();
});
// upload file to SPIFFS
server.on("/fupload2", HTTP_POST, []() {
server.sendHeader("Connection", "close");
server.sendHeader("Access-Control-Allow-Origin", "*");
server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
}, []() {
HTTPUpload& upload = server.upload();
if (upload.status == UPLOAD_FILE_START)
{
fileName = upload.filename;
Serial.setDebugOutput(true);
//fileName = upload.filename;
Serial.println("Upload Name: " + fileName);
String path;
if (fileName.indexOf(".css") >= 0)
{
path = "/css/" + fileName;
}
else if (fileName.indexOf(".js") >= 0)
{
path = "/js/" + fileName;
}
else if (fileName.indexOf(".otf") >= 0 || fileName.indexOf(".eot") >= 0 || fileName.indexOf(".svg") >= 0 || fileName.indexOf(".ttf") >= 0 || fileName.indexOf(".woff") >= 0 || fileName.indexOf(".woff2") >= 0)
{
path = "/fonts/" + fileName;
}
else
{
path = "/" + fileName;
}
UploadFile = SPIFFS.open(path, "w");
// already existing file will be overwritten!
}
else if (upload.status == UPLOAD_FILE_WRITE)
{
if (UploadFile)
UploadFile.write(upload.buf, upload.currentSize);
Serial.println(fileName + " size: " + upload.currentSize);
}
else if (upload.status == UPLOAD_FILE_END)
{
Serial.print("Upload Size: ");
Serial.println(upload.totalSize); // need 2 commands to work!
if (UploadFile)
UploadFile.close();
}
yield();
});
//called when the url is not defined here
//use it to load content from SPIFFS
server.onNotFound([]() {
if (!handleFileRead(server.uri()))
server.send(404, "text/plain", "FileNotFound");
});
//here the list of headers to be recorded
const char * headerkeys[] = {"User-Agent","Cookie"} ;
size_t headerkeyssize = sizeof(headerkeys)/sizeof(char*);
//ask server to track these headers
server.collectHeaders(headerkeys, headerkeyssize );
telnet.begin();
telnet.setNoDelay(true);
server.begin();
Serial.println("HTTP server started");
EnableWebAuth = HandleEeprom(enablewebauth_Address, "read");
DHTEnabled = HandleEeprom(enabledht_Address, "read");
if (DHTEnabled == "1")
{
String dhtinterval = HandleEeprom(dhtinterval_Address, "read");
String dhtpin = HandleEeprom(dhtpin_Address, "read");
String dhttype = HandleEeprom(dhttype_Address, "read");
dht_sendInterval = (dhtinterval.toInt() * 60000);
uint8_t dhtpinU = atoi (dhtpin.c_str());
if (dhttype == "1")
{
dht = DHT(dhtpin.toInt(), DHT11, 15);
dht.begin();
}
if (dhttype == "2")
{
dht = DHT(dhtpin.toInt(), DHT22, 15);
dht.begin();
}
get_dht();
}
DS18B20Enabled = HandleEeprom(enableds18b20_Address, "read");
if (DS18B20Enabled == "1")
{
String busStored = HandleEeprom(ds18b20pin_Address, "read");
String resoStored = HandleEeprom(ds18b20resolution_Address, "read");
ONE_WIRE_BUS = busStored.toInt();
oneWire = OneWire(ONE_WIRE_BUS);
sensors.begin();
sensors.getAddress(insideThermometer, 0);
int NumSens = sensors.getDeviceCount();
if (NumSens == 0)
{
ErrorList[ErrorDs18b20] = 1;
}
else
{
int reso = sensors.getResolution(insideThermometer);
if (reso != resoStored.toInt())
{
sensors.setResolution(insideThermometer, resoStored.toInt());
}
}
String ds18b20_interval = HandleEeprom(ds18b20interval_Address, "read");
ds18b20_sendInterval = (ds18b20_interval.toInt() * 60000);
get_ds18b20;
}
ADCEnabled = HandleEeprom(enableadc_Address, "read");
kwhintEnabled = HandleEeprom(kwhintenable_Address, "read");
if (kwhintEnabled == "1")
{
String c = HandleEeprom(kwhintc_Address, "read");
kwhintc = c.toInt();
String kwhintpin = HandleEeprom(kwhintpin_Address, "read");
pinMode(kwhintpin.toInt(), INPUT);
attachInterrupt(kwhintpin.toInt(), handle_kwh_interrupt, FALLING);
}
String DSEnabled = HandleEeprom(enabledsleep_Address, "read");
if (DSEnabled == "1")
{
String DSbackdoor = HandleEeprom(dsleepbackdoor_Address, "read");
String DSbackdoorEnabled = get_data(DSbackdoor);
if (DSbackdoorEnabled != "1")
{
String DSaction = HandleEeprom(dsleepaction_Address, "read");
String sleeptime = HandleEeprom(dsleepinterval_Address, "read");
if (DSaction == "1") //DS18B20
{
String temp = get_ds18b20();
String ds18b20_var = HandleEeprom(ds18b20var_Address, "read");
send_data(temp, ds18b20_var);
}
if (DSaction == "2") //DHT
{
String dhttemp_var = HandleEeprom(dhttempvar_Address, "read");
String dhthum_var = HandleEeprom(dhthumvar_Address, "read");
String dhtTempHum = get_dht();
int commaIndex = dhtTempHum.indexOf(",");
int secondCommaIndex = dhtTempHum.indexOf(",", commaIndex+1);
String dht_temp = dhtTempHum.substring(0, commaIndex);
String dht_hum = dhtTempHum.substring(commaIndex+1, secondCommaIndex);
if(dht_temp != "nan")
{
send_data(dht_temp, dhttemp_var);
}
if(dht_hum != "nan")
{
send_data(dht_hum, dhthum_var);
}
}
if (DSaction == "3") //ADC
{
ADC = analogRead(A0);
String adc_var = HandleEeprom(adcvar_Address, "read");
send_data(String(ADC), adc_var);
}
Serial.println("Done. Sleeping for " + String(sleeptime.toInt()) + " minutes");
ESP.deepSleep((sleeptime.toInt() * 60000000), WAKE_RF_DEFAULT); // Sleep for 60 seconds
}
else
{
Serial.println("DeepSleep is enabled, but backdoor value found at " + String(DSbackdoor));
}
}
}
String getContentType(String filename) {
if (server.hasArg("download")) return "application/octet-stream";
else if (filename.endsWith(".htm")) return "text/html";
else if (filename.endsWith(".html")) return "text/html";
else if (filename.endsWith(".css")) return "text/css";
else if (filename.endsWith(".js")) return "application/javascript";
else if (filename.endsWith(".png")) return "image/png";
else if (filename.endsWith(".gif")) return "image/gif";
else if (filename.endsWith(".jpg")) return "image/jpeg";
else if (filename.endsWith(".ico")) return "image/x-icon";
else if (filename.endsWith(".xml")) return "text/xml";
else if (filename.endsWith(".pdf")) return "application/x-pdf";
else if (filename.endsWith(".zip")) return "application/x-zip";
else if (filename.endsWith(".gz")) return "application/x-gzip";
return "text/plain";
}
bool handleFileRead(String path)
{
Serial.println("handleFileRead: " + path);
if (path.endsWith("/")) path += "root.html";
if (path == "/js/insert.js" && BSlocal != "1")
{
path = "/js/insert-web.js";
}
if (path == "/js/insert.js" && BSlocal == "1")
{
path = "/js/insert-local.js";
}
String contentType = getContentType(path);
String pathWithGz = path + ".gz";
if (SPIFFS.exists(pathWithGz) || SPIFFS.exists(path))
{
// ingelogd?
String header;
if (!is_authenticated(1) && path != "/login.html" && EnableWebAuth == "1" && !path.startsWith("/js/insert-"))
{
String header = "HTTP/1.1 301 OK\r\nLocation: /login.html\r\nCache-Control: no-cache\r\n\r\n";
server.sendContent(header);
}
else
{
// je komt hier als je ingelogd bent
if (SPIFFS.exists(pathWithGz))
path += ".gz";
File file = SPIFFS.open(path, "r");
if ( (path.startsWith("/css/") || path.startsWith("/js/") || path.startsWith("/fonts/")) && !path.startsWith("/js/insert"))
{
server.sendHeader("Cache-Control"," max-age=31104000");
}
else
{
server.sendHeader("Connection", "close");
}
size_t sent = server.streamFile(file, contentType);
size_t contentLength = file.size();
file.close();
return true;
}
}
else
{
//Serial.println(path);
}
return false;
}
void handle_api()
{
// Get vars for all commands
String action = server.arg("action");
String value = server.arg("value");
String api = server.arg("api");
String EspimaticApi = HandleEeprom(espimaticapikey_Address, "read");
if (api != EspimaticApi && EnableWebAuth == "1" && !is_authenticated(0) )
{
server.send ( 200, "text/html", "unauthorized");
delay(500);
}
else
{
if (action == "ir")
{
server.send ( 200, "text/html", "OK");
unsigned int ArrayKey[512];
char *tmp;
int i = 0;
tmp = strtok(&value[0], ",");
while (tmp)
{
ArrayKey[i++] = atoi(tmp);
tmp = strtok(NULL, ",");
}
int SizeOfArr = sizeof(ArrayKey);
irsend.sendRaw(ArrayKey, 227, 38);
}
if (action == "reboot" && value == "true")
{
server.send ( 200, "text/html", "OK");
delay(500);
ESP.restart();
}
if (action == "matrix_brightness" && value != "status")
{
lc.setIntensity(0, value.toInt());
lc.setIntensity(1, value.toInt());
MatrixIntensity = value;
server.send ( 200, "text/html", "OK");
}
if (action == "matrix_brightness" && value == "status")
{
server.send ( 200, "text/html", MatrixIntensity);
}
if (action == "matrix_display" && value == "on")
{
server.send ( 200, "text/html", "OK");
lc.shutdown(0, false);
lc.shutdown(1, false);
}
if (action == "matrix_display" && value == "off")
{
server.send ( 200, "text/html", "OK");
lc.shutdown(0, true);
lc.shutdown(1, true);
}
if (action == "relay1")
{
String relay1_pin = HandleEeprom(relay1pin_Address, "read");
String relay1type = HandleEeprom(relay1type_Address, "read");
if (value == "on")
{
if (relay1type == "0") { digitalWrite(relay1_pin.toInt(), LOW); }
if (relay1type == "1") { digitalWrite(relay1_pin.toInt(), HIGH); }
server.send ( 200, "text/html", "OK");
}
if (value == "off")
{
if (relay1type == "0") { digitalWrite(relay1_pin.toInt(), HIGH); }
if (relay1type == "1") { digitalWrite(relay1_pin.toInt(), LOW); }
server.send ( 200, "text/html", "OK");
}
if (value == "status")
{
int relay1_status = digitalRead(relay1_pin.toInt());
if (relay1_status == 0 && relay1type == "0")
{