forked from sticilface/ESPmanager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathESPmanager.cpp
More file actions
1938 lines (1507 loc) · 59.8 KB
/
ESPmanager.cpp
File metadata and controls
1938 lines (1507 loc) · 59.8 KB
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 "ESPmanager.h"
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <ArduinoJson.h>
#include <ESP8266mDNS.h>
#include "MD5Builder.h"
extern "C" {
#include "user_interface.h"
}
ESPmanager::ESPmanager(
ESP8266WebServer & HTTP, FS & fs, const char* host, const char* ssid, const char* pass) : _HTTP(HTTP), _fs(fs)
{
httpUpdater.setup(&_HTTP);
// This sets the default fallback options...
if (host && (strlen(host) < 32)) {
_host = strdup(host);
}
if (ssid && (strlen(ssid) < 32)) {
_ssid_hardcoded = ssid;
}
if (pass && (strlen(pass) < 63)) {
_pass_hardcoded = pass;
}
_manageWiFi = true;
}
ESPmanager::~ESPmanager()
{
// if (ota_server)
// {
// delete ota_server;
// ota_server = NULL;
// };
if (_host) {
free((void*)_host);
_host = nullptr;
};
if (_pass) {
free((void*)_pass);
_pass = nullptr;
};
if (_ssid) {
free((void*)_ssid);
_ssid = nullptr;
};
if (_APpass) {
free((void*)_APpass);
_APpass = nullptr;
};
if (_APssid) {
free((void*)_APssid);
_APssid = nullptr;
};
if (_IPs) {
delete _IPs;
_IPs = nullptr;
};
if (_APmac) {
delete _APmac;
_APmac = nullptr;
}
if (_STAmac) {
delete _STAmac;
_STAmac = nullptr;
}
if (_OTApassword) {
delete _OTApassword;
_OTApassword = nullptr;
}
}
void ESPmanager::begin()
{
ESPMan_Debugln("Settings Manager V" ESPMANVERSION);
wifi_set_sleep_type(NONE_SLEEP_T); // workaround no modem sleep.
if (_fs.begin()) {
ESPMan_Debugln(F("File System mounted sucessfully"));
_NewFilesCheck();
if (!_FilesCheck(true)) {
ESPMan_Debugln(F("Major FAIL, required files are NOT in SPIFFS, please upload required files"));
} else {
_NewFilesCheck();
}
if ( LoadSettings() ) {
ESPMan_Debugln("Load settings returned true");
} else {
ESPMan_Debugln("Load Settings returned false");
}
} else {
ESPMan_Debugln(F("File System mount failed"));
}
// needs to be set before WiFi.Begin() and DHCP request
if (_host) {
if (WiFi.hostname(_host)) {
ESPMan_Debug(F("Host Name Set: "));
ESPMan_Debugln(_host);
}
} else {
char tmp[15];
sprintf(tmp, "esp8266-%06x", ESP.getChipId());
_host = strdup(tmp);
ESPMan_Debug(F("Default Host Name: "));
ESPMan_Debugln(_host);
}
if (_manageWiFi) {
Serial.print("Connecting to WiFi...");
WiFi.mode(WIFI_STA);
if (!_APssid) {
_APssid = strdup(_host);
}
if (!Wifistart()) {
ESPMan_Debug(F("WiFi Failed: "));
if (_APrestartmode > 1) { // 1 = none, 2 = 5min, 3 = 10min, 4 = whenever : 0 is reserved for unset...
_APtimer = millis();
// if (!_APenabled) {
InitialiseSoftAP();
ESPMan_Debug(F("Starting AP"));
// }
ESPMan_Debugln();
} else {
ESPMan_Debugln(F("Soft AP disbaled by config"));
}
} else {
Serial.print(F("Success\nConnected to "));
Serial.print(WiFi.SSID());
Serial.print(" (");
Serial.print(WiFi.localIP());
Serial.println(")");
}
}
// if (_APrestartmode) {
// ESPMan_Debugln(F("Soft AP enabled by config"));
// InitialiseSoftAP();
// } else { ESPMan_Debugln(F("Soft AP disbaled by config")); }
InitialiseFeatures();
_HTTP.on("/espman/data.esp", std::bind(&ESPmanager::HandleDataRequest, this));
_HTTP.on("/espman/upload", HTTP_POST , [this]() { _HTTP.send(200, "text/plain", ""); }, std::bind(&ESPmanager::handleFileUpload, this) );
_HTTP.serveStatic("/espman", _fs, "/espman", "max-age=86400");
}
// template<class T>
// void ESPmanager::_extract( const char * name, T dest )
// {
// }
void ESPmanager::_extractkey(JsonObject& root, const char * name, char *& ptr )
{
if (name && root.containsKey(name)) {
const char* temp = root[name];
if (ptr) {
free(ptr);
ptr = nullptr;
};
if (!ptr && temp) {
ptr = strdup(temp);
}
}
}
bool ESPmanager::LoadSettings()
{
DynamicJsonBuffer jsonBuffer(1000);
File f = _fs.open(SETTINGS_FILE, "r");
if (!f) {
ESPMan_Debugln(F("Settings file open failed!"));
return false;
}
char * data = new char[f.size()];
// prevent nullptr exception if can't allocate
if (data) {
// This method give a massive improvement in file reading speed for SPIFFS files..
// 2K file down to 1-2ms from 60ms
int bytesleft = f.size();
int position = 0;
while ((f.available() > -1) && (bytesleft > 0)) {
// get available data size
int sizeAvailable = f.available();
if (sizeAvailable) {
int readBytes = sizeAvailable;
// read only the asked bytes
if (readBytes > bytesleft) {
readBytes = bytesleft ;
}
// get new position in buffer
char * buf = &data[position];
// read data
int bytesread = f.readBytes(buf, readBytes);
bytesleft -= bytesread;
position += bytesread;
}
// time for network streams
delay(0);
}
//////
f.close();
JsonObject& root = jsonBuffer.parseObject(data);
if (!root.success()) {
ESPMan_Debugln(F("Parsing settings file Failed!"));
return false;
}
_extractkey(root, "host", _host);
_extractkey(root, "ssid", _ssid);
_extractkey(root, "pass", _pass);
_extractkey(root, "APpass", _APpass);
_extractkey(root, "APssid", _APssid);
// if (root.containsKey("host")) {
// const char* host = root[F("host")];
// if (_host) {
// free((void*)_host);
// _host = nullptr;
// };
// if (host) { _host = strdup(host); } else { _host = nullptr ; } ;
// }
// if (root.containsKey("ssid")) {
// const char* ssid = root["ssid"];
// if (_ssid) {
// free((void*)_ssid);
// _ssid = nullptr;
// };
// if (ssid) { _ssid = strdup(ssid); } else { _ssid = nullptr ; } ;
// }
// if (root.containsKey("pass")) {
// const char* pass = root["pass"];
// if (_pass) {
// free((void*)_pass);
// _pass = nullptr;
// };
// if (pass) { _pass = strdup(pass); } else { _pass = nullptr; } ;
// }
// if (root.containsKey("APpass")) {
// const char* APpass = root["APpass"];
// if (_APpass) {
// free((void*)_APpass);
// _APpass = nullptr;
// };
// if (APpass) { _APpass = strdup(APpass); } else { _APpass = nullptr; } ;
// }
// if (root.containsKey("APssid")) {
// const char* APssid = root["APssid"];
// if (_APssid) {
// free((void*)_APssid);
// _APssid = nullptr;
// };
// if (APssid) { _APssid = strdup(APssid); } else {_APssid = nullptr; } ;
// }
if (root.containsKey("APchannel")) {
long APchannel = root["APchannel"];
if (APchannel < 13 && APchannel > 0) {
_APchannel = (uint8_t)APchannel;
}
}
if (root.containsKey("DHCP")) {
_DHCP = root["DHCP"];
}
if (root.containsKey("APenabled")) {
_APenabled = root["APenabled"];
}
if (root.containsKey("APrestartmode")) {
_APrestartmode = root["APrestartmode"];
}
if (root.containsKey("APhidden")) {
_APhidden = root["APhidden"];
}
if (root.containsKey("OTAenabled")) {
_OTAenabled = root["OTAenabled"];
}
_extractkey(root, "OTApassword", _OTApassword);
// if (root.containsKey("OTApassword")) {
// const char* OTApassword = root["OTApassword"];
// if (_OTApassword) {
// free((void*)_OTApassword);
// _OTApassword = nullptr;
// };
// if (OTApassword) { _OTApassword = strdup(OTApassword); } else {_OTApassword = nullptr; } ;
// }
if (root.containsKey("mDNSenable")) {
_mDNSenabled = root["mDNSenable"];
}
if (root.containsKey("WiFimanage")) {
_manageWiFi = root["WiFimanage"];
}
// if (root.containsKey("OTAusechipID"))
// {
// _OTAusechipID = root["OTAusechipID"];
// //_manageWiFi = (strcmp(manageWiFi, "true") == 0) ? true : false;
// }
if (root.containsKey("IPaddress") && root.containsKey("Gateway") && root.containsKey("Subnet")) {
const char* ip = root[F("IPaddress")];
const char* gw = root[F("Gateway")];
const char* sn = root[F("Subnet")];
if (!_DHCP) {
// only bother to allocate memory if dhcp is NOT being used.
if (_IPs) {
delete _IPs;
_IPs = NULL;
};
_IPs = new IPconfigs_t;
_IPs->IP.fromString(String(ip));
_IPs->GW.fromString(String(gw));
_IPs->SN.fromString(String(sn));
}
}
if (root.containsKey("STAmac")) {
uint8_t savedmac[6] = {0};
uint8_t currentmac[6] = {0};
WiFi.macAddress(currentmac);
for (uint8_t i = 0; i < 6; i++) {
savedmac[i] = root["STAmac"][i];
}
if (memcmp( (const void *)savedmac, (const void *) currentmac, 6 ) != 0 ) {
ESPMan_Debugln("Saved STA MAC does not equal native mac");
if (_STAmac) {
delete _STAmac;
_STAmac = nullptr;
}
_STAmac = new uint8_t[6];
memcpy(_STAmac, savedmac, 6);
}
}
if (root.containsKey("APmac")) {
uint8_t savedmac[6] = {0};
uint8_t currentmac[6] = {0};
WiFi.softAPmacAddress(currentmac);
for (uint8_t i = 0; i < 6; i++) {
savedmac[i] = root["APmac"][i];
}
if (memcmp( (const void *)savedmac, (const void *) currentmac, 6 ) != 0 ) {
ESPMan_Debugln("Saved AP MAC does not equal native mac");
if (_APmac) {
delete _APmac;
_APmac = nullptr;
}
_APmac = new uint8_t[6];
memcpy(_APmac, savedmac, 6);
}
}
ESPMan_Debugln(F("----- Saved Variables -----"));
PrintVariables();
ESPMan_Debugln(F("---------------------------"));
delete[] data; // OK to delete as it is wrapped in if (data)
} // end of if data...
return true;
}
void ESPmanager::PrintVariables()
{
#ifdef DEBUG_YES
ESPMan_Debugln(F("VARIABLE STATES: "));
ESPMan_Debugf("_host = %s\n", _host);
ESPMan_Debugf("_ssid = %s\n", _ssid);
ESPMan_Debugf("_pass = %s\n", _pass);
ESPMan_Debugf("_APpass = %s\n", _APpass);
ESPMan_Debugf("_APssid = %s\n", _APssid);
ESPMan_Debugf("_APchannel = %u\n", _APchannel);
(_DHCP) ? ESPMan_Debugln(F("_DHCP = true")) : ESPMan_Debugln(F("_DHCP = false"));
(_APenabled) ? ESPMan_Debugln(F("_APenabled = true")) : ESPMan_Debugln(F("_APenabled = false"));
(_APhidden) ? ESPMan_Debugln(F("_APhidden = true")) : ESPMan_Debugln(F("_APhidden = false"));
(_OTAenabled) ? ESPMan_Debugln(F("_OTAenabled = true")) : ESPMan_Debugln(F("_OTAenabled = false"));
if (_IPs) {
ESPMan_Debug(F("IPs->IP = "));
ESPMan_Debugln( (_IPs->IP).toString() );
ESPMan_Debug(F("IPs->GW = "));
ESPMan_Debugln( (_IPs->GW).toString() );
ESPMan_Debug(F("IPs->SN = "));
ESPMan_Debugln( (_IPs->SN).toString() );
} else {
ESPMan_Debugln(F("NO IPs held in memory"));
}
if (_STAmac) {
ESPMan_Debug(F("STA MAC = "));
ESPMan_Debugf("%02X:%02X:%02X:%02X:%02X:%02X\n", _STAmac[0], _STAmac[1], _STAmac[2], _STAmac[3], _STAmac[4], _STAmac[5]);
} else { ESPMan_Debugln("STA MAC not held in memory"); }
if (_APmac) {
ESPMan_Debug(F("AP MAC = "));
ESPMan_Debugf("%02X:%02X:%02X:%02X:%02X:%02X\n", _APmac[0], _APmac[1], _APmac[2], _APmac[3], _APmac[4], _APmac[5]);
} else { ESPMan_Debugln("AP MAC not held in memory"); }
#endif
}
void ESPmanager::SaveSettings()
{
/*
Settings to save
bool _APhidden = false;
bool _APenabled = false;
bool _OTAenabled = true;
bool _DHCP = true;
uint8_t _APchannel = 1;
const char * _host = NULL;
const char * _ssid = NULL;
const char * _pass = NULL;
const char * _APpass = NULL;
WiFi.localIP()
WiFi.gatewayIP()
WiFi.subnetMask()) + "\",";
*/
ESPMan_Debugf("[ESPmanager::SaveSettings] CALLED\n");
long starttime = millis();
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root[F("host")] = (_host) ? _host : C_null;
root[F("ssid")] = (_ssid) ? _ssid : C_null;
root[F("pass")] = (_pass) ? _pass : C_null;
root[F("APrestartmode")] = _APrestartmode;
root[F("APpass")] = (_APpass) ? _APpass : C_null;
root[F("APssid")] = (_APssid) ? _APssid : C_null;
root[F("DHCP")] = (_DHCP) ? true : false;
root[F("APchannel")] = (_APchannel) ? true : false;
root[F("APenabled")] = (_APenabled) ? true : false;
root[F("APhidden")] = (_APhidden) ? true : false;
root[F("OTAenabled")] = (_OTAenabled) ? true : false;
root[F("OTApassword")] = (_OTApassword) ? _OTApassword : C_null;
//root[F("OTAusechipID")] = (_OTAusechipID) ? true : false;
root[F("mDNSenable")] = (_mDNSenabled) ? true : false;
root[F("WiFimanage")] = (_manageWiFi) ? true : false;
char IP[30];
String ip = WiFi.localIP().toString() ;
ip.toCharArray(IP, ip.length() + 3);
char GW[30];
String gw = WiFi.gatewayIP().toString() ;
gw.toCharArray(GW, gw.length() + 3);
char SN[30];
String sn = WiFi.subnetMask().toString() ;
sn.toCharArray(SN, sn.length() + 3);
root[F("IPaddress")] = IP;
root[F("Gateway")] = GW;
root[F("Subnet")] = SN;
JsonArray& macarray = root.createNestedArray("STAmac");
uint8_t mac[6];
WiFi.macAddress(mac);
for (uint8_t i = 0; i < 6; i ++) {
macarray.add(mac[i]);
}
JsonArray& macAParray = root.createNestedArray("APmac");
uint8_t apmac[6];
WiFi.softAPmacAddress(apmac);
for (uint8_t i = 0; i < 6; i ++) {
macAParray.add(apmac[i]);
}
// ESPMan_Debugf("IP = %s, GW = %s, SN = %s\n", IP, GW, SN);
File f = _fs.open(SETTINGS_FILE, "w");
if (!f) {
ESPMan_Debugln(F("Settings file save failed!"));
return;
}
root.prettyPrintTo(f);
f.close();
}
void ESPmanager::handle()
{
static bool triggered = false;
// if (ota_server)
// ota_server->handle();
ArduinoOTA.handle();
if (save_flag) {
SaveSettings();
save_flag = false;
}
if (_APtimer > 0) {
uint32_t timer = 0;
_APtimer = 0;
if (_APrestartmode == 2) { timer = 5 * 60 * 1000; }
if (_APrestartmode == 3) { timer = 10 * 60 * 1000; }
if (millis() - _APtimer > timer) {
WiFi.mode(WIFI_STA); // == WIFI_AP
ESPMan_Debugln("AP Stopped");
}
}
// need to work on this...
// reset trigger if wifi is reconnected...
if (WiFi.status() == WL_CONNECTED && _APrestartmode == 4 && triggered) {
triggered = false;
}
// AP should only be activated for option 4
if (WiFi.status() != WL_CONNECTED && _APrestartmode == 4 && !triggered) {
triggered = true;
static uint32_t _wait = 0;
ESPMan_Debugln(F("WiFi Disconnected: Starting AP"));
WiFi.mode(WIFI_AP_STA);
WiFi.softAP(_APssid, _APpass, (int)_APchannel, (int)_APhidden);
ESPMan_Debugln(F("Done"));
_APtimer = millis();
}
}
void ESPmanager::InitialiseFeatures()
{
// if (_OTAenabled)
// {
// char OTAhost[strlen(_host) + 2];
// strcpy(OTAhost, _host);
// OTAhost[strlen(_host)] = '-';
// OTAhost[strlen(_host) + 1] = 0;
// // if (ota_server)
// // {
// // delete ota_server;
// // ota_server = NULL;
// // };
// ArduinoOTA.begin();
// ota_server = new ArduinoOTA(OTAhost, 8266, true);
// ota_server->setup();
// }
// else
// {
// if (ota_server)
// {
// delete ota_server;
// ota_server = NULL;
// };
// }
// if (_OTAusechipID) {
// char OTAhost[33];
// strcpy(OTAhost, _host);
// OTAhost[strlen(_host)] = '-';
// OTAhost[strlen(_host) + 1] = 0;
// char tmp[15];
// sprintf(tmp, "%02x", ESP.getChipId());
// strcat(OTAhost, tmp);
// ArduinoOTA.setHostname(OTAhost);
// ESPMan_Debugf("OTA host = %s\n", OTAhost);
// } else {
if (_host) {
ArduinoOTA.setHostname(_host);
ESPMan_Debugf("OTA host = %s\n", _host);
};
//}
// Port defaults to 8266
// ArduinoOTA.setPort(8266);
// Hostname defaults to esp8266-[ChipID]
// ArduinoOTA.setHostname(OTAhost);
// No authentication by default
// ArduinoOTA.setPassword((const char *)"123");
ArduinoOTA.onStart([]() {
Serial.print(F( "[ Performing OTA Upgrade ]\n["));
// ("[--------------------------------------------------]\n ");
});
ArduinoOTA.onEnd([]() {
Serial.println(F("]\nOTA End"));
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
static uint8_t done = 0;
uint8_t percent = (progress / (total / 100) );
if ( percent % 2 == 0 && percent != done ) {
Serial.print("-");
done = percent;
}
});
ArduinoOTA.onError([](ota_error_t error) {
Serial.printf("OTA Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) { Serial.println(F("Auth Failed")); }
else if (error == OTA_BEGIN_ERROR) { Serial.println(F("Begin Failed")); }
else if (error == OTA_CONNECT_ERROR) { Serial.println(F("Connect Failed")); }
else if (error == OTA_RECEIVE_ERROR) { Serial.println(F("Receive Failed")); }
else if (error == OTA_END_ERROR) { Serial.println(F("End Failed")); }
});
ArduinoOTA.begin();
// not sure this is needed now.
if (_mDNSenabled) {
MDNS.addService("http", "tcp", 80);
}
}
#ifdef USE_WEB_UPDATER
bool ESPmanager::_upgrade()
{
static const uint16_t httpPort = 80;
static const size_t bufsize = 1024;
// get files list into json
uint8_t files_recieved = 0;
uint8_t files_expected = 0;
HTTPClient http;
String path = String(__updateserver) + String(__updatepath);
http.begin(path); //HTTP
int httpCode = http.GET();
if (httpCode) {
if (httpCode == 200) {
size_t len = http.getSize();
if (len > bufsize) {
ESPMan_Debugln("Receive update length too big. Increase buffer");
return false;
}
uint8_t buff[bufsize] = { 0 }; // max size of input buffer. Don't use String, as arduinoJSON doesn't like it!
// get tcp stream
WiFiClient * stream = http.getStreamPtr();
// read all data from server
while (http.connected() && (len > 0 || len == -1)) {
// get available data size
size_t size = stream->available();
if (size) {
int c = stream->readBytes(buff, ((size > sizeof(buff)) ? sizeof(buff) : size));
if (len > 0) {
len -= c;
}
}
delay(1);
}
http.end();
yield();
DynamicJsonBuffer jsonBuffer;
JsonArray& root = jsonBuffer.parseArray( (char*)buff );
if (!root.success()) {
ESPMan_Debugln("Parse JSON failed");
return false;
} else {
uint8_t count = 0;
for (JsonArray::iterator it = root.begin(); it != root.end(); ++it) {
files_expected++;
JsonObject& item = *it;
const char* value = item["file"];
const char* md5 = item["md5"];
ESPMan_Debugf("[%u] ", files_expected);
String fullpathtodownload = String(__updateserver) + String(value);
String filename = fullpathtodownload.substring( fullpathtodownload.lastIndexOf("/"), fullpathtodownload.length() );
bool downloaded = _DownloadToSPIFFS(fullpathtodownload.c_str() , filename.c_str(), md5 );
if (downloaded) {
ESPMan_Debugf("Download SUCCESS (%s)\n", fullpathtodownload.c_str() );
files_recieved++;
} else {
ESPMan_Debugf("Download FAILED (%s)\n", fullpathtodownload.c_str() );
}
delay(1);
}
}
} else {
ESPMan_Debugf("HTTP CODE [%d]", httpCode);
http.end();
return false;
}
} else {
ESPMan_Debugln("GET request Failed");
http.end();
return false;
}
if (files_recieved == files_expected) {
ESPMan_Debugf("Update Successful [%u/%u] downloaded\n", files_recieved, files_expected);
return true;
} else {
ESPMan_Debugf("Update Error [%u/%u] downloaded succesfully\n", files_recieved, files_expected);
return false;
}
}
bool ESPmanager::_DownloadToSPIFFS(const char * url , const char * filename, const char * md5_true )
{
HTTPClient http;
File f = _fs.open("/tempfile", "w+"); // w+ is to allow read operations on file.... otherwise crc gets 255!!!!!
if (!f) {
ESPMan_Debugln("file open failed");
return false;
} else {
http.begin(url);
int httpCode = http.GET();
if (httpCode > 0) {
if (httpCode == 200) {
int len = http.getSize();
size_t byteswritten = http.writeToStream(&f);
// ESPMan_Debugf("%s downloaded, expected (%s) \n", formatBytes(byteswritten).c_str(), formatBytes(len).c_str() ) ;
bool success = false;
if (f.size() == len || len == -1 ) {
if (md5_true) {
String crc = _file_md5(f);
if (crc = String(md5_true)) {
success = true;
// ESPMan_Debugln("CRC MATCH");
}
} else {
success = true; // set to true if no CRC provided...
}
f.close();
if (success) {
//ESPMan_Debugln("Download Successful");
_fs.rename("/tempfile", filename);
return true;
} else {
ESPMan_Debug("Download FAILED: CRC mismatch");
_fs.remove("/tempfile");
}
} else {
ESPMan_Debugf("Download FAILED %s downloaded (%s required)\n", formatBytes(byteswritten).c_str(), formatBytes(http.getSize()).c_str() );
_fs.remove("/tempfile");
}
} else { ESPMan_Debugf("HTTP code not correct [%d]\n", httpCode); }
} else { ESPMan_Debugf("HTTP code ERROR [%d]\n", httpCode); }
yield();
}
http.end();
f.close();
return false;
}
#endif
String ESPmanager::_file_md5 (File & f)
{
// Md5 check
if (f.seek(0, SeekSet)) {
MD5Builder md5;
md5.begin();
md5.addStream(f, f.size());
md5.calculate();
return md5.toString();
} else {
ESPMan_Debugln("Seek failed on file");
}
}
bool ESPmanager::_FilesCheck(bool startwifi)
{
bool haserror = false;
bool present[file_no];
for (uint8_t i = 0; i < file_no; i++) {
if (!_fs.exists(TRUEfileslist[i])) {
present[i] = false;
haserror = true;
ESPMan_Debugf("ERROR %s does not exist\n", TRUEfileslist[i]);
} else {
present[i] = true;
}
}
if (haserror ) {
// try to start wifi
WiFi.mode(WIFI_STA); // == WIFI_AP
if ( (startwifi && Wifistart() ) || WiFi.status() == WL_CONNECTED) {
Serial.print("Connected to WiFi: ");
Serial.println(WiFi.SSID());
// need this.. taken out tempararily
#ifdef USE_WEB_UPDATER
return _upgrade();
#endif
} else {
ESPMan_Debugln(F("Attempted to download required files, failed no internet. Try hard coding credentials"));
}
}
return !haserror;
}
void ESPmanager::InitialiseSoftAP()
{
WiFiMode mode = WiFi.getMode();
if (!WiFi.enableAP(true)) {
WiFi.mode(WIFI_AP_STA);
}
if (_APmac) {
if ( wifi_set_macaddr(0x01, _APmac)) {
ESPMan_Debugln("AP MAC applied succesfully");
} else {
ESPMan_Debugln("AP MAC FAILED");
}
}
if (mode == WIFI_AP_STA || mode == WIFI_AP) {
WiFi.softAP(_APssid, _APpass, _APchannel, _APhidden);
_APenabled = true;
}
}
bool ESPmanager::Wifistart()
{
if (!WiFi.enableSTA(true)) {
ESPMan_Debugln("[ESPmanager::Wifistart] Could not active STA mode");
return false;
}
ESPMan_Debugf("[ESPmanager::Wifistart] WiFi Mode = %u\n", WiFi.getMode());
wl_status_t status = WiFi.status();
ESPMan_Debugf("[ESPmanager::Wifistart] Pre init - WiFiStatus = %u, ssid %s, psk %s \n", status, WiFi.SSID().c_str(), WiFi.psk().c_str());
if (!_DHCP && _IPs) {
// void config(IPAddress local_ip, IPAddress gateway, IPAddress subnet);
ESPMan_Debugln(F("[ESPmanager::Wifistart] Using Stored IPs"));
WiFi.config(_IPs->IP, _IPs->GW, _IPs->SN);
}
if (_STAmac) {
if (wifi_set_macaddr(0x00, _STAmac)) {
ESPMan_Debugln("[ESPmanager::Wifistart] STA MAC applied succesfully");
} else {
ESPMan_Debugln("[ESPmanager::Wifistart] STA MAC FAILED");
}
}
WiFi.begin(); // This screws EVERYTHING up. just leave it out!
ESPMan_Debugln("[ESPmanager::Wifistart] WiFi init");
uint8_t i = 0;
uint32_t timeout = millis();
// Try SDK connect first
if (WiFi.SSID().length() > 0 && WiFi.psk().length() > 0 ) {
ESPMan_Debugf("[ESPmanager::Wifistart] waiting for SDK auto Connect\n");
while (status != WL_CONNECTED) {// && status != WL_NO_SSID_AVAIL && status != WL_CONNECT_FAILED) {
delay(10);
status = WiFi.status();
if (millis() - timeout > 30000) {
ESPMan_Debugln("[ESPmanager::Wifistart] TIMEOUT");
break;
}
}
}
status = WiFi.status();
ESPMan_Debugf("[ESPmanager::Wifistart] Autoconnect WiFiStatus = %u \n", status);
// Try Hard coded if present
if (status != WL_CONNECTED && _ssid_hardcoded && _pass_hardcoded) {
ESPMan_Debug(F("[ESPmanager::Wifistart] Auto connect failed..\nTrying HARD CODED credentials...\n"));
ESPMan_Debugf("[ESPmanager::Wifistart] Using ssid %s, psk %s \n", _ssid_hardcoded, _pass_hardcoded );
WiFi.begin(_ssid_hardcoded, _pass_hardcoded);
timeout = millis();
while (status != WL_CONNECTED) { //} && status != WL_NO_SSID_AVAIL && status != WL_CONNECT_FAILED) {
delay(10);
status = WiFi.status();
if (millis() - timeout > 30000) {
ESPMan_Debugln("[ESPmanager::Wifistart] TIMEOUT");
break;
}
}
if (status == WL_CONNECTED) {
ESPMan_Debugf("[ESPmanager::Wifistart] Connected copying settigns accross\n");
if (_ssid) {
free((void*)_ssid);
_ssid = nullptr;
};
if (_pass) {
free((void*)_pass);
_pass = nullptr;