forked from jsphuebner/esp32-web-interface
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathesp32-web-interface.ino
More file actions
2918 lines (2664 loc) · 105 KB
/
Copy pathesp32-web-interface.ino
File metadata and controls
2918 lines (2664 loc) · 105 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
/*
FSWebServer - Example WebServer with SPIFFS backend
Copyright (c) 2015 Hristo Gochkov. All rights reserved.
This file is based on the WebServer library for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* This file is part of the esp32 web interface
*
* Copyright (C) 2018 Johannes Huebner <dev@johanneshuebner.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
#include <HTTPClient.h>
#include <WebServer.h>
#include <HTTPUpdateServer.h>
#include <ESPmDNS.h>
#include <ArduinoOTA.h>
#include <Update.h>
#include <FS.h>
#include <Ticker.h>
#include <SD_MMC.h>
#include "RTClib.h"
#include <ESP32Time.h>
#include <time.h>
#include "driver/uart.h"
#include "src/can_driver.h"
#include "src/can_protocol.h"
#ifndef DBG_OUTPUT_PORT
#define DBG_OUTPUT_PORT Serial2
#endif
#ifndef ENABLE_SDCARD
#define ENABLE_SDCARD 1
#endif
#define INVERTER_PORT UART_NUM_0
#define INVERTER_RX 1 //3 - Swapped for Wemos board onto Zombie and other OI boards
#define INVERTER_TX 3 //1 - Swapped for Wemos board onto Zombie and other OI boards
#define UART_TIMEOUT (100 / portTICK_PERIOD_MS)
#define UART_MESSBUF_SIZE 100
#define CAN_NODE_ID_MIN 1
#define CAN_NODE_ID_MAX 127
#ifndef LED_BUILTIN
#define LED_BUILTIN 2 //clashes with SDIO, need to change to suit hardware and uncomment lines
#endif
#define RESERVED_SD_SPACE 2000000000
#define SDIO_BUFFER_SIZE 16384
#define FLUSH_WRITES 60 //flush file every 60 blocks
#define MAX_SD_FILES 200
#define LOG_DELAY_VAL 10000
//HardwareSerial Inverter(INVERTER_PORT);
const char* host = "inverter";
String deviceName = ""; // friendly nickname (Settings → Device Name); also drives the hostname
#define SSE_PORT 81 // push value stream for the gauges page (advertised via /settings)
bool fastUart = false;
bool fastUartAvailable = true;
uint8_t fastUartAttempts = 0; // negotiation storms per boot are bounded — wrong-baud bytes can upset some inverter consoles
bool txrxSwapped = true; // default: swapped for Wemos/OI/Zombie boards
int uartRxPin = INVERTER_RX; // configurable UART pins (the swap toggle flips their roles)
int uartTxPin = INVERTER_TX;
bool apFallback = false; // true = AP broadcasts only while the station link is down
bool canMode = false; // true = CAN bus mode, false = UART mode
int canNodeId = CAN_NODE_ID_MIN;
int canSpeed = 2; // 0=125k, 1=250k, 2=500k
int canRxPin = CAN_RX_PIN;
int canTxPin = CAN_TX_PIN;
// Optional transceiver control pins for boards like the LilyGO T-CAN485:
// a 5V-boost/power enable and a transceiver standby(silent)-enable. -1 = unused.
// The *_inv flag flips the level asserted to ENABLE (default: drive HIGH to
// enable; inverted: drive LOW — e.g. an active-low standby pin).
int canPwrPin = -1; bool canPwrInv = false; // 5V boost / transceiver power
int canEnPin = -1; bool canEnInv = false; // transceiver standby / silent enable
char uartMessBuff[UART_MESSBUF_SIZE];
// Build architecture — the UI only offers board presets whose pin numbers
// suit this chip (ESP32 vs ESP32-S3 have different valid GPIOs)
#if defined(CONFIG_IDF_TARGET_ESP32S3)
#define BOARD_ARCH "esp32s3"
#elif defined(CONFIG_IDF_TARGET_ESP32S2)
#define BOARD_ARCH "esp32s2"
#elif defined(CONFIG_IDF_TARGET_ESP32C3)
#define BOARD_ARCH "esp32c3"
#else
#define BOARD_ARCH "esp32"
#endif
// Drive the optional CAN transceiver enable pins to their active level (call
// before bringing up the TWAI driver). No-op for pins left unconfigured.
static void applyCanEnablePins()
{
if (canPwrPin >= 0) { pinMode(canPwrPin, OUTPUT); digitalWrite(canPwrPin, canPwrInv ? LOW : HIGH); }
if (canEnPin >= 0) { pinMode(canEnPin, OUTPUT); digitalWrite(canEnPin, canEnInv ? LOW : HIGH); }
}
// CAN parameter cache (downloaded from device via segmented SDO)
String canParamJson = "";
bool canParamCacheLoaded = false;
// Virtual spot values: ESP-side CAN RX mappings (configured in the UI,
// stored in /virtualvals.json). Captured frames update these via the CAN
// driver's RX hook; values surface through the json/get command paths.
#define VIRT_MAX 16
struct VirtualVal {
char name[24];
char unit[12];
uint32_t id;
uint8_t pos; // start bit (0-63, little-endian across the frame)
uint8_t len; // bit length (1-32)
bool sgn; // sign-extend the extracted value
float gain;
float offset;
volatile float value;
volatile bool valid;
};
static VirtualVal virtVals[VIRT_MAX];
static int virtCount = 0;
static void canVirtualRxHook(const twai_message_t* f) {
for (int i = 0; i < virtCount; i++) {
VirtualVal& v = virtVals[i];
if (f->identifier != v.id) continue;
uint64_t data = 0;
memcpy(&data, f->data, f->data_length_code > 8 ? 8 : f->data_length_code);
uint64_t mask = (v.len >= 64) ? ~0ULL : ((1ULL << v.len) - 1ULL);
uint64_t raw = (data >> v.pos) & mask;
int64_t sv = (int64_t)raw;
if (v.sgn && v.len < 64 && (raw & (1ULL << (v.len - 1)))) sv = (int64_t)raw - (int64_t)(1ULL << v.len);
v.value = (float)sv * v.gain + v.offset;
v.valid = true;
}
}
// Pull a value field out of a flat JSON object substring
static String jsonField(const String& obj, const char* key) {
String k = String("\"") + key + "\":";
int p = obj.indexOf(k);
if (p < 0) return "";
p += k.length();
while (p < (int)obj.length() && obj[p] == ' ') p++;
if (p < (int)obj.length() && obj[p] == '"') {
int e = obj.indexOf('"', p + 1);
return e > p ? obj.substring(p + 1, e) : "";
}
int e = p;
while (e < (int)obj.length() && obj[e] != ',' && obj[e] != '}') e++;
return obj.substring(p, e);
}
static void canVirtualLoad() {
virtCount = 0;
if (!SPIFFS.exists("/virtualvals.json")) return;
File f = SPIFFS.open("/virtualvals.json", "r");
if (!f) return;
String j = f.readString();
f.close();
int pos = j.indexOf("\"items\"");
if (pos < 0) return;
while (virtCount < VIRT_MAX) {
int os = j.indexOf('{', pos + 1);
if (os < 0) break;
int oe = j.indexOf('}', os);
if (oe < 0) break;
String obj = j.substring(os, oe + 1);
pos = oe;
String name = jsonField(obj, "name");
if (!name.startsWith("v_") || name.length() < 3) continue; // enforced prefix
VirtualVal& v = virtVals[virtCount];
strncpy(v.name, name.c_str(), sizeof(v.name) - 1);
v.name[sizeof(v.name) - 1] = 0;
String unit = jsonField(obj, "unit");
strncpy(v.unit, unit.c_str(), sizeof(v.unit) - 1);
v.unit[sizeof(v.unit) - 1] = 0;
v.id = strtoul(jsonField(obj, "id").c_str(), NULL, 0);
v.pos = constrain(jsonField(obj, "pos").toInt(), 0, 63);
v.len = constrain(jsonField(obj, "len").toInt(), 1, 32);
v.sgn = jsonField(obj, "signed") == "true";
String g = jsonField(obj, "gain");
v.gain = g.length() ? g.toFloat() : 1.0f;
v.offset = jsonField(obj, "offset").toFloat();
v.value = 0;
v.valid = false;
virtCount++;
}
DBG_OUTPUT_PORT.printf("Virtual values: %d loaded\n", virtCount);
}
// Look up a virtual value by name. Returns true when the name belongs to
// the virtual table (membership decides routing — not the name prefix,
// since a device could legitimately expose a value named v_something);
// *out is the captured value or NAN when no frame has been seen yet.
static bool canVirtualFind(const String& name, float* out) {
for (int i = 0; i < virtCount; i++) {
if (name == virtVals[i].name) {
*out = virtVals[i].valid ? virtVals[i].value : NAN;
return true;
}
}
return false;
}
// CAN firmware update background task state
enum CanFwState { CANFW_IDLE = 0, CANFW_WAITBOOT = 1, CANFW_FLASHING = 2, CANFW_DONE = 3, CANFW_ERROR = 4 };
static volatile uint8_t canFwState = CANFW_IDLE;
// True while the CAN firmware-update task owns the TWAI driver. Every handler
// that reinits the driver or injects frames must refuse while this holds —
// tearing the driver down under the task kills the transfer mid-flash.
static bool canFwBusy() { return canFwState == CANFW_WAITBOOT || canFwState == CANFW_FLASHING; }
static volatile uint16_t canFwPage = 0;
static volatile uint16_t canFwPages = 0;
static String canFwMsg = "";
static String canFwPath = "";
// Look up parameter ID by name from cached JSON
// JSON format: {"name":{"id":12,"unit":"V",...},"name2":{...}}
static int canGetParamId(const String& name) {
if (!canParamCacheLoaded) return -1;
String search = "\"" + name + "\"";
int pos = canParamJson.indexOf(search);
if (pos < 0) return -1;
// Find "id" within this entry's object only — entries without an id
// (e.g. serial) must not pick up the next entry's id
int objStart = canParamJson.indexOf('{', pos + search.length());
if (objStart < 0) return -1;
int objEnd = canParamJson.indexOf('}', objStart); // entries are flat objects
int idPos = canParamJson.indexOf("\"id\"", objStart);
if (idPos < 0 || (objEnd > 0 && idPos > objEnd)) return -1;
idPos = canParamJson.indexOf(':', idPos) + 1;
while (idPos < canParamJson.length() && (canParamJson[idPos] == ' ' || canParamJson[idPos] == '\t')) idPos++;
return canParamJson.substring(idPos).toInt();
}
// Download parameter database from device via segmented SDO
static bool canDownloadParamCache() {
if (!canMode || !canDriverIsRunning()) return false;
DBG_OUTPUT_PORT.println("CAN: downloading parameter database...");
// Allocate buffer for JSON string (ZombieVerter-class param databases run >32KB)
const uint32_t bufSize = 49152;
uint8_t* buf = (uint8_t*)malloc(bufSize);
if (!buf) return false;
// A single lost segment truncates the transfer, so retry the whole download
// and only cache transfers that finished with the device's last-segment flag.
// (A retry after a truncated attempt may resume mid-transfer on the device
// side — the sanity check below rejects that and the next attempt is fresh.)
for (int attempt = 1; attempt <= 3; attempt++) {
memset(buf, 0, bufSize);
bool complete = false;
uint32_t bytesRead = canSdoReadSegmented(canNodeId, CAN_INDEX_JSON, buf, bufSize - 1, 100, &complete);
// Sanity check: a real param database is a non-trivial JSON object
uint32_t end = bytesRead;
while (end > 0 && (buf[end - 1] == 0 || isspace(buf[end - 1]))) end--;
bool looksValid = end > 64 && buf[0] == '{' && buf[end - 1] == '}';
if (bytesRead > 0 && complete && looksValid) {
buf[bytesRead] = 0;
canParamJson = String((char*)buf);
canParamCacheLoaded = true;
DBG_OUTPUT_PORT.printf("CAN: downloaded %u bytes of parameter data (attempt %d)\n", bytesRead, attempt);
free(buf);
return true;
}
DBG_OUTPUT_PORT.printf("CAN: parameter download incomplete (%u bytes, attempt %d)\n", bytesRead, attempt);
delay(50);
}
free(buf);
DBG_OUTPUT_PORT.println("CAN: parameter download failed");
return false;
}
// Build the full json response: walk the cached param database, read each
// entry's live value via SDO and splice it in, preserving all metadata
// (category, minimum, maximum, default, unit, isparam, ...) for the UI.
static float canReadParamValue(int paramId);
static String canBuildJsonWithValues() {
const int len = canParamJson.length();
String result;
result.reserve(len + 2048);
int i = canParamJson.indexOf('{');
if (i < 0) return "{\"can_cache\":true}";
result += '{';
i++;
bool firstEntry = true;
int failedReads = 0;
int successReads = 0;
bool skipReads = false; // set when the device looks offline — avoids 240 timeouts
while (i < len) {
// Next top-level key
int keyStart = canParamJson.indexOf('"', i);
if (keyStart < 0) break;
int keyEnd = canParamJson.indexOf('"', keyStart + 1);
if (keyEnd < 0) break;
String name = canParamJson.substring(keyStart + 1, keyEnd);
// Entry object bounds (track nesting and strings to find matching brace)
int objStart = canParamJson.indexOf('{', keyEnd);
if (objStart < 0) break;
int depth = 1, j = objStart + 1;
bool inStr = false;
while (j < len && depth > 0) {
char c = canParamJson[j];
if (inStr) {
if (c == '\\') j++;
else if (c == '"') inStr = false;
}
else if (c == '"') inStr = true;
else if (c == '{') depth++;
else if (c == '}') depth--;
j++;
}
if (depth != 0) break;
String entry = canParamJson.substring(objStart, j);
// Read live value over CAN and replace (or insert) the "value" field
int idPos = entry.indexOf("\"id\":");
if (idPos >= 0) {
int paramId = entry.substring(idPos + 5).toInt();
if (paramId > 0 && !skipReads) {
float val = canReadParamValue(paramId);
if (!isnan(val)) {
successReads++;
String valStr = String(val, 2);
int vPos = entry.indexOf("\"value\":");
if (vPos >= 0) {
int vStart = vPos + 8;
int vEnd = vStart;
while (vEnd < (int)entry.length() && entry[vEnd] != ',' && entry[vEnd] != '}') vEnd++;
entry = entry.substring(0, vStart) + valStr + entry.substring(vEnd);
} else {
entry = "{\"value\":" + valStr + "," + entry.substring(1);
}
} else {
failedReads++;
if (failedReads >= 8 && successReads == 0) skipReads = true;
}
}
}
if (!firstEntry) result += ',';
result += '"' + name + "\":" + entry;
firstEntry = false;
i = j;
}
// Virtual spot values (ESP-side CAN RX mappings)
for (int vi = 0; vi < virtCount; vi++) {
if (!firstEntry) result += ',';
result += "\"" + String(virtVals[vi].name) + "\":{\"unit\":\"" + String(virtVals[vi].unit) +
"\",\"isparam\":false,\"virtual\":true,\"value\":" +
(virtVals[vi].valid ? String(virtVals[vi].value, 2) : "0") + "}";
firstEntry = false;
}
// Only claim a live connection if the reads mostly succeeded — otherwise
// the UI would show stale cached values as if they were current
if (failedReads < 5) {
if (!firstEntry) result += ',';
result += "\"can_cache\":true}";
} else {
result += '}';
}
return result;
}
// Read a single parameter value via SDO (returns NaN on failure)
static float canReadParamValue(int paramId) {
if (!canMode || paramId < 0) return NAN;
uint16_t index = canParamIndex(paramId);
uint8_t subIndex = canParamSubIndex(paramId);
// Drain stale frames so a leftover response can't be mismatched to this read
twai_message_t resp;
while (canDriverReceive(&resp)) {}
if (!canSdoRead(canNodeId, index, subIndex)) return NAN;
if (!canReceiveForNode(canNodeId, &resp, 20)) return NAN;
uint16_t rIndex;
uint8_t rSubIndex;
int32_t raw;
if (!canSdoParseResponse(&resp, NULL, &rIndex, &rSubIndex, &raw)) return NAN;
if (rIndex != index || rSubIndex != subIndex) return NAN;
return canDecodeValue(raw);
}
#ifndef WEB_REPO
#define WEB_REPO ""
#endif
#ifndef WEB_OTA_TARGET
#define WEB_OTA_TARGET "esp32"
#endif
WebServer server(80);
HTTPUpdateServer updater;
//holds the current upload
File fsUploadFile;
Ticker sta_tick;
//SWD bit-banging, ported from https://github.com/scanlime/esp8266-arm-swd
#include <StreamString.h>
RTC_PCF8523 ext_rtc;
ESP32Time int_rtc;
bool haveRTC = false;
bool haveSDCard = false;
bool fastLoggingEnabled = true;
bool fastLoggingActive = false;
uint8_t SDIObuffer[SDIO_BUFFER_SIZE];
uint16_t indexSDIObuffer = 0;
uint16_t blockCountSD = 0;
File dataFile;
int startLogAttempt = 0;
uint32_t deleteOldest(uint64_t spaceRequired);
String formatBytes(uint64_t bytes);
bool createNextSDFile()
{
char filename[50];
uint32_t nextFileIndex = deleteOldest(RESERVED_SD_SPACE);
if(haveRTC)
nextFileIndex = 0; //have a date so restart index from 0 (still needed in case serial stream fails to start)
do
{
if(haveRTC)
snprintf(filename, 50, "/%d-%02d-%02d-%02d-%02d-%02d_%d.bin", int_rtc.getYear(), int_rtc.getMonth(), int_rtc.getDay(), int_rtc.getHour(), int_rtc.getMinute(), int_rtc.getSecond(), nextFileIndex++);
else
snprintf(filename, 50, "/%010d.bin", nextFileIndex++);
}
while(SD_MMC.exists(filename));
dataFile = SD_MMC.open(filename, FILE_WRITE);
if (dataFile)
{
dataFile.flush(); //make sure FAT updated for debugging purposes
DBG_OUTPUT_PORT.println("Created file: " + String(filename));
return true;
}
else
return false;
}
uint32_t deleteOldest(uint64_t spaceRequired)
{
time_t oldestTime = 0;
File root, file;
String oldestFileName;
uint64_t spaceRem;
time_t t;
uint32_t nextIndex = 0;
uint32_t fileCount = 0;
spaceRem = SD_MMC.totalBytes() - SD_MMC.usedBytes();
DBG_OUTPUT_PORT.println("Space Required = " + formatBytes(spaceRequired));
DBG_OUTPUT_PORT.println("Space Remaining = " + formatBytes(spaceRem));
do
{
root = SD_MMC.open("/");
oldestTime = 0;
fileCount = 0;
while(file = root.openNextFile())
{
if(haveRTC)
t = file.getLastWrite();
else
{
String fname = file.name();
fname.remove(0,1); //lose starting /
t = fname.toInt()+1; //make sure 0 special case isnt used
if(t > nextIndex)
nextIndex = t;
}
if(!file.isDirectory())
{
fileCount++;
if((oldestTime==0) || (t<oldestTime))
{
oldestTime = t;
oldestFileName = "/";
oldestFileName += file.name();
}
}
file.close();
}
root.close();
if((spaceRem < spaceRequired) || (fileCount >= MAX_SD_FILES))
{
if(oldestFileName.length() > 0)
{
if(SD_MMC.remove(oldestFileName))
DBG_OUTPUT_PORT.println("Deleted file: " + oldestFileName);
else
DBG_OUTPUT_PORT.println("Couldn't delete: " + oldestFileName);
}
else
{
DBG_OUTPUT_PORT.println("No files found, can't free space");
break;//no files so can do no more
}
}
spaceRem = SD_MMC.totalBytes() - SD_MMC.usedBytes();
} while((spaceRem < spaceRequired) || (fileCount >= MAX_SD_FILES));
return(nextIndex);
}
//format bytes
String formatBytes(uint64_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";
}
}
String getContentType(String filename){
if(server.hasArg("download")) return "application/octet-stream";
else if(filename.endsWith(".bin")) 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(".svg")) return "image/svg+xml";
else if(filename.endsWith(".json")) return "application/json";
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){
//DBG_OUTPUT_PORT.println("handleFileRead: " + path);
// Strip query string (e.g. /ui.js?v=2 -> /ui.js)
int qs = path.indexOf('?');
if (qs >= 0) path = path.substring(0, qs);
if(path.endsWith("/")) path += "index.html";
String contentType = getContentType(path);
// Decide cacheability from the requested path (before the .gz fallback):
// long-cache images/fonts, always revalidate code so UI updates take effect
bool longCache = path.endsWith(".png") || path.endsWith(".gif") ||
path.endsWith(".jpg") || path.endsWith(".ico") ||
path.endsWith(".woff2") || path.endsWith(".svg");
String pathWithGz = path + ".gz";
if(SPIFFS.exists(pathWithGz) || SPIFFS.exists(path)){
if(SPIFFS.exists(pathWithGz))
path += ".gz";
File file = SPIFFS.open(path, "r");
server.sendHeader("Cache-Control", longCache ? "public, max-age=86400" : "no-cache");
size_t sent = server.streamFile(file, contentType);
file.close();
return true;
}
//try download from the sdcard
if (haveSDCard) {
DBG_OUTPUT_PORT.print("handleFileRead Trying SD Card: ");
DBG_OUTPUT_PORT.println(path);
DBG_OUTPUT_PORT.print("SD_MMC.exists: ");
DBG_OUTPUT_PORT.println(SD_MMC.exists( path));
if (SD_MMC.exists(path)) {
File file = SD_MMC.open(path, "r");
size_t sent = server.streamFile(file, contentType);
file.close();
return true;
}
}
return false;
}
void handleFileUpload(){
if(server.uri() != "/edit") return;
HTTPUpload& upload = server.upload();
if(upload.status == UPLOAD_FILE_START){
String filename = upload.filename;
if(!filename.startsWith("/")) filename = "/"+filename;
//DBG_OUTPUT_PORT.print("handleFileUpload Name: "); DBG_OUTPUT_PORT.println(filename);
fsUploadFile = SPIFFS.open(filename, "w");
if (!fsUploadFile) {
DBG_OUTPUT_PORT.println("ERROR: SPIFFS open failed for " + filename + " - filesystem may be full or fragmented");
}
filename = String();
} else if(upload.status == UPLOAD_FILE_WRITE){
//DBG_OUTPUT_PORT.print("handleFileUpload Data: "); DBG_OUTPUT_PORT.println(upload.currentSize);
if(fsUploadFile)
fsUploadFile.write(upload.buf, upload.currentSize);
} else if(upload.status == UPLOAD_FILE_END){
if(fsUploadFile) {
fsUploadFile.close();
DBG_OUTPUT_PORT.println("Upload complete: " + upload.filename + " (" + String(upload.totalSize) + " bytes)");
} else {
DBG_OUTPUT_PORT.println("ERROR: Upload failed - file was not written (SPIFFS open failed)");
}
}
}
// Browser-driven OTA of the ESP32 itself: app firmware (U_FLASH) or the SPIFFS
// filesystem image (U_SPIFFS). The target is taken from the ?cmd=fs|app query
// arg, with the uploaded file name as a fallback. Streams straight into the
// Update partition; the POST responder reboots on success. The bootloader and
// partition table are never touched, so a bad image is recoverable over serial.
// Combined OTA image: a small header followed by the app firmware and the
// SPIFFS image, so the two are always flashed together and can never drift out
// of sync. Format: "OIWEBOTA" + uint32 LE firmware length + uint32 LE
// filesystem length, then firmware.bin, then spiffs.bin. The bootloader and
// partition table are never touched, so a bad image stays recoverable over USB.
static const char ESP_OTA_MAGIC[8] = {'O','I','W','E','B','O','T','A'};
static bool espOtaDone = false; // upload finished (whether or not it worked)
static bool espOtaOk = false; // both partitions flashed successfully
static String espOtaErr;
static uint8_t espOtaHdr[16];
static int espOtaHdrGot;
static uint32_t espOtaFwLen, espOtaFsLen, espOtaAppDone, espOtaFsDone;
static int espOtaPhase; // 0=header 1=app 2=fs 3=finished 4=error
// Background URL-download progress, polled by the UI via /espupdate-status
static volatile int espOtaDlState = 0; // 0 idle, 1 downloading/flashing, 2 success, 3 error
static volatile int espOtaDlPct = 0;
static String espOtaDlUrl;
static void espOtaReset(){
espOtaDone = false; espOtaOk = false; espOtaErr = "";
espOtaHdrGot = 0; espOtaPhase = 0;
espOtaFwLen = espOtaFsLen = espOtaAppDone = espOtaFsDone = 0;
}
static void espOtaFail(const String& msg){
if(espOtaErr.length() == 0) espOtaErr = msg;
espOtaPhase = 4;
Update.abort();
DBG_OUTPUT_PORT.println("ESP OTA error: " + espOtaErr);
}
// Stream the combined image through a small state machine: parse the header,
// flash the app partition, then the filesystem partition. A single upload
// buffer may straddle any boundary, so each phase consumes only its share.
static void espOtaFeed(const uint8_t* data, size_t len){
size_t i = 0;
while(i < len && espOtaPhase < 3){
if(espOtaPhase == 0){
while(espOtaHdrGot < 16 && i < len) espOtaHdr[espOtaHdrGot++] = data[i++];
if(espOtaHdrGot < 16) return;
if(memcmp(espOtaHdr, ESP_OTA_MAGIC, 8) != 0){ espOtaFail("Not a combined OTA image"); return; }
espOtaFwLen = espOtaHdr[8] | (espOtaHdr[9] << 8) | (espOtaHdr[10] << 16) | ((uint32_t)espOtaHdr[11] << 24);
espOtaFsLen = espOtaHdr[12] | (espOtaHdr[13] << 8) | (espOtaHdr[14] << 16) | ((uint32_t)espOtaHdr[15] << 24);
if(espOtaFwLen == 0 || espOtaFsLen == 0){ espOtaFail("Bad OTA header"); return; }
if(!Update.begin(espOtaFwLen, U_FLASH)){ espOtaFail(Update.errorString()); return; }
espOtaPhase = 1;
} else if(espOtaPhase == 1){
size_t want = espOtaFwLen - espOtaAppDone;
size_t n = want < (len - i) ? want : (len - i);
if(n && Update.write((uint8_t*)data + i, n) != n){ espOtaFail(Update.errorString()); return; }
espOtaAppDone += n; i += n;
if(espOtaAppDone == espOtaFwLen){
if(!Update.end(true)){ espOtaFail(Update.errorString()); return; }
if(!Update.begin(espOtaFsLen, U_SPIFFS)){ espOtaFail(Update.errorString()); return; }
espOtaPhase = 2;
}
} else { // espOtaPhase == 2
size_t want = espOtaFsLen - espOtaFsDone;
size_t n = want < (len - i) ? want : (len - i);
if(n && Update.write((uint8_t*)data + i, n) != n){ espOtaFail(Update.errorString()); return; }
espOtaFsDone += n; i += n;
if(espOtaFsDone == espOtaFsLen){
if(!Update.end(true)){ espOtaFail(Update.errorString()); return; }
espOtaPhase = 3;
}
}
}
}
static bool espOtaUploadRejected = false; // upload arrived while the URL-download task owned Update
void handleEspUpdateUpload(){
if(server.uri() != "/espupdate") return;
HTTPUpload& upload = server.upload();
if(upload.status == UPLOAD_FILE_START){
// A URL-download OTA task may be mid-flash: two writers on the same
// Update partition corrupt the image. Reject this upload entirely.
espOtaUploadRejected = (espOtaDlState == 1);
if(espOtaUploadRejected){
DBG_OUTPUT_PORT.println("ESP OTA upload rejected: URL update in progress");
return;
}
espOtaReset();
DBG_OUTPUT_PORT.println("ESP OTA start: " + upload.filename);
} else if(upload.status == UPLOAD_FILE_WRITE){
if(espOtaUploadRejected) return;
espOtaFeed(upload.buf, upload.currentSize);
} else if(upload.status == UPLOAD_FILE_END){
if(espOtaUploadRejected) return;
espOtaDone = true;
espOtaOk = (espOtaPhase == 3);
if(!espOtaOk && espOtaErr.length() == 0) espOtaErr = "Incomplete OTA image";
if(espOtaOk) DBG_OUTPUT_PORT.println("ESP OTA complete: app " + String(espOtaFwLen) + " + fs " + String(espOtaFsLen) + " bytes");
} else if(upload.status == UPLOAD_FILE_ABORTED){
espOtaDone = true; espOtaOk = false; espOtaErr = "Upload aborted";
Update.abort();
}
}
// Download a combined OTA image from a URL and flash it server-side. The ESP
// fetches it directly (the browser can't — GitHub release downloads have no CORS
// headers), following redirects, and streams the body through the same parser.
// Runs as a background task so the web server stays responsive and the UI can
// poll /espupdate-status for progress.
static void espOtaDownloadTask(void* param){
(void)param;
espOtaReset();
espOtaDlPct = 0; espOtaDlState = 1;
WiFiClientSecure client;
client.setInsecure(); // skip cert validation; the image is validated on flash
HTTPClient http;
http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS);
http.setTimeout(20000);
if(!http.begin(client, espOtaDlUrl)){
espOtaErr = "Could not start download"; espOtaDlState = 3; vTaskDelete(NULL); return;
}
int code = http.GET();
if(code != HTTP_CODE_OK){
http.end(); espOtaErr = String("Download HTTP ") + code; espOtaDlState = 3; vTaskDelete(NULL); return;
}
int total = http.getSize();
WiFiClient* stream = http.getStreamPtr();
uint8_t buf[1024];
uint32_t got = 0;
uint32_t idleMs = 0; // a live-but-silent peer must not stall the task forever
while(http.connected() && espOtaPhase < 3){
size_t avail = stream->available();
if(avail){
int n = stream->readBytes(buf, avail > sizeof(buf) ? sizeof(buf) : avail);
if(n > 0){ espOtaFeed(buf, n); got += n; if(total > 0) espOtaDlPct = (int)((uint64_t)got * 100 / (uint32_t)total); idleMs = 0; }
} else {
delay(1);
if(++idleMs > 30000){ espOtaErr = "Download stalled (no data for 30s)"; break; }
}
}
http.end();
espOtaDone = true;
espOtaOk = (espOtaPhase == 3);
if(espOtaOk){
espOtaDlPct = 100; espOtaDlState = 2;
DBG_OUTPUT_PORT.println("ESP OTA from URL complete, rebooting");
delay(1200); // let the UI poll catch the success before the link drops
ESP.restart();
} else {
if(espOtaErr.length() == 0) espOtaErr = "Incomplete download";
espOtaDlState = 3;
vTaskDelete(NULL);
}
}
void handleEspUpdateFromUrl(){
if(espOtaDlState == 1){ server.send(409, "application/json", "{\"ok\":false,\"message\":\"Update already in progress\"}"); return; }
String url = server.arg("url");
if(url.length() == 0){ server.send(400, "application/json", "{\"ok\":false,\"message\":\"Missing url\"}"); return; }
DBG_OUTPUT_PORT.println("ESP OTA from URL: " + url);
espOtaDlUrl = url;
espOtaErr = ""; espOtaDlPct = 0; espOtaDlState = 1;
if (xTaskCreate(espOtaDownloadTask, "espota_dl", 16384, NULL, 1, NULL) != pdPASS) {
// Roll the state back or every future attempt 409s until reboot
espOtaDlState = 3; espOtaErr = "Could not start download task (out of memory?)";
server.send(500, "application/json", "{\"ok\":false,\"message\":\"Could not start download task\"}");
return;
}
server.send(200, "application/json", "{\"ok\":true,\"started\":true}");
}
void handleFileDelete(){
if(server.args() == 0) return server.send(500, "text/plain", "BAD ARGS");
String path = server.arg(0);
//DBG_OUTPUT_PORT.println("handleFileDelete: " + path);
if(path == "/")
return server.send(500, "text/plain", "BAD PATH");
if(!SPIFFS.exists(path))
return server.send(404, "text/plain", "FileNotFound");
SPIFFS.remove(path);
server.send(200, "text/plain", "");
path = String();
}
void handleFileCreate(){
if(server.args() == 0)
return server.send(500, "text/plain", "BAD ARGS");
String path = server.arg(0);
//DBG_OUTPUT_PORT.println("handleFileCreate: " + path);
if(path == "/")
return server.send(500, "text/plain", "BAD PATH");
if(SPIFFS.exists(path))
return server.send(500, "text/plain", "FILE EXISTS");
File file = SPIFFS.open(path, "w");
if(file)
file.close();
else
return server.send(500, "text/plain", "CREATE FAILED");
server.send(200, "text/plain", "");
path = String();
}
void handleRTCNow() {
String output = "{ \"now\":\"";
if (haveRTC) {
DateTime t = ext_rtc.now();
output += t.timestamp();
} else {
output += "NO RTC";
}
output += "\"}";
server.send(200, "text/json", output);
}
void handleRTCSet() {
if (server.hasArg("timestamp")) {
// Reject garbage — toInt() on a non-number is 0, which would silently
// set both clocks to 1970
long ts = server.arg("timestamp").toInt();
if (ts < 1000000000) { server.send(400, "text/json", "{\"result\":\"invalid timestamp\"}"); return; }
DateTime now = DateTime((uint32_t)ts);
if (haveRTC) ext_rtc.adjust(now); // don't write to an absent I2C device
int_rtc.setTime(now.unixtime());
handleRTCNow(); // single response (a second send() desyncs keep-alive clients)
} else {
server.send(500, "text/json", "{\"result\":\"timestamp missing\"}");
}
}
void handleSdCardDeleteAll() {
if (haveSDCard) {
// Never unlink the log file while it's open for writing — FatFs allows
// it and subsequent writes then corrupt the allocation table
if (dataFile) { dataFile.close(); }
File root, file;
if (haveSDCard) {
root = SD_MMC.open("/");
while(file = root.openNextFile())
{
String filename = file.name();
if(SD_MMC.remove("/" + filename))
DBG_OUTPUT_PORT.println("Deleted file: " + filename);
else
DBG_OUTPUT_PORT.println("Couldn't delete: " + filename);
}
}
}
server.send(200, "text/json", "{\"result\": \"done\"}");
}
void handleSdCardList() {
if (!haveSDCard) {
server.send(200, "text/json", "{\"error\": \"No SD Card\"}");
return;
}
File root = SD_MMC.open("/");
if(!root){
server.send(200, "text/json", "{\"error\": \"Failed to open directory\"}");
return;
}
if(!root.isDirectory()){
server.send(200, "text/json", "{\"error\": \"Root is not a directory\"}");
return;
}
File sdFile = root.openNextFile();
String output = "[";
int count = 0;
while(sdFile && count < 200){
if (output != "[") output += ',';
output += "\"";
output += String(sdFile.name());
output += "\"";
sdFile = root.openNextFile();
count++;
}
output += "]";
server.send(200, "text/json", output);
return;
}
void handleFileList() {
String path = "/";
if(server.hasArg("dir"))
path = server.arg("dir");
//DBG_OUTPUT_PORT.println("handleFileList: " + path);
File root = SPIFFS.open(path);
String output = "[";
if(!root){
// Always answer — returning without a response leaves the client hanging
server.send(404, "text/plain", "DirNotFound");
return;
}
File file = root.openNextFile();
while(file){
if (output != "[") output += ',';
bool isDir = false;
output += "{\"type\":\"";
output += file.isDirectory()?"dir":"file";
output += "\",\"name\":\"";
output += String(file.name());
output += "\"}";
file = root.openNextFile();
}
output += "]";
server.send(200, "text/json", output);
}
// static void sendCommand(String cmd)
// {
// DBG_OUTPUT_PORT.println("Sending '" + cmd + "' to inverter");
// Inverter.print("\n");
// delay(1);
// while(Inverter.available())
// Inverter.read(); //flush all previous output
// Inverter.print(cmd);
// Inverter.print("\n");
// Inverter.readStringUntil('\n'); //consume echo
// }
void uart_readUntill(char val)
{
int retVal;
do
{
retVal = uart_read_bytes(INVERTER_PORT, uartMessBuff, 1, UART_TIMEOUT);
}
while((retVal>0) && (uartMessBuff[0] != val));
}
// Terminate any partial line sitting in the inverter's terminal buffer
// (garbage accumulates there whenever we talked at the wrong baud) and
// discard the inverter's response to it, so the next command's echo/reply
// framing starts clean.
static void uartResync()