-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJcorpNomadProject.ino
More file actions
executable file
·4763 lines (4123 loc) · 168 KB
/
JcorpNomadProject.ino
File metadata and controls
executable file
·4763 lines (4123 loc) · 168 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
// Jcorp Nomad Backend
//<!-- Version 3.3 -->
#include <Arduino.h>
#define FF_USE_FASTSEEK 1
#define SD_FREQ_KHZ 40000
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include "FS.h"
#define CONFIG_FATFS_EXFAT 1
#include <SD_MMC.h>
#ifndef SD
#define SD SD_MMC
#endif
#include <DNSServer.h>
#include "SD_Card.h"
#include <ArduinoJson.h>
#include <map>
#include "Display_ST7789.h"
#include "LVGL_Driver.h"
#include "ui.h"
#include "RGB_lamp.h"
#include <SPIFFS.h>
#include <Preferences.h>
#include "esp_wifi.h"
#if defined(ARDUINO_ARCH_ESP32)
#include "soc/soc.h"
#include "soc/rtc_cntl_reg.h"
#include "esp_system.h"
#endif
#include "usb_mode.h"
#include "boot_mode.h" // library for firmware switching
void handleRangeRequest(AsyncWebServerRequest *request);
void handleUpload(AsyncWebServerRequest *request, const String& filename, size_t index, uint8_t *data, size_t len, bool final);
String urlDecode(const String& str);
void enqueueIndexUpdateForPath(const String& path);
void RGB_SetMode(uint8_t mode);
void applyRGBSettings();
String sanitizeToken(const String &s);
bool saveSettings();
void launch_usb_mode() {
extern void usb_setup();
extern void usb_loop();
usb_setup();
for (;;) {
usb_loop();
}
}
#define BOOT_BUTTON_PIN 0
#include <vector>
#ifndef GLOBAL_INDEX_BUF
#define GLOBAL_INDEX_BUF 1024
#endif
enum { HALF_INDEX_BUF = GLOBAL_INDEX_BUF / 2 };
static char g_lineBuf[GLOBAL_INDEX_BUF];
static uint8_t g_fileBuf[4096]; // file reads/writes
static std::map<String, unsigned long> g_lastIndexSkipLog;
static inline void freeString(String &s) { s = String(); }
static inline void freeVectorString(std::vector<String> &v) { std::vector<String>().swap(v); }
static inline void freeVectorUInt32(std::vector<uint32_t> &v) { std::vector<uint32_t>().swap(v); }
static inline void closeFile(File &f) { if (f) f.close(); }
#ifndef INDEX_MIN_HEAP
#define INDEX_MIN_HEAP 20000UL
#endif
static inline bool enoughHeapForIndex(size_t estNeededBytes = 40000) {
size_t freeHeap = ESP.getFreeHeap();
if (freeHeap < (INDEX_MIN_HEAP + estNeededBytes)) {
Serial.printf("[Index] Not enough heap for index work (free=%u, need~%u). Deferring.\n",
(unsigned)freeHeap, (unsigned)estNeededBytes);
return false;
}
return true;
}
static size_t jsonEscapeToBuf(const String &in, char *dst, size_t dstLen) {
if (!dst || dstLen == 0) return 0;
size_t pos = 0;
for (size_t i = 0; i < in.length() && pos + 1 < dstLen; ++i) {
char c = in.charAt(i);
if (c == '\\' || c == '\"') {
if (pos + 2 >= dstLen) break;
dst[pos++] = '\\';
dst[pos++] = c;
} else if (c == '\n') {
if (pos + 2 >= dstLen) break;
dst[pos++] = '\\';
dst[pos++] = 'n';
} else if (c == '\r') {
if (pos + 2 >= dstLen) break;
dst[pos++] = '\\';
dst[pos++] = 'r';
} else {
dst[pos++] = c;
}
}
dst[pos] = '\0';
return pos;
}
static void writeIndexEntryToFile(File &fout, char t, const String &name, const String &path, uint64_t sz = 0, uint64_t mt = 0) {
char escName[HALF_INDEX_BUF];
char escPath[HALF_INDEX_BUF];
jsonEscapeToBuf(name, escName, HALF_INDEX_BUF);
jsonEscapeToBuf(path, escPath, HALF_INDEX_BUF);
int pos = snprintf(g_lineBuf, GLOBAL_INDEX_BUF,
"{\"t\":\"%c\",\"n\":\"%s\",\"p\":\"%s\"", t, escName, escPath);
if (pos < 0) pos = 0;
if (t == 'f') {
pos += snprintf(g_lineBuf + pos, (pos < (int)GLOBAL_INDEX_BUF) ? (GLOBAL_INDEX_BUF - pos) : 0,
",\"sz\":%llu,\"mt\":%llu}\n",
(unsigned long long)sz, (unsigned long long)mt);
} else {
pos += snprintf(g_lineBuf + pos, (pos < (int)GLOBAL_INDEX_BUF) ? (GLOBAL_INDEX_BUF - pos) : 0,
"}\n");
}
size_t wlen = strlen(g_lineBuf);
if (wlen) fout.write((const uint8_t*)g_lineBuf, wlen);
}
int screenBrightness = 100; // 0-100, default full brightness
void handleConnector(AsyncWebServerRequest *request);
unsigned long lastTempReading = 0;
float currentTempC = 0.0;
volatile bool mediaStreamingActive = false; // Flag to indicate active media streaming
static bool sdScanned = false;
const uint32_t SD_SCAN_DELAY = 5000; // milliseconds after boot
SemaphoreHandle_t sdMutex = NULL;
static uint64_t cachedTotalBytes = 0;
static uint64_t cachedUsedBytes = 0;
const char* SD_USAGE_FILE = "/.system-index/sd_usage.json";
static unsigned long lastScanTime = 0;
volatile bool sdbarDirty = false;
volatile int activeStreams = 0;
struct IndexBuildArgs {
String dir; // directory path to build index for (e.g. "/Music/Album")
String out; // output index filename
};
static QueueHandle_t indexQueue = nullptr;
// Task management for performance optimization
TaskHandle_t indexWorkerTaskHandle = nullptr;
TaskHandle_t storageMonitorTaskHandle = nullptr;
volatile bool shutdownBackgroundTasks = false;
volatile bool indexingTasksActive = false;
volatile bool firstTimeIndexBuild = false; // Track if this is initial index creation
// Function declarations for task management
void shutdownBackgroundTasksForStreaming();
void startBackgroundTasksIfNeeded();
void checkStreamingTimeout();
void immediateEnqueueTopLevelTask(void *param);
void triggerIndexingIfNeeded(const String& filePath);
// Last time UI bar was updated
unsigned long lastSdbarUpdate = 0;
void updateSDBAR() {
sdbarDirty = true;
}
void updateSDBAR_UI_ThreadOnly() {
if (cachedTotalBytes == 0) return;
int usage = (int)((cachedUsedBytes * 100) / cachedTotalBytes);
if (usage > 100) usage = 100;
if (usage < 0) usage = 0;
lv_bar_set_value(ui_sdbar, usage, LV_ANIM_OFF);
sdbarDirty = false;
}
#include <string> // used by std::map key
static std::map<std::string, unsigned long> lastIndexRequestMs;
const unsigned long INDEX_REQUEUE_COALESCE_MS = 2000UL; // 2 seconds coalescing
static bool shouldCoalesceIndexRequest(const String &path) {
std::string k(path.c_str());
unsigned long now = millis();
auto it = lastIndexRequestMs.find(k);
if (it != lastIndexRequestMs.end()) {
if (now - it->second < INDEX_REQUEUE_COALESCE_MS) {
return false;
}
}
lastIndexRequestMs[k] = now;
return true;
}
// Helper: get parent directory for a path ("/Music/song.mp3" -> "/Music")
static String parentDirFromPath(const String &path) {
if (path.length() == 0) return "/";
int last = path.lastIndexOf('/');
if (last <= 0) return "/"; // root or malformed -> treat as root
String p = path.substring(0, last);
if (p.length() == 0) return "/";
return p;
}
// START: SD_MMC compatibility alias
#include <SD_MMC.h>
#ifndef SD
#define SD SD_MMC
#endif
#define INDEXER_SLEEP_MS 300000 // 5 minutes between background scans
#define MAX_CLIENTS 4
String encodeIndexName(const String &path);
struct AdminSettings {
String rgbMode = "off";
String rgbColor = "#ff0000";
String adminPassword = "";
String wifiSSID = "Jcorp_Nomad";
String wifiPassword = "password";
int brightness = 230;
bool autoGenerateMedia = false;
};
AdminSettings settings;
const char* SETTINGS_PATH = "/config/settings.json";
// Web Console Logging System
#define MAX_LOG_ENTRIES 50
struct LogEntry {
String message;
String type;
unsigned long timestamp;
};
LogEntry webLogs[MAX_LOG_ENTRIES];
int logIndex = 0;
int logCount = 0;
// Function to add log entry for web console
void webLog(const String& message, const String& type = "info") {
webLogs[logIndex].message = message;
webLogs[logIndex].type = type;
webLogs[logIndex].timestamp = millis();
logIndex = (logIndex + 1) % MAX_LOG_ENTRIES;
if (logCount < MAX_LOG_ENTRIES) {
logCount++;
}
// Also send to serial for debugging
Serial.println(message);
}
// Function for formatted web logging
void webLogf(const String& type, const char* format, ...) {
char buffer[256];
va_list args;
va_start(args, format);
vsnprintf(buffer, sizeof(buffer), format, args);
va_end(args);
webLog(String(buffer), type);
}
#define SD_CLK_PIN 14
#define SD_CMD_PIN 15
#define SD_D0_PIN 16
#define SD_D1_PIN 18
#define SD_D2_PIN 17
#define SD_D3_PIN 21
const char *INDEX_DIR = "/.system-index"; // on-SD folder for index files
const size_t INDEX_WRITE_CHUNK = 4096; // flush buffer when larger than this
// Normalize path: ensure leading '/', remove trailing '/'
String normalizePath(const String &p_in){
if (p_in.length() == 0) return "/";
String p = p_in;
if (!p.startsWith("/")) p = "/" + p;
while (p.length() > 1 && p.endsWith("/")) p = p.substring(0, p.length()-1);
return p;
}
String encodeIndexName(const String &path_in) {
String p = path_in;
if (p.length() == 0) return String("root");
// normalize leading/trailing slashes
if (p.startsWith("/")) p = p.substring(1);
while (p.length() > 1 && p.endsWith("/")) p = p.substring(0, p.length()-1);
if (p.length() == 0) return String("root");
// split on slashes and sanitize each segment
std::vector<String> parts;
String cur;
for (size_t i = 0; i < p.length(); ++i) {
char c = p.charAt(i);
if (c == '/') {
if (cur.length()) parts.push_back(cur);
cur = "";
} else {
cur += c;
}
}
if (cur.length()) parts.push_back(cur);
// build encoded name joined by "__"
String out;
for (size_t i = 0; i < parts.size(); ++i) {
String tok = sanitizeToken(parts[i]);
if (tok.length() == 0) tok = "_";
if (i) out += "__";
out += tok;
}
if (out.length() == 0) out = "root";
return out;
}
// Sanitize a directory name into a filename token (keeps alnum, - and _, else underscore)
String sanitizeToken(const String &s){
String out;
out.reserve(s.length());
for (size_t i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) out += c;
else if (c == '-' || c == '_') out += c;
else out += '_';
}
return out;
}
// Minimal JSON escape used for NDJSON fields
String jsonEscape(const String &in){
String out;
out.reserve(in.length() + 8);
for (size_t i = 0; i < in.length(); ++i) {
char c = in.charAt(i);
if (c == '\\' || c == '\"') { out += '\\'; out += c; }
else if (c == '\n') out += "\\n";
else if (c == '\r') out += "\\r";
else out += c;
}
return out;
}
// Build NDJSON header line: {"_type":"dir","path":"/X","sig":"hex","count":N}
String buildIndexHeader(const String &path, const String &sigHex, uint32_t count){
String h;
h.reserve(128);
h += "{\"_type\":\"dir\",\"path\":\"";
h += jsonEscape(path);
h += "\",\"sig\":\"";
h += sigHex;
h += "\",\"count\":";
h += String(count);
h += "}\n";
return h;
}
// Append one NDJSON entry (t: 'f'|'d', n: filename, p: absolute path, optional sz/mt)
String buildIndexEntry(const char t, const String &name, const String &path, uint64_t sz=0, uint64_t mt=0){
String line;
line.reserve(160);
line += "{\"t\":\"";
line += t;
line += "\",\"n\":\"";
line += jsonEscape(name);
line += "\",\"p\":\"";
line += jsonEscape(path);
if (t == 'f') {
line += "\",\"sz\":";
line += String((unsigned long long)sz);
line += ",\"mt\":";
line += String((unsigned long long)mt);
line += "}\n";
} else {
line += "\"}\n";
}
return line;
}
#define MAX_NESTED_AUTOGEN_ITEMS 40
bool readIndexHeaderSig(const String &indexPath, String &outSig, uint32_t &outCount) {
outSig = "";
outCount = 0;
if (!SD_MMC.exists(indexPath)) return false;
File f = SD_MMC.open(indexPath, FILE_READ);
if (!f) return false;
String header = f.readStringUntil('\n');
f.close();
if (header.length() == 0) return false;
// Parse small JSON header
StaticJsonDocument<256> doc;
DeserializationError err = deserializeJson(doc, header);
if (err) return false;
const char* sig = doc["sig"];
if (sig) outSig = String(sig);
outCount = (uint32_t)(doc["count"] | doc["count"]); // header key is "count"
return true;
}
// ---------- Media file detector + safe recursive counter ----------
static bool isMediaFile(const String &lowerName) {
int dot = lowerName.lastIndexOf('.');
if (dot < 0) return false;
String ext = lowerName.substring(dot); // includes the dot, e.g. ".mp4"
// Video (playback generally reliable: mp4, mov, mkv, webm, m4v)
if (ext == ".mp4" || ext == ".mov" || ext == ".mkv" || ext == ".webm" || ext == ".m4v"
|| ext == ".ts" || ext == ".m2ts") return true;
// Audio (mp3/flac/wav plus common containers)
if (ext == ".mp3" || ext == ".flac" || ext == ".wav" || ext == ".aac" || ext == ".m4a"
|| ext == ".ogg" || ext == ".opus") return true;
// Images
if (ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".webp" || ext == ".avif"
|| ext == ".gif" || ext == ".bmp" || ext == ".tiff" || ext == ".tif" || ext == ".heic") return true;
// Books / Documents / Archives (PDF and EPUB primary; comic archives included, will support eventualy lol)
if (ext == ".pdf" || ext == ".epub" || ext == ".txt" || ext == ".html" || ext == ".htm"
|| ext == ".cbz" || ext == ".cbr" || ext == ".azw3" || ext == ".mobi") return true;
// Other video containers we count (wont work, dont use these dummy): .avi, .flv, .rmvb
if (ext == ".avi" || ext == ".flv" || ext == ".rmvb") return true;
return false;
}
unsigned int countMediaFiles(const String &dirPath) {
unsigned int count = 0;
File d = SD_MMC.open(dirPath);
if (!d || !d.isDirectory()) {
if (d) d.close();
return 0;
}
d.rewindDirectory();
File e;
while ((e = d.openNextFile())) {
if (e.isDirectory()) {
// e.name() returns the full path; recurse on it
String sub = String(e.name());
count += countMediaFiles(sub);
} else {
// Lower-case filename once for efficient extension checks
String name = String(e.name());
name.toLowerCase();
if (isMediaFile(name)) {
++count;
}
}
e.close();
yield(); // keep watchdog happy during recursion/long scans
}
d.close();
return count;
}
// compatibility wrapper, some callers expect countDirItems()
unsigned int countDirItems(const String &p) {
return countMediaFiles(p);
}
// Ensure INDEX_DIR exists (creates it if missing.. usualy)
void ensureIndexDir(){
if (!SD_MMC.exists(INDEX_DIR)) {
if (!SD_MMC.mkdir(INDEX_DIR)) {
Serial.printf("[Index] Failed to create index dir %s\n", INDEX_DIR);
} else {
Serial.printf("[Index] Created index dir %s\n", INDEX_DIR);
}
}
}
// FNV-1a 64-bit hash incremental update (used to compute signature)
uint64_t fnv1a64_update(uint64_t h, const String &s){
const uint64_t FNV_PRIME = 0x100000001b3ULL;
uint64_t hash = h;
for (size_t i = 0; i < s.length(); ++i) {
hash ^= (uint8_t)s[i];
hash *= FNV_PRIME;
}
return hash;
}
// Rename or copy fallback: try rename first, if that fails try copy & remove.
bool renameOrCopy(const String &src, const String &dst) {
if (SD_MMC.exists(dst)) SD_MMC.remove(dst);
if (SD_MMC.rename(src, dst)) return true;
File fsrc = SD_MMC.open(src, FILE_READ);
if (!fsrc) return false;
File fdst = SD_MMC.open(dst, FILE_WRITE);
if (!fdst) { fsrc.close(); return false; }
uint8_t buf[512];
while (fsrc.available()) {
size_t r = fsrc.read(buf, sizeof(buf));
if (r > 0) fdst.write(buf, r);
}
fsrc.close();
fdst.close();
SD_MMC.remove(src);
return true;
}
// Atomic write helper - writes tmp then moves to final (uses renameOrCopy)
bool atomicWriteFile(const String &tmpPath, const String &finalPath) {
// final renameOrCopy already does the heavy lifting; here just ensure final exists
return renameOrCopy(tmpPath, finalPath);
}
void dumpSDRoot() {
Serial.println("[Index] dumpSDRoot(): listing /");
File r = SD_MMC.open("/");
if (!r) {
Serial.println("[Index] dumpSDRoot(): FAILED to open root '/'");
return;
}
r.rewindDirectory();
while (true) {
File e = r.openNextFile();
if (!e) break;
Serial.printf("[Index] root-entry: %s %s\n", e.name(), e.isDirectory() ? "(dir)" : "(file)");
}
r.close();
}
bool writeNDIndexForDir(const String &dirPath, const String &outFilename) {
// ensure index folder exists
if (!SD_MMC.exists(INDEX_DIR)) SD_MMC.mkdir(INDEX_DIR);
if (!enoughHeapForIndex()) {
Serial.printf("[Index] Skipping index for '%s' due to low memory (free=%u)\n",
dirPath.c_str(), (unsigned)ESP.getFreeHeap());
return false;
}
// Normalize target dir
String normPath = dirPath;
if (!normPath.startsWith("/")) normPath = "/" + normPath;
normPath = normalizePath(normPath);
Serial.printf("[Index] Building index for '%s'\n", normPath.c_str());
webLogf("indexing_progress", "Starting indexing for '%s'", normPath.c_str());
if (!SD_MMC.exists(normPath)) {
Serial.printf("[Index] Path does not exist: %s\n", normPath.c_str());
return false;
}
// Open once to verify directory
File root = SD_MMC.open(normPath);
if (!root || !root.isDirectory()) {
if (root) root.close();
Serial.printf("[Index] Not a directory: %s\n", normPath.c_str());
return false;
}
root.close();
// Determine recursion strategy based on path
bool isRoot = (normPath == "/");
bool isShows = (normPath == "/Shows");
bool isMusic = (normPath == "/Music");
bool isShowSubfolder = normPath.startsWith("/Shows/") && normPath.indexOf('/', 7) < 0; // e.g. /Shows/MyShow
bool isShowSeasonFolder = normPath.startsWith("/Shows/") && normPath.indexOf('/', 7) > 0; // e.g. /Shows/MyShow/Season1
bool isMusicSubfolder = normPath.startsWith("/Music/"); // any depth under /Music
int maxDepth = 10; // Default to fully recursive for all media directories.
if (isRoot) {
maxDepth = 0; // Root should only list top-level buckets.
}
Serial.printf("[Index] Recursion depth for '%s': %d\n", normPath.c_str(), maxDepth);
// Prepass: compute signature and total count
uint64_t sig = 0xcbf29ce484222325ULL;
unsigned long count = 0;
// Helper: should we skip indexing this folder?
auto shouldSkipFolder = [](const String &path) -> bool {
if (path.startsWith("/.system-index")) return true;
if (path.startsWith("/.")) return true; // skip all hidden folders
if (path.startsWith("/System Volume Information")) return true;
if (path.startsWith("/Archive")) return true; // skip large ZIM archives
if (path.startsWith("/$")) return true;
return false;
};
std::function<void(const String&, int)> prepass = [&](const String &path, int depth) {
// Stop recursion if we've hit max depth
if (depth > maxDepth) return;
// Skip system/hidden folders
if (shouldSkipFolder(path)) {
Serial.printf("[Index] Skipping folder: %s\n", path.c_str());
return;
}
File d = SD_MMC.open(path);
if (!d || !d.isDirectory()) { if (d) d.close(); return; }
d.rewindDirectory();
int itemCount = 0;
while (true) {
File e = d.openNextFile();
if (!e) break;
String full = String(e.name());
// Normalize full path for consistency
if (!full.startsWith("/")) full = normalizePath(path + "/" + full);
else full = normalizePath(full);
int ls = full.lastIndexOf('/');
String tail = (ls >= 0) ? full.substring(ls + 1) : full;
// Skip hidden files/folders
if (tail.startsWith(".")) {
e.close();
continue;
}
if (e.isDirectory()) {
sig = fnv1a64_update(sig, full + "|" + tail);
++count;
e.close();
// Recurse with depth tracking
prepass(full, depth + 1);
} else {
uint64_t fsz = (uint64_t)e.size();
uint64_t fmt = 0;
sig = fnv1a64_update(sig, full + "|" + String(fsz) + "|" + String(fmt));
++count;
e.close();
}
// Yield more frequently to prevent WDT and keep device responsive
if (++itemCount % 5 == 0) {
yield();
vTaskDelay(pdMS_TO_TICKS(2)); // Give other tasks time (FreeRTOS-friendly)
}
}
d.close();
};
prepass(normPath, 0); // Start at depth 0
// Prepare files
String tmpPath = String(INDEX_DIR) + "/" + outFilename + ".tmp";
String finalPath = String(INDEX_DIR) + "/" + outFilename;
File fout = SD_MMC.open(tmpPath, FILE_WRITE);
if (!fout) {
Serial.printf("[Index] FAILED to open tmp for write: %s\n", tmpPath.c_str());
return false;
}
// Write header line
char sigHex[17];
snprintf(sigHex, sizeof(sigHex), "%016llx", (unsigned long long)sig);
String header = buildIndexHeader(normPath, String(sigHex), count);
fout.write((const uint8_t*)header.c_str(), header.length());
// Second pass: write entries with same depth control
std::function<void(const String&, int)> writepass = [&](const String &path, int depth) {
// Stop recursion if we've hit max depth
if (depth > maxDepth) return;
// Skip system/hidden folders
if (shouldSkipFolder(path)) return;
File d = SD_MMC.open(path);
if (!d || !d.isDirectory()) { if (d) d.close(); return; }
d.rewindDirectory();
int itemCount = 0;
while (true) {
File e = d.openNextFile();
if (!e) break;
String full = String(e.name());
if (!full.startsWith("/")) full = normalizePath(path + "/" + full);
else full = normalizePath(full);
int ls = full.lastIndexOf('/');
String tail = (ls >= 0) ? full.substring(ls + 1) : full;
// Skip hidden files/folders
if (tail.startsWith(".")) {
e.close();
continue;
}
char entryType = e.isDirectory() ? 'd' : 'f';
// Emit NDJSON one line per entry
char escName[HALF_INDEX_BUF];
char escPath[HALF_INDEX_BUF];
jsonEscapeToBuf(tail, escName, HALF_INDEX_BUF);
jsonEscapeToBuf(full, escPath, HALF_INDEX_BUF);
if (entryType == 'f') {
uint64_t fsz = (uint64_t)e.size();
uint64_t fmt = 0;
int pos = snprintf(g_lineBuf, GLOBAL_INDEX_BUF,
"{\"t\":\"f\",\"n\":\"%s\",\"p\":\"%s\",\"sz\":%llu,\"mt\":%llu}\n",
escName, escPath, (unsigned long long)fsz, (unsigned long long)fmt);
if (pos < 0) pos = 0;
size_t wlen = strlen(g_lineBuf);
if (wlen) fout.write((const uint8_t*)g_lineBuf, wlen);
} else {
int pos = snprintf(g_lineBuf, GLOBAL_INDEX_BUF,
"{\"t\":\"d\",\"n\":\"%s\",\"p\":\"%s\"}\n", escName, escPath);
if (pos < 0) pos = 0;
size_t wlen = strlen(g_lineBuf);
if (wlen) fout.write((const uint8_t*)g_lineBuf, wlen);
}
// Recurse into subdirectory
if (entryType == 'd') {
e.close();
writepass(full, depth + 1);
} else {
e.close();
}
// Yield more frequently
if (++itemCount % 10 == 0) {
yield();
delay(1);
}
}
d.close();
};
writepass(normPath, 0); // Start at depth 0
fout.flush();
fout.close();
String newFinal = finalPath + ".new";
if (SD_MMC.exists(newFinal)) SD_MMC.remove(newFinal);
bool moved = SD_MMC.rename(tmpPath, newFinal);
if (!moved) {
File fsrc = SD_MMC.open(tmpPath, FILE_READ);
if (fsrc) {
File fdst = SD_MMC.open(newFinal, FILE_WRITE);
if (fdst) {
uint8_t buf[512];
while (fsrc.available()) {
size_t r = fsrc.read(buf, sizeof(buf));
if (r > 0) fdst.write(buf, r);
}
fsrc.close();
fdst.close();
SD_MMC.remove(tmpPath);
moved = true;
} else {
fsrc.close();
}
}
}
if (!moved) {
Serial.printf("[Index] FAILED staging -> %s from tmp %s\n", newFinal.c_str(), tmpPath.c_str());
SD_MMC.remove(tmpPath);
return false;
}
if (SD_MMC.exists(finalPath)) SD_MMC.remove(finalPath);
if (!SD_MMC.rename(newFinal, finalPath)) {
if (!renameOrCopy(newFinal, finalPath)) {
Serial.printf("[Index] FAILED atomic replace %s -> %s\n", newFinal.c_str(), finalPath.c_str());
SD_MMC.remove(newFinal);
webLogf("error", "Failed atomic replace %s -> %s", newFinal.c_str(), finalPath.c_str());
return false;
} else {
SD_MMC.remove(newFinal);
}
}
Serial.printf("[Index] Built index %s for %s (count=%lu, sig=%s, maxDepth=%d)\n",
outFilename.c_str(), normPath.c_str(), count, sigHex, maxDepth);
webLogf("completed_index_logging", "Completed indexing '%s' - %lu items processed", normPath.c_str(), count);
String metaFilename = outFilename;
if (metaFilename.endsWith(".ndjson")) {
metaFilename = metaFilename.substring(0, metaFilename.length() - 7); // remove ".ndjson"
}
metaFilename += ".meta";
String metaPath = String(INDEX_DIR) + "/" + metaFilename;
File metaFile = SD_MMC.open(metaPath, FILE_WRITE);
if (metaFile) {
// Write JSON meta with path, count, and signature
metaFile.print("{\"path\":\"");
metaFile.print(jsonEscape(normPath));
metaFile.print("\",\"count\":");
metaFile.print(count);
metaFile.print(",\"sig\":\"");
metaFile.print(sigHex);
metaFile.println("\"}");
metaFile.close();
Serial.printf("[Index] Wrote meta file %s\n", metaFilename.c_str());
} else {
Serial.printf("[Index] WARNING: Failed to write meta file %s\n", metaFilename.c_str());
}
return true;
}
// ---------------- write bucket-level index ----------------
// write top-level bucket index (e.g. /Music -> Music.index.ndjson)
bool writeBucketIndex(const String &bucketPath) {
String name = bucketPath;
if (name.startsWith("/")) name = name.substring(1);
int slash = name.indexOf('/');
if (slash >= 0) name = name.substring(0, slash);
if (!name.length()) name = "root";
String outFile = String(name) + ".index.ndjson";
return writeNDIndexForDir(bucketPath, outFile);
}
// Build bucket index convenience wrapper (returns true on success)
bool buildBucketIndex(const String &bucketPath) {
String bucket = bucketPath;
if (bucket.startsWith("/")) bucket = bucket.substring(1);
if (bucket.endsWith("/")) bucket = bucket.substring(0, bucket.length()-1);
if (bucket.length() == 0) bucket = "root";
String outFilename = bucket + ".index.ndjson";
bool ok = writeNDIndexForDir(bucketPath, outFilename);
if (ok) {
Serial.printf("[Index] Built bucket index %s for %s\n", outFilename.c_str(), bucketPath.c_str());
webLogf("completed_index_logging", "Completed indexing bucket '%s' - wrote %s", bucketPath.c_str(), outFilename.c_str());
return true;
}
Serial.printf("[Index] Failed building bucket index for %s\n", bucketPath.c_str());
return false;
}
String urlencode(String str) {
String encoded = "";
char c;
char code0, code1;
char code[] = "0123456789ABCDEF";
for (int i = 0; i < str.length(); i++) {
c = str.charAt(i);
if (isalnum(c)) {
encoded += c;
} else {
code0 = code[(c >> 4) & 0xF];
code1 = code[c & 0xF];
encoded += '%';
encoded += code0;
encoded += code1;
}
}
return encoded;
}
// Settings Setup:
bool loadSettings() {
if (!SD_MMC.exists(SETTINGS_PATH)) {
Serial.println("Settings file not found. Generating default.");
return saveSettings(); // Save defaults
}
File file = SD_MMC.open(SETTINGS_PATH);
if (!file || file.isDirectory()) {
Serial.println("Failed to open settings file.");
return false;
}
StaticJsonDocument<512> doc;
DeserializationError error = deserializeJson(doc, file);
file.close();
if (error) {
Serial.println("Failed to parse settings JSON.");
return false;
}
settings.rgbMode = doc["rgbMode"] | "off";
settings.rgbColor = doc["rgbColor"] | "#ff0000";
settings.adminPassword = doc["adminPassword"] | "";
settings.wifiSSID = doc["wifiSSID"] | "Jcorp_Nomad";
settings.wifiPassword = doc["wifiPassword"] | "password";
settings.brightness = doc["brightness"] | 230;
settings.autoGenerateMedia = doc["autoGenerateMedia"] | false;
return true;
}
bool saveSettings() {
SD_MMC.mkdir("/config"); // Ensure directory exists
File file = SD_MMC.open(SETTINGS_PATH, FILE_WRITE);
if (!file) {
Serial.println("Failed to open settings file for writing.");
return false;
}
StaticJsonDocument<512> doc;
doc["rgbMode"] = settings.rgbMode;
doc["rgbColor"] = settings.rgbColor;
doc["adminPassword"] = settings.adminPassword;
doc["wifiSSID"] = settings.wifiSSID;
doc["wifiPassword"] = settings.wifiPassword;
doc["brightness"] = settings.brightness;
doc["autoGenerateMedia"] = settings.autoGenerateMedia;
bool success = serializeJson(doc, file) > 0;
file.close();
return success;
}
// --------------- Media Generation Stuff ------------
bool isAlwaysGenerateEnabled() {
return SD_MMC.exists("/always_generate.flag");
}
void enableAlwaysGenerate() {
File f = SD_MMC.open("/always_generate.flag", FILE_WRITE);
if (f) {
f.print("1");
f.close();
}
}
void disableAlwaysGenerate() {
SD_MMC.remove("/always_generate.flag");
}
bool isOneTimeGenerateRequested() {
return SD_MMC.exists("/generate_once.flag");
}
void requestOneTimeGenerate() {
File f = SD_MMC.open("/generate_once.flag", FILE_WRITE);
if (f) {
f.print("1");
f.close();
}
}
void clearOneTimeGenerate() {
SD_MMC.remove("/generate_once.flag");
}
//------------------- delete recursive -------------
bool deleteRecursive(String path) {
File entry = SD_MMC.open(path);
if (!entry) return false;
if (!entry.isDirectory()) {
entry.close();
return SD_MMC.remove(path);
}
File child;
while ((child = entry.openNextFile())) {
String childPath = String(path) + "/" + child.name();
deleteRecursive(childPath);
child.close();
}
entry.close();
return SD_MMC.rmdir(path);
}
// ───────────────── SD‑recovery globals ───────────────
volatile bool sdErrorFlag = false;
unsigned long sdErrorCooldownUntil = 0;
bool tryRecoverSDCard() {
Serial.println("[SD] Attempting recovery…");
SD_MMC.end(); // unmount
delay(1000); // give hardware a breather
if (!SD_MMC.begin("/sdcard", true, false, SD_FREQ_KHZ, 12)) {
Serial.println("[SD] Recovery failed.");
return false;
}
Serial.println("[SD] Recovery OK.");
return true;
}
String rfc3339Now() {
return "2025-07-12T12:00:00Z"; // Hard-coded UTC timestamp, or it gets mad
}
// Captive portal DNS setup
const byte DNS_PORT = 53;
DNSServer dnsServer;
AsyncWebServer server(80); // Web server on port 80
std::map<AsyncWebServerRequest*, File> activeUploads;
int connectedClients = 0;
// LED Mode and Color Helper Wrappers
uint8_t currentLEDMode = 0; // 0=off, 1=rainbow, 2=solid color
uint8_t solidR = 0, solidG = 0, solidB = 0;
void RGB_SetColor(uint8_t r, uint8_t g, uint8_t b) {
solidR = r;
solidG = g;
solidB = b;
currentLEDMode = 2;
Set_Color(g, r, b);
}
extern lv_obj_t *ui_wifi;
extern lv_obj_t *ui_SDcard;