forked from sticilface/ESPmanager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ESPmanager.cpp
3457 lines (2505 loc) · 131 KB
/
ESPmanager.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
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>
#include <AsyncJson.h>
#include <MD5Builder.h>
#include <umm_malloc/umm_malloc.h>
#include <time.h>
#include <stdio.h>
#include <WebAuthentication.h>
#include <Hash.h>
extern "C" {
#include "user_interface.h"
}
extern UMM_HEAP_INFO ummHeapInfo;
#define LAST_MODIFIED_DATE "Mon, 20 Jun 2016 14:00:00 GMT"
// Stringifying the BUILD_TAG parameter
#define TEXTIFY(A) #A
#define ESCAPEQUOTE(A) TEXTIFY(A)
// //String buildTag = ESCAPEQUOTE(BUILD_TAG);
// String commitTag = ESCAPEQUOTE(TRAVIS_COMMIT);
// #ifndef BUILD_TAG
// #define BUILD_TAG Not Set
// #endif
// #ifndef COMMIT_TAG
// #define COMMIT_TAG Not Set
// #endif
// #ifndef BRANCH_TAG
// #define BRANCH_TAG Not Set
// #endif
// #ifndef SLUG_TAG
// #define SLUG_TAG Not Set
// #endif
//
// const char * buildTag = ESCAPEQUOTE(BUILD_TAG);
// const char * commitTag = ESCAPEQUOTE(COMMIT_TAG);
// const char * branchTag = ESCAPEQUOTE(BRANCH_TAG);
// const char * slugTag = ESCAPEQUOTE(SLUG_TAG);
ESPmanager::ESPmanager(
AsyncWebServer & HTTP, FS & fs, const char* host, const char* ssid, const char* pass)
: _HTTP(HTTP)
, _fs(fs)
, _events("/espman/events")
, _perminant_host(host)
, _perminant_ssid(ssid)
, _perminant_pass(pass)
{
}
ESPmanager::~ESPmanager()
{
if (settings)
{
delete settings;
}
}
int ESPmanager::begin()
{
using namespace std::placeholders;
using namespace ESPMAN;
// #ifdef RANDOM_MANIFEST_ON_BOOT
// _randomvalue = random(0,300000);
// #endif
ESPMan_Debugln("Settings Manager V" ESPMANVERSION);
// ESPMan_Debugf("REPO: %s\n", slugTag );
// ESPMan_Debugf("BRANCH: %s\n", branchTag );
// ESPMan_Debugf("BuildTag: %s\n", buildTag );
// ESPMan_Debugf("commitTag: %s\n", commitTag );
//
ESPMan_Debugf("True Sketch Size: %u\n", trueSketchSize() );
ESPMan_Debugf("Sketch MD5: %s\n", getSketchMD5().c_str() );
ESPMan_Debugf("Device MAC: %s\n", WiFi.macAddress().c_str() );
wifi_set_sleep_type(NONE_SLEEP_T); // workaround no modem sleep.
if (!_fs.begin()) {
return ERROR_SPIFFS_MOUNT;
}
#ifdef Debug_ESPManager
#ifdef DEBUG_ESP_PORT
DEBUG_ESP_PORT.println("SPIFFS FILES:");
{
Dir dir = SPIFFS.openDir("/");
while (dir.next()) {
String fileName = dir.fileName();
size_t fileSize = dir.fileSize();
DEBUG_ESP_PORT.printf(" FS File: %s\n", fileName.c_str());
}
DEBUG_ESP_PORT.printf("\n");
}
#endif
#endif
int getallERROR = _getAllSettings();
ESPMan_Debugf("[ESPmanager::begin()] _getAllSettings = %i \n", getallERROR);
//settings_t::AP_t test = settings->AP;
if (!settings) {
ESPMan_Debugf("[ESPmanager::begin()] Unable to MALLOC for settings. rebooting....\n");
ESP.restart();
}
if (getallERROR == SPIFFS_FILE_OPEN_ERROR) {
settings->changed = true; // give save button at first boot if no settings file
}
if (!settings->GEN.host()) {
ESPMan_Debugf("[ESPmanager::begin()] Host NOT SET\n");
char tmp[33] = {'\0'};
snprintf(tmp, 32, "esp8266-%06x", ESP.getChipId());
settings->GEN.host = tmp;
}
//
//
// ESPMan_Debugf("[ESPmanager::begin()] host = %s\n", _GEN_SETTINGS.host );
//
int AP_ERROR = 0;
int STA_ERROR = 0;
int AUTO_ERROR = 0;
WiFi.hostname(settings->GEN.host());
if (settings->configured || _perminant_ssid) {
ESPMan_Debugf("[ESPmanager::begin()] (settings->configured || _perminant_ssid) = true \n");
AP_ERROR = _initialiseAP();
ESPMan_Debugf("[ESPmanager::begin()] _initialiseAP = %i \n", AP_ERROR);
STA_ERROR = _initialiseSTA();
ESPMan_Debugf("[ESPmanager::begin()] _initialiseSTA = %i \n", STA_ERROR);
} else if (settings->STA.enabled != STA_DISABLED) {
ESPMan_Debugf("[ESPmanager::begin()] Trying autoconnect\n");
AUTO_ERROR = _autoSDKconnect(); // try an autoconnect, if projectconf fails...
ESPMan_Debugf("[ESPmanager::begin()] _autoSDKconnect() = %i\n", AUTO_ERROR);
if (!AUTO_ERROR) {
ESPMan_Debugf("[ESPmanager::begin()] Auto autoconnect successfull SSID and PSK added \n");
settings->STA.ssid = WiFi.SSID().c_str();
settings->STA.pass = WiFi.psk().c_str();
settings->STA.enabled = true;
settings->changed = true;
}
}
if (_OTAupload) {
ArduinoOTA.setHostname(settings->GEN.host());
if ( (STA_ERROR && STA_ERROR != STA_DISABLED) || AUTO_ERROR || (AP_ERROR == AP_DISABLED && STA_ERROR == STA_DISABLED ) )
{
if (_ap_boot_mode != DISABLED) {
_APenabledAtBoot = true;
ESPMan_Debugf("[ESPmanager::begin()] CONNECT FAILURE: emergency mode enabled for %i\n", (int8_t)_ap_boot_mode * 60 * 1000 );
_emergencyMode(true); // at boot if disconnected don't disable AP...
}
}
//
ArduinoOTA.setPort( settings->GEN.OTAport);
//
if (settings->GEN.OTApassword())
{
ESPMan_Debugf("[ESPmanager::begin()] OTApassword: %s\n",settings->GEN.OTApassword() );
ArduinoOTA.setPassword( (const char *)settings->GEN.OTApassword() );
}
ArduinoOTA.onStart([this]() {
//_events.send("begin","update");
event_printf("update", "begin");
#ifdef DEBUG_ESP_PORT
DEBUG_ESP_PORT.print(F( "[ Performing OTA Upgrade ]\n["));
// ("[--------------------------------------------------]\n ");
#endif
});
ArduinoOTA.onEnd([this]() {
_events.send("end", "update", 0, 5000);
delay(100);
_events.close();
delay(1000);
#ifdef DEBUG_ESP_PORT
DEBUG_ESP_PORT.println(F("]\nOTA End"));
ESP.restart();
#endif
});
ArduinoOTA.onProgress([this](unsigned int progress, unsigned int total) {
static uint8_t done = 0;
uint8_t percent = (progress / (total / 100) );
if ( percent % 2 == 0 && percent != done ) {
#ifdef DEBUG_ESP_PORT
DEBUG_ESP_PORT.print("-");
#endif
event_printf("update", "%u", percent);
done = percent;
}
});
ArduinoOTA.onError([this](ota_error_t error) {
using namespace ESPMAN;
#ifdef DEBUG_ESP_PORT
DEBUG_ESP_PORT.printf("OTA Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) { DEBUG_ESP_PORT.println(F("Auth Failed")); }
else if (error == OTA_BEGIN_ERROR) { DEBUG_ESP_PORT.println(F("Begin Failed")); }
else if (error == OTA_CONNECT_ERROR) { DEBUG_ESP_PORT.println(F("Connect Failed")); }
else if (error == OTA_RECEIVE_ERROR) { DEBUG_ESP_PORT.println(F("Receive Failed")); }
else if (error == OTA_END_ERROR) { DEBUG_ESP_PORT.println(F("End Failed")); }
#endif
if (error) {
event_printf(string_UPDATE, string_ERROR, error);
}
});
ArduinoOTA.begin();
} else {
ESPMan_Debugf("[ESPmanager::begin()] OTA DISABLED\n");
}
if (settings->GEN.mDNSenabled) {
MDNS.addService("http", "tcp", 80);
}
_HTTP.on("/espman/data.esp", std::bind(&ESPmanager::_HandleDataRequest, this, _1 ));
_HTTP.on("/espman/site.appcache", HTTP_ANY, std::bind (&ESPmanager::_handleManifest, this, _1));
_HTTP.on("/espman/upload", HTTP_POST, [this](AsyncWebServerRequest *request) {
request->send(200);
}, std::bind(&ESPmanager::_handleFileUpload, this, _1, _2, _3, _4, _5, _6) );
_events.onConnect([](AsyncEventSourceClient *client){
client->send(NULL,NULL,0,1000);
});
_HTTP.addHandler(&_events);
_HTTP.serveStatic("/espman", _fs, "/espman").setCacheControl("no-store");//.setLastModified(getCompileTime());
_HTTP.serveStatic("/jquery", _fs, "/jquery").setCacheControl("max-age:86400");//.setLastModified(getCompileTime());
_HTTP.on("/espman/update", std::bind(&ESPmanager::_HandleSketchUpdate, this, _1 ));
}
void ESPmanager::handle()
{
using namespace ESPMAN;
static uint32_t timeout = 0;
if (_OTAupload) { ArduinoOTA.handle(); }
// Ony handle manager code every 500ms...
if (millis() - timeout < 500) {
return;
}
timeout = millis();
if (_syncCallback) {
if (_syncCallback()) {
_syncCallback = nullptr;
};
}
if ( _APtimer > 0 && !WiFi.softAPgetStationNum()) {
uint32_t time_total {0};
if (_APenabledAtBoot) {
time_total = (int8_t)_ap_boot_mode * 60 * 1000;
} else {
time_total = (int8_t)_no_sta_mode * 60 * 1000;
}
if (time_total > 0 && millis() - _APtimer > time_total )
{
ESPMan_Debugf("[ESPmanager::handle()] Disabling AP\n");
bool result = WiFi.enableAP(false);
if (result == false)
{
ESPMan_Debugf("[ESPmanager::handle()] ERROR disabling AP\n");
}
_APtimer = 0;
_APtimer2 = 0;
_APenabledAtBoot = false;
} else if (time_total > 0) {
ESPMan_Debugf("[ESPmanager::handle()] Countdown to disabling AP %i\n", (time_total - (millis() - _APtimer) )/1000);
}
// uint32_t timer = 0;
}
// triggered once when no timers.. and wifidisconnected
if (!_APtimer && !_APtimer2 && WiFi.isConnected() == false)
{
// if something is to be done... check that action is not do nothing, or that AP is enabled, or action is reboot...
if ( ( _no_sta_mode != NO_STA_NOTHING ) && ( WiFi.getMode() != WIFI_AP_STA || WiFi.getMode() != WIFI_AP || _no_sta_mode == NO_STA_REBOOT ) ) {
ESPMan_Debugf("[ESPmanager::handle()] WiFi disconnected: starting AP Countdown\n" );
_APtimer2 = millis();
}
//_ap_triggered = true;
}
// only triggered once AP_start_delay has elapsed... and not reset...
// this gives chance for a reconnect..
if (_APtimer2 && !_APtimer && millis() - _APtimer2 > ESPMAN::AP_START_DELAY && !WiFi.isConnected()) {
if (_no_sta_mode == NO_STA_REBOOT) {
ESPMan_Debugf("[ESPmanager::handle()] WiFi disconnected: REBOOTING\n" );
ESP.restart();
} else {
ESPMan_Debugf("[ESPmanager::handle()] WiFi disconnected: starting AP\n" );
_emergencyMode();
}
}
// turn off only if these timers are enabled, but you are reconnected.. and settings have not changed...
// this functions only work for a discconection and reconnection.. when settings have not changed...
if ( (_APtimer2 || _APtimer ) && WiFi.isConnected() == true)
{
if ( !settings || (settings && !settings->changed) && !WiFi.softAPgetStationNum() ) { // stops the AP being disabled if it is the result of changing stuff
settings_t::AP_t APsettings;
APsettings.enabled = false;
_initialiseAP(APsettings);
ESPMan_Debugf("[ESPmanager::handle()] WiFi reconnected: disable AP\n" );
//_ap_triggered = false;
_APtimer = 0;
_APtimer2 = 0;
_APenabledAtBoot = false;
}
}
if (_updateFreq && millis() - _updateTimer > _updateFreq * 60000) {
_updateTimer = millis();
ESPMan_Debugf("Performing update check\n");
_events.send("Checking for updates",nullptr, 0, 5000);
_getAllSettings();
if (settings) {
upgrade(settings->GEN.updateURL());
}
}
if (settings && !settings->changed) {
if (millis() - settings->start_time > SETTINGS_MEMORY_TIMEOUT) {
uint32_t startheap = ESP.getFreeHeap();
delete settings;
settings = nullptr;
ESPMan_Debugf("[ESPmanager::handle()] Deleting Settings. Heap freed = %u (%u)\n", ESP.getFreeHeap() - startheap, ESP.getFreeHeap() );
}
}
}
//format bytes thanks to @me-no-dev
String ESPmanager::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";
}
}
bool ESPmanager::StringtoMAC(uint8_t *mac, const String & input)
{
char tempbuffer[input.length() + 1];
urldecode(tempbuffer, input.c_str() );
String decodedMAC = String(tempbuffer);
String buf;
uint8_t pos = 0;
char tempbuf[5];
bool remaining = true;
do {
buf = decodedMAC.substring(0, decodedMAC.indexOf(':'));
remaining = (decodedMAC.indexOf(':') != -1) ? true : false;
decodedMAC = decodedMAC.substring(decodedMAC.indexOf(':') + 1, decodedMAC.length());
buf.toCharArray(tempbuf, buf.length() + 1);
mac[pos] = (uint8_t)strtol (tempbuf, NULL, 16);
//Serial.printf("position %u = %s ===>%u \n", pos, tempbuf, mac[pos]);
pos++;
} while (remaining);
if (pos == 6) { return true; } else { return false; }
}
//URI Decoding function
//no check if dst buffer is big enough to receive string so
//use same size as src is a recommendation
void ESPmanager::urldecode(char *dst, const char *src)
{
char a, b, c;
if (dst == NULL) { return; }
while (*src) {
if ((*src == '%') &&
((a = src[1]) && (b = src[2])) &&
(isxdigit(a) && isxdigit(b))) {
if (a >= 'a') {
a -= 'a' - 'A';
}
if (a >= 'A') {
a -= ('A' - 10);
} else {
a -= '0';
}
if (b >= 'a') {
b -= 'a' - 'A';
}
if (b >= 'A') {
b -= ('A' - 10);
} else {
b -= '0';
}
*dst++ = 16 * a + b;
src += 3;
} else {
c = *src++;
if (c == '+') { c = ' '; }
*dst++ = c;
}
}
*dst++ = '\0';
}
String ESPmanager::file_md5 (File & f)
{
// Md5 check
if (!f) {
return String();
}
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");
}
}
template <class T> void ESPmanager::sendJsontoHTTP( const T & root, AsyncWebServerRequest *request)
{
AsyncResponseStream *response = request->beginResponseStream("text/json");
response->addHeader(ESPMAN::string_CORS,"*");
response->addHeader(ESPMAN::string_CACHE_CONTROL,"no-store");
root.printTo(*response);
request->send(response);
}
String ESPmanager::getHostname() {
settings_t set;
if (settings) {
set = *settings;
}
int ERROR = _getAllSettings(set);
ESPMan_Debugf("[ESPmanager::_updateUrl()] error = %i\n", ERROR);
if (!ERROR && set.GEN.host() ) {
return String(set.GEN.host());
} else {
char tmp[33] = {'\0'};
snprintf(tmp, 32, "esp8266-%06x", ESP.getChipId());
return String(tmp);
}
}
void ESPmanager::upgrade(const char * path)
{
using namespace ESPMAN;
if (!path) {
event_printf(string_UPGRADE, "[%i]", NO_UPDATE_URL );
return;
}
_getAllSettings();
if (!settings) {
return;
}
int files_expected = 0;
int files_recieved = 0;
int file_count = 0;
DynamicJsonBuffer jsonBuffer;
JsonObject * p_root = nullptr;
uint8_t * buff = nullptr;
bool updatesketch = false;
char msgdata[100]; // delete me when done
_events.send("begin", string_UPGRADE,0, 5000);
ESPMan_Debugf("[ESPmanager::_HandleDataRequest] Checking for Updates: %s\n", path);
String Spath = String(path);
String rooturi = Spath.substring(0, Spath.lastIndexOf('/') );
event_printf(string_CONSOLE, "%s", path);
ESPMan_Debugf("[ESPmanager::upgrade] rooturi=%s\n", rooturi.c_str());
// save new update path for future update checks... (if done via url only for example)
if (settings->GEN.updateURL()) {
if (strcmp(settings->GEN.updateURL(), path) != 0) {
settings->GEN.updateURL = path;
save_flag = true;
}
} else {
settings->GEN.updateURL = path;
save_flag = true;
}
int ret = _parseUpdateJson(buff, jsonBuffer, p_root, path);
if (ret) {
event_printf(string_UPGRADE, string_ERROR2, MANIFST_FILE_ERROR, ret);
ESPMan_Debugf("[ESPmanager::upgrade] MANIFEST ERROR [%i]\n", ret );
return;
}
ESPMan_Debugf("[ESPmanager::_HandleSketchUpdate] _parseUpdateJson success\n");
if (!p_root) {
event_printf(string_UPGRADE, string_ERROR, JSON_OBJECT_ERROR);
ESPMan_Debugf("[ESPmanager::upgrade] JSON ERROR [%i]\n", JSON_OBJECT_ERROR );
return;
}
JsonObject & root = *p_root;
files_expected = root["filecount"];
if (!files_expected) {
event_printf(string_UPGRADE, string_ERROR, UNKNOWN_NUMBER_OF_FILES);
ESPMan_Debugf("[ESPmanager::upgrade] ERROR [%i]\n", UNKNOWN_NUMBER_OF_FILES );
}
JsonArray & array = root["files"];
if (root.containsKey("formatSPIFFS")) {
if (root["formatSPIFFS"] == true) {
ESPMan_Debugf("[ESPmanager::_HandleSketchUpdate] Formatting SPIFFS....");
_fs.format();
ESPMan_Debugf("done\n");
}
}
if (root.containsKey("clearWiFi")) {
if (root["clearWiFi"] == true) {
ESPMan_Debugf("[ESPmanager::_HandleSketchUpdate] Erasing WiFi Config ....");
ESPMan_Debugf("done\n");
}
}
for (JsonArray::iterator it = array.begin(); it != array.end(); ++it) {
file_count++;
JsonObject& item = *it;
String remote_path = String();
// if the is url is set to true then don't prepend the rootUri...
if (item["isurl"] == true) {
remote_path = String(item["location"].asString());
} else {
remote_path = rooturi + String(item["location"].asString());
}
const char* md5 = item["md5"];
String filename = item["saveto"];
if (remote_path.endsWith("bin") && filename == "sketch" ) {
updatesketch = true;
files_recieved++; // add one to keep count in order...
#if defined(DEBUG_ESP_PORT)
DEBUG_ESP_PORT.printf("[%u/%u] BIN Updated pending\n", file_count, files_expected);
#endif
continue;
}
#if defined(DEBUG_ESP_PORT)
DEBUG_ESP_PORT.printf("[%u/%u] Downloading (%s)..", file_count, files_expected, filename.c_str() );
#endif
int ret = _DownloadToSPIFFS(remote_path.c_str(), filename.c_str(), md5 );
if (ret == 0 || ret == FILE_NOT_CHANGED) {
event_printf(string_CONSOLE, "[%u/%u] (%s) : %s", file_count, files_expected, filename.c_str(), (!ret) ? "Downloaded" : "Not changed");
} else {
event_printf(string_CONSOLE, "[%u/%u] (%s) : ERROR [%i]", file_count, files_expected, filename.c_str(), ret);
}
event_printf(string_UPGRADE, "%u", (uint8_t ) (( (float)file_count / (float)files_expected) * 100.0f) );
#if defined(DEBUG_ESP_PORT)
if (ret == 0) {
DEBUG_ESP_PORT.printf("SUCCESS \n");
//files_recieved++;
} else if (ret == FILE_NOT_CHANGED){
DEBUG_ESP_PORT.printf("FILE NOT CHANGED \n");
} else {
DEBUG_ESP_PORT.printf("FAILED [%i]\n", ret );
}
#endif
delay(20);
}
if (updatesketch) {
for (JsonArray::iterator it = array.begin(); it != array.end(); ++it) {
JsonObject& item = *it;
String remote_path = rooturi + String(item["location"].asString());
String filename = item["saveto"];
String commit = root["commit"];
if (remote_path.endsWith("bin") && filename == "sketch" ) {
if ( String( item["md5"].asString() ) != getSketchMD5() ) {
ESPMan_Debugf("START SKETCH DOWNLOAD (%s)\n", remote_path.c_str() );
_events.send("firmware", string_UPGRADE, 0, 5000);
delay(10);
_events.send("Upgrading sketch", nullptr, 0, 5000);
// _fs.end();
ESPhttpUpdate.rebootOnUpdate(false);
t_httpUpdate_return ret = ESPhttpUpdate.update(remote_path);
switch (ret) {
case HTTP_UPDATE_FAILED:
ESPMan_Debugf("HTTP_UPDATE_FAILD Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
// snprintf(msgdata, 100,"FAILD Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str() );
// _events.send(msgdata, "upgrade");
event_printf(string_UPGRADE, "ERROR [%s]", ESPhttpUpdate.getLastErrorString().c_str() );
break;
case HTTP_UPDATE_NO_UPDATES:
ESPMan_Debugf("HTTP_UPDATE_NO_UPDATES");
//_events.send("FAILED no update", "upgrade");
event_printf(string_UPGRADE, "ERROR no update");
break;
case HTTP_UPDATE_OK:
ESPMan_Debugf("HTTP_UPDATE_OK");
_events.send("firmware-end", string_UPGRADE, 0, 1000);
delay(100);
_events.close();
delay(1000);
ESP.reset();
break;
}
} else {
_events.send("No Change to firmware", string_CONSOLE, 0, 5000 );
ESPMan_Debugf("BINARY HAS SAME MD5 as current (%s)\n", item["md5"].asString() );
}
}
}
}
if (buff) {
delete[] buff;
}
_events.send("end", string_UPGRADE, 0, 5000);
}
uint32_t ESPmanager::trueSketchSize() {
return ESP.getSketchSize();
}
String ESPmanager::getSketchMD5()
{
return ESP.getSketchMD5();
}
AsyncEventSource & ESPmanager::getEvent()
{
return _events;
}
size_t ESPmanager::event_printf(const char * topic, const char * format, ... )
{
va_list arg;
va_start(arg, format);
char temp[64];
char* buffer = temp;
size_t len = vsnprintf(temp, sizeof(temp), format, arg);
va_end(arg);
if (len > sizeof(temp) - 1) {
buffer = new char[len + 1];
if (!buffer) {
return 0;
}
va_start(arg, format);
vsnprintf(buffer, len + 1, format, arg);
va_end(arg);
}
_events.send(buffer, topic, 0, 5000);
if (buffer != temp) {
delete[] buffer;
}
return len;
}
int ESPmanager::save() {
using namespace ESPMAN;
_getAllSettings();
if (settings) {
return _saveAllSettings(*settings);
} else {
return SETTINGS_NOT_IN_MEMORY;
}
}
#ifdef USE_WEB_UPDATER
int ESPmanager::_DownloadToSPIFFS(const char * url, const char * filename, const char * md5_true )
{
using namespace ESPMAN;
HTTPClient http;
FSInfo _FSinfo;
int freeBytes = 0;
bool success = false;
int ERROR = 0;
if ( _fs.exists(filename) ) {
File Fcheck = _fs.open(filename, "r");
String crc = file_md5(Fcheck);
if (crc == String(md5_true)) {
Fcheck.close();
return FILE_NOT_CHANGED;
}
Fcheck.close();
}
if (!_fs.info(_FSinfo)) {
return SPIFFS_INFO_FAIL;
}
freeBytes = _FSinfo.totalBytes - _FSinfo.usedBytes;
if (strlen(filename) > _FSinfo.maxPathLength) {
return SPIFFS_FILENAME_TOO_LONG;
}
File f = _fs.open("/tempfile", "w+"); // w+ is to allow read operations on file.... otherwise crc gets 255!!!!!
if (!f) {
return SPIFFS_FILE_OPEN_ERROR;
}
http.begin(url);
int httpCode = http.GET();
if (httpCode == 200) {
int len = http.getSize();
if (len < freeBytes) {
size_t byteswritten = http.writeToStream(&f);
http.end();
if (f.size() == len ||
len == -1 ) { // len = -1 means server did not provide length...
if (md5_true) {
String crc = file_md5(f);
if (crc == String(md5_true)) {
success = true;
} else {
ERROR = CRC_ERROR;
}
} else {
ESPMan_Debugf("\n [ERROR] CRC not provided \n");
success = true; // set to true if no CRC provided...
}
} else {
ERROR = INCOMPLETE_DOWNLOAD;
}
} else {
ERROR = FILE_TOO_LARGE;
}
} else {
ERROR = httpCode;
}
f.close();
if (success) {
if (_fs.exists(filename)) {
_fs.remove(filename);
}
_fs.rename("/tempfile", filename);
} else {
_fs.remove("/tempfile");
}
return ERROR;
}
/*
* Takes POST request with url parameter for the json
*
*
*/
int ESPmanager::_parseUpdateJson(uint8_t *& buff, DynamicJsonBuffer & jsonBuffer, JsonObject *& root, const char * path)
{
using namespace ESPMAN;
ESPMan_Debugf("[ESPmanager::_parseUpdateJson] path = %s\n", path);
HTTPClient http;
http.begin(path); //HTTP
int httpCode = http.GET();
if (httpCode != 200) {
ESPMan_Debugf("[ESPmanager::_parseUpdateJson] HTTP code: %i\n", httpCode );
return httpCode;
}
ESPMan_Debugln("[ESPmanager::_parseUpdateJson] Connected downloading json");
size_t len = http.getSize();
const size_t length = len;
if (len > MAX_BUFFER_SIZE) {
ESPMan_Debugln("[ESPmanager::_parseUpdateJson] Receive update length too big. Increase buffer");
return JSON_TOO_LARGE;
}
//uint8_t buff[bufsize] = { 0 }; // max size of input buffer. Don't use String, as arduinoJSON doesn't like it!
buff = nullptr;
buff = new uint8_t[len];
if (!buff) {
ESPMan_Debugf("[ESPmanager::_parseUpdateJson] failed to allocate buff\n");
return MALLOC_FAIL;
}
// get tcp stream
WiFiClient * stream = http.getStreamPtr();
int position = 0;
// read all data from server
while (http.connected() && (len > 0 || len == -1)) {
// get available data size
size_t size = stream->available();
uint8_t * b = &buff[position];
if (size) {
int c = stream->readBytes(b, ((size > sizeof(buff)) ? sizeof(buff) : size));
position += c;
if (len > 0) {
len -= c;
}
}
delay(0);
}
http.end();
root = &jsonBuffer.parseObject( (char*)buff, length );
if (root->success()) {
ESPMan_Debugf("[ESPmanager::_parseUpdateJson] root->success() = true\n");
return 0;
} else {
ESPMan_Debugf("[ESPmanager::_parseUpdateJson] root->success() = false\n");
return JSON_PARSE_ERROR;
}
}
void ESPmanager::_HandleSketchUpdate(AsyncWebServerRequest *request)
{
ESPMan_Debugf("[ESPmanager::_HandleSketchUpdate] HIT\n" );
if ( request->hasParam("url", true)) {
String path = request->getParam("url", true)->value();
ESPMan_Debugf("[ESPmanager::_HandleSketchUpdate] path = %s\n", path.c_str());
_syncCallback = [ = ]() {
upgrade(path.c_str());
return true;
};
}
AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", "OK");
response->addHeader( ESPMAN::string_CORS,"*");
response->addHeader( ESPMAN::string_CACHE_CONTROL,"no-store");
request->send(response);