// ===================== Libraries ===================== #include #include #include #include #include #include // Arduino-ESP32 3.x WebServer uses the unified Network API. // These buffer definitions MUST be before WebServer.h. #ifndef HTTP_UPLOAD_BUFLEN #define HTTP_UPLOAD_BUFLEN 8192 #endif #ifndef HTTP_DOWNLOAD_UNIT_SIZE #define HTTP_DOWNLOAD_UNIT_SIZE 8192 #endif #include #include #include #include // ===================== Shared SPI Bus (W5500 + TFT only) ===================== // ESP32-S3 general-purpose SPI pins. Keep GPIO26-37 free on N16R8. #define SPI_SCK 12 #define SPI_MISO 13 #define SPI_MOSI 11 // ===================== Dedicated SD SPI Bus (isolated, HSPI) ===================== // SD card gets its own SPI peripheral so it can never contend with // the W5500 on the shared bus above. Only 3 wires move; SD_CS stays put. #define SD_SPI_SCK 16 #define SD_SPI_MISO 17 #define SD_SPI_MOSI 18 SPIClass sdSPI(HSPI); // ===================== W5500 ===================== #define ETH_CS 10 #define ETH_IRQ 9 #define ETH_RST 8 #define ETH_TYPE ETH_PHY_W5500 #define ETH_ADDR 1 // ===================== SD Card ===================== #define SD_CS 4 // unchanged — only the bus it rides on changed // ===================== ILI9341 TFT ===================== #define TFT_CS 7 #define TFT_DC 6 #define TFT_RST 5 // 2.4" ILI9341, landscape Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST); // ===================== Other Hardware ===================== #define LED_GREEN 1 #define LED_BLUE 2 #define LED_RED 3 #define RESET_SWITCH 14 #define BUZZER_PIN 15 // ===================== Network ===================== WebServer server(80); // ===================== Security / Multi-user ===================== // Up to 8 independent users can stay logged in at the same time. // The first boot seeds the default administrator below. #define ADMIN_USER "admin" #define ADMIN_PASS "MT@Admin2026!" #define MAX_USERS 8 #define MAX_SESSIONS 8 const uint32_t AUTH_TTL_MS = 12UL * 60UL * 60UL * 1000UL; struct PortalUser { String username; String password; String role; }; struct PortalSession { String token; String username; uint32_t issuedAt; bool used; }; PortalSession sessions[MAX_SESSIONS]; String currentSessionUser = ""; // ===================== Resumable Upload ===================== File chunkUploadFile; String chunkFinalPath = ""; String chunkPartPath = ""; uint64_t chunkOffset = 0; uint64_t chunkTotal = 0; uint64_t chunkWritten = 0; bool chunkFailed = false; String chunkError = ""; // AP config portal #define AP_SSID "ESP32-FileHub-Setup" #define AP_PASSWORD "" // open AP for easy setup; set a password if you prefer #define DNS_PORT 53 DNSServer dnsServer; Preferences preferences; const char *AUTH_HEADERS[] = {"Cookie"}; enum NetworkMode { NET_NONE, NET_ETHERNET, NET_WIFI }; NetworkMode currentNetworkMode = NET_NONE; bool ethPresent = false; bool wifiPresent = false; bool sdPresent = false; uint8_t ethMac[6] = {0x02, 0x45, 0x53, 0x33, 0x53, 0x01}; uint32_t lastWifiRetry = 0; // ===================== Upload State ===================== File uploadFile; volatile bool uploading = false; volatile uint64_t uploadProgress = 0; volatile uint64_t uploadTotal = 0; String currentUploadFile = ""; uint32_t transferStartMs = 0; uint32_t lastTransferUpdateMs = 0; uint64_t lastTransferBytes = 0; float transferSpeedKBs = 0.0f; float transferSpeedMBs = 0.0f; uint32_t lastStatusUpdate = 0; uint32_t lastSDCheck = 0; // ===================== TFT UI ===================== enum ScreenMode { SCREEN_BOOT, SCREEN_STATUS, SCREEN_UPLOAD, SCREEN_MESSAGE }; ScreenMode screenMode = SCREEN_BOOT; String messageTitle = ""; String messageLine1 = ""; String messageLine2 = ""; uint16_t bgColor = ILI9341_BLACK; uint16_t panelColor = ILI9341_DARKGREY; uint16_t accentColor = ILI9341_CYAN; uint16_t goodColor = ILI9341_GREEN; uint16_t warningColor = ILI9341_YELLOW; uint16_t dangerColor = ILI9341_RED; uint16_t textColor = ILI9341_WHITE; // ===================== Forward Declarations ===================== void updateStatusScreen(); void showMessage(const String &title, const String &line1, const String &line2); void showBootScreen(const String &line1, const String &line2); void checkManualReset(); // ===================== Network Event ===================== bool userExists(const String &username, int *slotOut = nullptr) { preferences.begin("users", true); int count = preferences.getInt("count", 0); bool found = false; int foundSlot = -1; for (int i = 0; i < count && i < MAX_USERS; i++) { if (preferences.getString((String("u") + i + "n").c_str(), "") == username) { found = true; foundSlot = i; break; } } preferences.end(); if (slotOut) *slotOut = foundSlot; return found; } bool validateUser(const String &username, const String &password, String &roleOut) { preferences.begin("users", true); int count = preferences.getInt("count", 0); bool ok = false; roleOut = ""; for (int i = 0; i < count && i < MAX_USERS; i++) { String n = preferences.getString((String("u") + i + "n").c_str(), ""); if (n == username) { String p = preferences.getString((String("u") + i + "p").c_str(), ""); if (p == password) { roleOut = preferences.getString((String("u") + i + "r").c_str(), "admin"); ok = true; } break; } } preferences.end(); return ok; } bool addPortalUser(const String &username, const String &password, const String &role) { if (username.length() < 2 || username.length() > 24 || password.length() < 6) return false; if (role != "admin" && role != "user") return false; if (userExists(username)) return false; preferences.begin("users", false); int count = preferences.getInt("count", 0); if (count >= MAX_USERS) { preferences.end(); return false; } preferences.putString((String("u") + count + "n").c_str(), username); preferences.putString((String("u") + count + "p").c_str(), password); preferences.putString((String("u") + count + "r").c_str(), role); preferences.putInt("count", count + 1); preferences.end(); return true; } bool removePortalUser(const String &username) { // Keep the built-in administrator as a recovery account. if (username == ADMIN_USER) return false; preferences.begin("users", false); int count = preferences.getInt("count", 0); int slot = -1; for (int i = 0; i < count && i < MAX_USERS; i++) { if (preferences.getString((String("u") + i + "n").c_str(), "") == username) { slot = i; break; } } if (slot < 0 || count <= 1) { preferences.end(); return false; } for (int i = slot; i < count - 1; i++) { preferences.putString((String("u") + i + "n").c_str(), preferences.getString((String("u") + (i+1) + "n").c_str(), "")); preferences.putString((String("u") + i + "p").c_str(), preferences.getString((String("u") + (i+1) + "p").c_str(), "")); preferences.putString((String("u") + i + "r").c_str(), preferences.getString((String("u") + (i+1) + "r").c_str(), "user")); } int last = count - 1; preferences.remove((String("u") + last + "n").c_str()); preferences.remove((String("u") + last + "p").c_str()); preferences.remove((String("u") + last + "r").c_str()); preferences.putInt("count", count - 1); preferences.end(); // Invalidate sessions belonging to the removed user. for (int i = 0; i < MAX_SESSIONS; i++) if (sessions[i].used && sessions[i].username == username) sessions[i].used = false; return true; } bool updatePortalPassword(const String &username, const String &oldPass, const String &newPass) { if (newPass.length() < 6) return false; preferences.begin("users", false); int count = preferences.getInt("count", 0); bool changed = false; for (int i = 0; i < count && i < MAX_USERS; i++) { String base = "u" + String(i); if (preferences.getString((base + "n").c_str(), "") == username && preferences.getString((base + "p").c_str(), "") == oldPass) { preferences.putString((base + "p").c_str(), newPass); changed = true; break; } } preferences.end(); return changed; } void ensureDefaultAdmin() { preferences.begin("users", false); int count = preferences.getInt("count", 0); preferences.end(); if (count == 0) { addPortalUser(ADMIN_USER, ADMIN_PASS, "admin"); Serial.println("[AUTH] Default admin created: " ADMIN_USER); } } String makeToken() { uint32_t a = esp_random(), b = esp_random(), c = esp_random(), d = esp_random(); char buf[40]; snprintf(buf, sizeof(buf), "%08lx%08lx%08lx%08lx", (unsigned long)a, (unsigned long)b, (unsigned long)c, (unsigned long)d); return String(buf); } int findSessionByRequest() { if (!server.hasHeader("Cookie")) return -1; String cookie = server.header("Cookie"); int p = cookie.indexOf("MTSESSION="); if (p < 0) return -1; p += 10; int e = cookie.indexOf(';', p); String token = (e < 0) ? cookie.substring(p) : cookie.substring(p, e); token.trim(); for (int i = 0; i < MAX_SESSIONS; i++) { if (!sessions[i].used || sessions[i].token != token) continue; if (millis() - sessions[i].issuedAt > AUTH_TTL_MS) { sessions[i].used = false; return -1; } currentSessionUser = sessions[i].username; return i; } return -1; } bool hasValidSession() { currentSessionUser = ""; return findSessionByRequest() >= 0; } bool requireAuth() { if (hasValidSession()) return true; server.sendHeader("Location", "/login", true); server.send(302, "text/plain", "Login required"); return false; } String currentUserRole() { if (!hasValidSession()) return ""; String role; String dummy; // Read the role without checking the password. preferences.begin("users", true); int count = preferences.getInt("count", 0); for (int i = 0; i < count && i < MAX_USERS; i++) { String base = "u" + String(i); if (preferences.getString((base + "n").c_str(), "") == currentSessionUser) { role = preferences.getString((base + "r").c_str(), "user"); break; } } preferences.end(); return role; } bool requireAdmin() { if (!requireAuth()) return false; if (currentUserRole() == "admin") return true; server.send(403, "application/json", "{\"error\":\"Administrator permission required\"}"); return false; } void sendLoginPage(const String &error = "") { String html = R"HTML(Micro Tronic Server — Login
MICRO TRONIC SERVER

Portal Sign In

Secure multi-user local server access
)HTML"; if(error.length()) html += "
" + error + "
"; html += R"HTML(
ESP32-S3 • W5500 • SD Server
)HTML"; server.send(200,"text/html; charset=utf-8",html); } bool cleanFileName(String &filename) { filename.replace("\\", "/"); while (filename.startsWith("/")) filename.remove(0,1); if (!filename.length() || filename.indexOf("..") >= 0) return false; if (filename == "" || filename.charAt(0) == '.') return false; return true; } void onNetworkEvent(arduino_event_id_t event, arduino_event_info_t info) { (void)info; switch (event) { case ARDUINO_EVENT_ETH_START: Serial.println("[ETH] Started"); ETH.setHostname("MicroTronic-Server"); break; case ARDUINO_EVENT_ETH_CONNECTED: Serial.println("[ETH] Link connected"); break; case ARDUINO_EVENT_ETH_GOT_IP: ethPresent = true; currentNetworkMode = NET_ETHERNET; Serial.println("[ETH] IP: " + ETH.localIP().toString()); break; case ARDUINO_EVENT_ETH_LOST_IP: case ARDUINO_EVENT_ETH_DISCONNECTED: case ARDUINO_EVENT_ETH_STOP: ethPresent = false; if (wifiPresent) currentNetworkMode = NET_WIFI; else currentNetworkMode = NET_NONE; Serial.println("[ETH] Link/IP lost"); break; case ARDUINO_EVENT_WIFI_STA_START: Serial.println("[WIFI] STA started"); break; case ARDUINO_EVENT_WIFI_STA_GOT_IP: wifiPresent = true; if (!ethPresent) currentNetworkMode = NET_WIFI; Serial.println("[WIFI] IP: " + WiFi.localIP().toString()); break; case ARDUINO_EVENT_WIFI_STA_DISCONNECTED: wifiPresent = false; if (ethPresent) currentNetworkMode = NET_ETHERNET; else currentNetworkMode = NET_NONE; Serial.println("[WIFI] Disconnected"); break; default: break; } } // ===================== Helpers ===================== String formatBytes(uint64_t bytes) { if (bytes >= 1024ULL * 1024ULL * 1024ULL) return String((double)bytes / (1024.0 * 1024.0 * 1024.0), 2) + " GB"; if (bytes >= 1024ULL * 1024ULL) return String((double)bytes / (1024.0 * 1024.0), 2) + " MB"; if (bytes >= 1024ULL) return String((double)bytes / 1024.0, 1) + " KB"; return String((unsigned long)bytes) + " B"; } String formatSpeed(float mbps) { if (mbps >= 1.0f) return String(mbps, 2) + " MB/s"; return String(mbps * 1024.0f, 0) + " KB/s"; } // Returns the IP of whichever network is currently active. String getActiveIP() { if (currentNetworkMode == NET_ETHERNET && ethPresent) return ETH.localIP().toString(); if (currentNetworkMode == NET_WIFI && wifiPresent) return WiFi.localIP().toString(); return "No Network"; } // True if either Ethernet or WiFi is currently up. bool networkIsUp() { if (currentNetworkMode == NET_ETHERNET) return ethPresent; if (currentNetworkMode == NET_WIFI) return wifiPresent; return false; } String activeNetworkLabel() { if (currentNetworkMode == NET_ETHERNET) return "ETHERNET"; if (currentNetworkMode == NET_WIFI) return "WIFI"; return "NO NET"; } uint64_t computeSDUsedBytes() { uint64_t total = 0; if (!sdPresent) return 0; File root = SD.open("/"); if (!root) return 0; File file = root.openNextFile(); while (file) { if (!file.isDirectory()) total += file.size(); file = root.openNextFile(); } root.close(); return total; } bool checkSDPresent() { File root = SD.open("/"); if (!root) return false; root.close(); return true; } String getContentType(String filename) { filename.toLowerCase(); if (filename.endsWith(".htm") || filename.endsWith(".html")) return "text/html"; if (filename.endsWith(".css")) return "text/css"; if (filename.endsWith(".js")) return "application/javascript"; if (filename.endsWith(".json")) return "application/json"; if (filename.endsWith(".txt")) return "text/plain"; if (filename.endsWith(".csv")) return "text/csv"; if (filename.endsWith(".xml")) return "application/xml"; if (filename.endsWith(".pdf")) return "application/pdf"; if (filename.endsWith(".zip")) return "application/zip"; if (filename.endsWith(".rar")) return "application/vnd.rar"; if (filename.endsWith(".7z")) return "application/x-7z-compressed"; if (filename.endsWith(".mp4")) return "video/mp4"; if (filename.endsWith(".mkv")) return "video/x-matroska"; if (filename.endsWith(".mp3")) return "audio/mpeg"; if (filename.endsWith(".wav")) return "audio/wav"; if (filename.endsWith(".png")) return "image/png"; if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")) return "image/jpeg"; if (filename.endsWith(".gif")) return "image/gif"; if (filename.endsWith(".webp")) return "image/webp"; return "application/octet-stream"; } bool isProtectedFile(String name) { if (!name.startsWith("/")) name = "/" + name; return name == "/index.html" || name == "/about.html" || name == "/files.html" || name == "/system.html" || name == "/settings.html" || name == "/logs.html" || name == "/style.css" || name == "/script.js" || name == "/app.js" || name.endsWith(".part"); } // ===================== TFT UI Helpers ===================== void drawHeader(const String &title, uint16_t color = ILI9341_CYAN) { tft.fillRect(0, 0, 320, 34, color); tft.setTextColor(ILI9341_BLACK); tft.setTextSize(2); tft.setCursor(10, 9); tft.print(title); } // ---- Network icons (drawn on the header strip, top-right corner) ---- // All icons are drawn in black to match the header text color, and are // masked/cleared against the header background color where needed. void drawWifiIcon(int cx, int cy, uint16_t color, uint16_t maskColor) { // Classic "signal fan" wifi icon: a dot plus growing arcs above it. tft.fillCircle(cx, cy, 2, color); for (int r = 6; r <= 12; r += 3) { tft.drawCircle(cx, cy, r, color); } // Mask out the bottom half of the circles so only the upward arcs show. tft.fillRect(cx - 14, cy, 28, 14, maskColor); } void drawEthernetIcon(int cx, int cy, uint16_t color) { // Simple RJ45 "connector" glyph: body + two prongs + short cable stub. tft.fillRect(cx - 6, cy - 10, 12, 8, color); tft.fillRect(cx - 4, cy - 14, 2, 4, color); tft.fillRect(cx + 2, cy - 14, 2, 4, color); tft.drawLine(cx, cy - 2, cx, cy + 3, color); tft.drawLine(cx - 3, cy + 3, cx + 3, cy + 3, color); } void drawNoNetIcon(int cx, int cy, uint16_t color) { // Circle with a diagonal slash through it. tft.drawCircle(cx, cy, 8, color); tft.drawLine(cx - 6, cy - 6, cx + 6, cy + 6, color); } // Draws the current-network icon in the top-right corner of the header. // headerColor must match whatever drawHeader() was called with, so the // wifi-icon mask blends in seamlessly. void drawNetworkStatusIcon(uint16_t headerColor = ILI9341_CYAN) { int cx = 300; int cy = 18; if (currentNetworkMode == NET_ETHERNET && ethPresent) { drawEthernetIcon(cx, cy, ILI9341_BLACK); } else if (currentNetworkMode == NET_WIFI && wifiPresent) { drawWifiIcon(cx, cy, ILI9341_BLACK, headerColor); } else { drawNoNetIcon(cx, cy, ILI9341_BLACK); } } void drawStatusPill(int x, int y, int w, const String &label, bool ok) { tft.fillRoundRect(x, y, w, 25, 6, ok ? goodColor : dangerColor); tft.setTextColor(ILI9341_BLACK); tft.setTextSize(1); tft.setCursor(x + 8, y + 8); tft.print(label); } void drawCentered(const String &text, int y, uint16_t color, uint8_t size) { tft.setTextSize(size); tft.setTextColor(color); int16_t x1, y1; uint16_t w, h; tft.getTextBounds(text, 0, y, &x1, &y1, &w, &h); int x = (320 - w) / 2; if (x < 0) x = 0; tft.setCursor(x, y); tft.print(text); } void showBootScreen(const String &line1, const String &line2 = "") { screenMode = SCREEN_BOOT; tft.fillScreen(bgColor); drawHeader("ESP32-S3 FILE HUB", accentColor); drawNetworkStatusIcon(accentColor); drawCentered("HIGH SPEED FILE SERVER", 62, textColor, 2); drawCentered(line1, 105, accentColor, 2); if (line2.length()) drawCentered(line2, 140, textColor, 1); tft.drawRoundRect(20, 180, 280, 35, 8, panelColor); tft.setTextSize(1); tft.setTextColor(ILI9341_LIGHTGREY); tft.setCursor(20, 193); tft.print("W5500 / WiFi | SD (dual-SPI) | ILI9341 | N16R8"); } void showMessage(const String &title, const String &line1 = "", const String &line2 = "") { screenMode = SCREEN_MESSAGE; messageTitle = title; messageLine1 = line1; messageLine2 = line2; tft.fillScreen(bgColor); drawHeader(title, accentColor); drawNetworkStatusIcon(accentColor); if (line1.length()) drawCentered(line1, 75, textColor, 2); if (line2.length()) drawCentered(line2, 115, ILI9341_LIGHTGREY, 1); } // ---------- Extra TFT icons / animation ---------- void drawSDIcon(int x, int y, uint16_t color) { tft.drawRoundRect(x, y, 24, 30, 3, color); tft.drawLine(x+5,y+7,x+19,y+7,color); tft.drawLine(x+5,y+13,x+19,y+13,color); tft.drawLine(x+5,y+19,x+19,y+19,color); tft.fillCircle(x+18,y+26,2,color); } void drawServerIcon(int x, int y, uint16_t color) { tft.drawRoundRect(x,y,34,24,4,color); tft.fillCircle(x+8,y+8,2,color); tft.fillCircle(x+8,y+16,2,color); tft.drawLine(x+14,y+8,x+28,y+8,color); tft.drawLine(x+14,y+16,x+28,y+16,color); } void drawPulseDot(int x, int y, uint16_t color, uint8_t phase) { uint8_t r = 3 + ((phase / 8) % 3); tft.fillCircle(x,y,r,color); } void drawStatusCard(int x, int y, int w, int h, const String &title, const String &value, uint16_t accent, bool ok) { tft.fillRoundRect(x,y,w,h,9,panelColor); tft.drawRoundRect(x,y,w,h,9,0x39C7); tft.setTextColor(ILI9341_LIGHTGREY); tft.setTextSize(1); tft.setCursor(x+10,y+8); tft.print(title); tft.setTextColor(ok ? accent : dangerColor); tft.setTextSize(2); tft.setCursor(x+10,y+25); tft.print(value); } void showBootScreen(const String &line1, const String &line2 = "") { screenMode = SCREEN_BOOT; tft.fillScreen(bgColor); drawHeader("ESP32-S3 FILE HUB", accentColor); drawNetworkStatusIcon(accentColor); // Centered server emblem tft.drawRoundRect(128,48,64,48,10,panelColor); tft.drawRoundRect(135,55,50,12,5,accentColor); tft.drawRoundRect(135,72,50,12,5,accentColor); tft.fillCircle(143,61,2,accentColor); tft.fillCircle(143,78,2,accentColor); drawCentered("HIGH SPEED FILE SERVER", 108, textColor, 2); drawCentered(line1, 139, accentColor, 2); if (line2.length()) drawCentered(line2, 166, ILI9341_LIGHTGREY, 1); // Animated loading track. The loop animates this area while boot is active. tft.drawRoundRect(30,195,260,16,6,panelColor); tft.fillRoundRect(34,199,20,8,4,accentColor); tft.setTextSize(1); tft.setTextColor(ILI9341_LIGHTGREY); tft.setCursor(30,222); tft.print("W5500 + WiFi | SD | ILI9341 | N16R8"); } void showMessage(const String &title, const String &line1 = "", const String &line2 = "") { screenMode = SCREEN_MESSAGE; messageTitle = title; messageLine1 = line1; messageLine2 = line2; tft.fillScreen(bgColor); drawHeader(title, accentColor); drawNetworkStatusIcon(accentColor); // Simple status emblem bool bad = title.indexOf("FAIL") >= 0 || title.indexOf("ERROR") >= 0 || title.indexOf("REMOVED") >= 0; uint16_t c = bad ? dangerColor : goodColor; tft.drawCircle(160,76,24,c); if (bad) { tft.drawLine(151,67,169,85,c); tft.drawLine(169,67,151,85,c); } else { tft.drawLine(149,77,157,85,c); tft.drawLine(157,85,172,67,c); } if (line1.length()) drawCentered(line1, 116, textColor, 2); if (line2.length()) drawCentered(line2, 148, ILI9341_LIGHTGREY, 1); } void updateStatusScreen() { if (uploading) return; screenMode = SCREEN_STATUS; tft.fillScreen(bgColor); drawHeader("SYSTEM DASHBOARD", accentColor); drawNetworkStatusIcon(accentColor); // Top status chips drawStatusPill(10,42,94,activeNetworkLabel(),networkIsUp()); drawStatusPill(113,42,94,"SD "+String(sdPresent?"READY":"OFF"),sdPresent); drawStatusPill(216,42,94,"SERVER",true); // Main information cards drawStatusCard(10,78,145,64,"NETWORK",getActiveIP(),accentColor,networkIsUp()); drawStatusCard(165,78,145,64,"STORAGE",formatBytes(computeSDUsedBytes()),goodColor,sdPresent); // Mini icons and metrics drawSDIcon(18,154,sdPresent ? goodColor : dangerColor); tft.setTextColor(ILI9341_LIGHTGREY); tft.setTextSize(1); tft.setCursor(50,157); tft.print("SD CARD"); tft.setTextColor(textColor); tft.setTextSize(1); tft.setCursor(50,171); tft.print(sdPresent ? "Dedicated SPI bus" : "Not detected"); drawServerIcon(177,156,goodColor); tft.setTextColor(ILI9341_LIGHTGREY); tft.setTextSize(1); tft.setCursor(218,157); tft.print("SERVER"); tft.setTextColor(textColor); tft.setCursor(218,171); tft.print("HTTP :80"); // Uptime / network details footer tft.setTextColor(ILI9341_LIGHTGREY); tft.setTextSize(1); tft.setCursor(12,201); tft.print("UPTIME "); tft.setTextColor(textColor); tft.print(String(millis()/60000UL) + " min"); tft.setTextColor(ILI9341_LIGHTGREY); tft.setCursor(155,201); tft.print("HEAP "); tft.setTextColor(textColor); tft.print(formatBytes(ESP.getFreeHeap())); tft.setTextColor(ILI9341_LIGHTGREY); tft.setCursor(12,220); if (currentNetworkMode == NET_ETHERNET) { tft.print("W5500 100 Mbps • Ethernet priority"); } else if (currentNetworkMode == NET_WIFI) { String ssid=WiFi.SSID(); if(ssid.length()>22) ssid=ssid.substring(0,22)+"..."; tft.print("WiFi • "+ssid); } else { tft.setTextColor(dangerColor); tft.print("NO NETWORK • Hold RESET to reconfigure"); } } void animateTFT() { static uint32_t lastAnim=0; static uint8_t phase=0; uint32_t now=millis(); if(now-lastAnim<120) return; lastAnim=now; phase++; if(screenMode==SCREEN_STATUS && !uploading) { // Refresh only the small live indicator, avoiding a full-screen redraw. uint16_t c = networkIsUp() ? goodColor : dangerColor; tft.fillRect(286,7,22,22,accentColor); if(currentNetworkMode==NET_WIFI && wifiPresent) drawWifiIcon(298,18,ILI9341_BLACK,accentColor); else if(currentNetworkMode==NET_ETHERNET && ethPresent) drawEthernetIcon(298,18,ILI9341_BLACK); else drawNoNetIcon(298,18,ILI9341_BLACK); drawPulseDot(304,47,c,phase); } if(screenMode==SCREEN_BOOT) { int x=34 + ((phase*8)%248); tft.fillRoundRect(34,199,252,8,4,bgColor); tft.fillRoundRect(x,199,34,8,4,accentColor); } } void updateUploadScreen(bool force = false) { if (!uploading && !force) return; screenMode = SCREEN_UPLOAD; uint64_t total = uploadTotal; uint64_t done = uploadProgress; int percent = 0; if (total > 0) percent = (int)((done * 100ULL) / total); if (percent > 100) percent = 100; tft.fillScreen(bgColor); drawHeader("FILE TRANSFER", accentColor); drawNetworkStatusIcon(accentColor); tft.setTextColor(textColor); tft.setTextSize(1); tft.setCursor(12, 48); tft.print("FILE"); String filename = currentUploadFile; if (filename.length() > 38) filename = filename.substring(0, 35) + "..."; tft.setTextSize(2); tft.setCursor(12, 63); tft.print(filename); tft.setTextSize(1); tft.setTextColor(ILI9341_LIGHTGREY); tft.setCursor(12, 95); tft.print(formatBytes(done)); tft.print(" / "); tft.print(formatBytes(total)); tft.setCursor(220, 95); tft.print(formatSpeed(transferSpeedMBs)); // Progress bar int barX = 12; int barY = 116; int barW = 296; int barH = 30; tft.drawRoundRect(barX, barY, barW, barH, 8, panelColor); int fillW = (barW - 4) * percent / 100; if (fillW > 0) tft.fillRoundRect(barX + 2, barY + 2, fillW, barH - 4, 6, goodColor); drawCentered(String(percent) + "%", 123, ILI9341_BLACK, 2); tft.setTextColor(textColor); tft.setTextSize(1); tft.setCursor(12, 169); tft.print("TRANSFER SPEED"); tft.setTextSize(2); tft.setCursor(12, 183); tft.print(formatSpeed(transferSpeedMBs)); tft.setTextSize(1); tft.setCursor(190, 169); tft.print("NETWORK"); tft.setTextSize(2); tft.setCursor(190, 183); tft.print(currentNetworkMode == NET_ETHERNET ? "W5500" : "WiFi"); tft.setTextSize(1); tft.setTextColor(ILI9341_LIGHTGREY); tft.setCursor(12, 220); tft.print("HTTP upload buffer: 8 KB"); } void updateTransferSpeed() { uint32_t now = millis(); if (now - lastTransferUpdateMs < 250) return; uint32_t dt = now - lastTransferUpdateMs; uint64_t bytesNow = uploadProgress; if (dt > 0 && bytesNow >= lastTransferBytes) { uint64_t delta = bytesNow - lastTransferBytes; transferSpeedKBs = ((float)delta / 1024.0f) / ((float)dt / 1000.0f); transferSpeedMBs = transferSpeedKBs / 1024.0f; } lastTransferBytes = bytesNow; lastTransferUpdateMs = now; updateUploadScreen(); } // ===================== HTTP ===================== void serveStaticFile(String path) { if (!hasValidSession()) { requireAuth(); return; } if (!sdPresent) { server.send(503,"text/plain","SD card unavailable"); return; } if (!path.length()) path="/index.html"; if (path.charAt(0)!='/') path="/"+path; if (isProtectedFile(path) == false && path != "/index.html" && path != "/about.html" && path != "/files.html" && path != "/system.html" && path != "/settings.html" && path != "/logs.html" && path != "/style.css" && path != "/script.js" && path != "/app.js") { server.send(404,"text/plain","Not found"); return; } File file=SD.open(path,FILE_READ); if(!file){server.send(404,"text/plain","File not found");return;} server.sendHeader("Cache-Control","no-store"); server.streamFile(file,getContentType(path)); file.close(); } void handleList() { if(!requireAuth()) return; if(!sdPresent){server.send(503,"application/json","[]");return;} File root=SD.open("/"); if(!root){server.send(200,"application/json","[]");return;} String json="["; bool first=true; File file=root.openNextFile(); while(file){ if(!file.isDirectory()){ String name=String(file.name()); if(!isProtectedFile(name)){ if(!first) json+=","; name.replace("\\","\\\\"); name.replace("\"","\\\""); json += "{\"name\":\""+name+"\",\"size\":"+String((unsigned long long)file.size())+",\"protected\":false}"; first=false; } } file=root.openNextFile(); } root.close(); json+="]"; server.send(200,"application/json",json); } void doDeleteFile() { if(!requireAuth()) return; if(!server.hasArg("name")){server.send(400,"text/plain","Missing file name");return;} String filename=server.arg("name"); if(!cleanFileName(filename)){server.send(400,"text/plain","Invalid filename");return;} String full="/"+filename; if(isProtectedFile(full)){server.send(403,"text/plain","Protected file");return;} if(!SD.exists(full)){server.send(404,"text/plain","Not found");return;} if(SD.remove(full)){server.send(200,"application/json","{\"ok\":true}");} else server.send(500,"application/json","{\"ok\":false,\"error\":\"Delete failed\"}"); } void handleDownload() { if(!requireAuth()) return; if(!server.hasArg("name")){server.send(400,"text/plain","Missing file name");return;} String filename=server.arg("name"); if(!cleanFileName(filename)){server.send(400,"text/plain","Invalid filename");return;} filename="/"+filename; if(isProtectedFile(filename) || !SD.exists(filename)){server.send(404,"text/plain","Not found");return;} File file=SD.open(filename,FILE_READ); if(!file){server.send(404,"text/plain","Open failed");return;} String ct=getContentType(filename); String dn=filename.substring(filename.lastIndexOf('/')+1); bool view=server.hasArg("view") && server.arg("view")=="1"; server.sendHeader("Cache-Control","no-store"); if(view) server.sendHeader("Content-Disposition","inline; filename=\""+dn+"\""); else server.sendHeader("Content-Disposition","attachment; filename=\""+dn+"\""); server.streamFile(file,ct); file.close(); } void handleStatus() { if(!requireAuth()) return; uint64_t used=computeSDUsedBytes(); String net=(currentNetworkMode==NET_ETHERNET)?"ethernet":(currentNetworkMode==NET_WIFI?"wifi":"none"); String ip=getActiveIP(); String json="{"; json += "\"network\":\""+net+"\",\"ethernet\":"+(ethPresent?String("true"):String("false"))+",\"wifi\":"+(wifiPresent?String("true"):String("false")); json += ",\"ip\":\""+ip+"\",\"link_speed\":\""+(currentNetworkMode==NET_ETHERNET?String("100Mbps"):String("WiFi"))+"\""; json += ",\"sd_present\":"+(sdPresent?String("true"):String("false"))+",\"sd_used_bytes\":"+String((unsigned long long)used); uint64_t sdTotal = sdPresent ? SD.cardSize() : 0; uint64_t sdFree = sdTotal > used ? sdTotal-used : 0; json += ",\"sd_total_bytes\":"+String((unsigned long long)sdTotal)+",\"sd_free_bytes\":"+String((unsigned long long)sdFree)+",\"heap\":"+String(ESP.getFreeHeap())+",\"psram\":"+String(ESP.getFreePsram()); json += ",\"uptime_sec\":"+String(millis()/1000UL)+",\"free_heap\":"+String(ESP.getFreeHeap())+",\"free_psram\":"+String(ESP.getFreePsram()); json += ",\"uploading\":"+(uploading?String("true"):String("false"))+",\"upload_bytes\":"+String((unsigned long long)uploadProgress)+",\"upload_total\":"+String((unsigned long long)uploadTotal)+",\"speed_mbps\":"+String(transferSpeedMBs,2)+"}"; server.send(200,"application/json",json); } // ===================== Resumable chunk upload ===================== void handleChunkUpload() { if(!hasValidSession()) return; HTTPUpload &u=server.upload(); if(u.status==UPLOAD_FILE_START){ chunkFailed=false; chunkError=""; chunkWritten=0; if(!server.hasArg("offset") || !server.hasArg("total")){chunkFailed=true;chunkError="offset/total missing";return;} chunkOffset=strtoull(server.arg("offset").c_str(),nullptr,10); chunkTotal=strtoull(server.arg("total").c_str(),nullptr,10); String name=server.hasArg("name")?server.arg("name"):u.filename; if(!cleanFileName(name)){chunkFailed=true;chunkError="invalid filename";return;} chunkFinalPath="/"+name; chunkPartPath=chunkFinalPath+".part"; if(isProtectedFile(chunkFinalPath)){chunkFailed=true;chunkError="protected filename";return;} if(chunkOffset==0){ if(SD.exists(chunkPartPath)) SD.remove(chunkPartPath); } if(!SD.exists(chunkPartPath) && chunkOffset!=0){chunkFailed=true;chunkError="resume part missing";return;} chunkUploadFile=SD.open(chunkPartPath,FILE_APPEND); if(!chunkUploadFile){chunkFailed=true;chunkError="cannot open part";return;} uint64_t existing=chunkUploadFile.size(); if(existing!=chunkOffset){chunkUploadFile.close();chunkFailed=true;chunkError="offset mismatch: server="+String((unsigned long long)existing);return;} currentUploadFile=name; uploadProgress=chunkOffset; uploadTotal=chunkTotal; uploading=true; digitalWrite(LED_BLUE,HIGH); } else if(u.status==UPLOAD_FILE_WRITE){ if(chunkFailed || !chunkUploadFile)return; size_t w=chunkUploadFile.write(u.buf,u.currentSize); chunkWritten+=w; uploadProgress+=w; if(w!=u.currentSize){chunkFailed=true;chunkError="SD write failed";} } else if(u.status==UPLOAD_FILE_END){ if(chunkUploadFile) chunkUploadFile.close(); if(chunkFailed){uploading=false;digitalWrite(LED_BLUE,LOW);return;} uint64_t endPos=chunkOffset+chunkWritten; if(endPos>chunkTotal){chunkFailed=true;chunkError="chunk exceeds total";uploading=false;digitalWrite(LED_BLUE,LOW);return;} if(endPos==chunkTotal){ if(SD.exists(chunkFinalPath)) SD.remove(chunkFinalPath); if(!SD.rename(chunkPartPath,chunkFinalPath)){chunkFailed=true;chunkError="rename failed";} else {uploadProgress=chunkTotal;uploading=false;digitalWrite(LED_BLUE,LOW);} } else {uploading=false;digitalWrite(LED_BLUE,LOW);} } else if(u.status==UPLOAD_FILE_ABORTED){if(chunkUploadFile)chunkUploadFile.close();uploading=false;digitalWrite(LED_BLUE,LOW);} } void handleChunkUploadResult(){ if(!requireAuth())return; if(chunkFailed){server.send(409,"application/json","{\"ok\":false,\"error\":\""+chunkError+"\"}");return;} bool complete=(chunkTotal>0 && uploadProgress==chunkTotal && !SD.exists(chunkPartPath)); String json="{\"ok\":true,\"next_offset\":"+String((unsigned long long)uploadProgress)+",\"total\":"+String((unsigned long long)chunkTotal)+",\"complete\":"+(complete?String("true"):String("false"))+"}"; server.send(200,"application/json",json); } // ===================== Ethernet ===================== bool startEthernet() { Serial.println("[ETH] Initializing W5500..."); /* * W5500 is an SPI Ethernet controller. * Arduino-ESP32 3.x provides ETH_PHY_W5500 through ETH.h. * * Runs on the shared SPI bus together with the TFT only — * SD card no longer shares this bus (see sdSPI below). */ bool ok = ETH.begin( ETH_TYPE, ETH_ADDR, ETH_CS, ETH_IRQ, ETH_RST, SPI, 40 // W5500 max rated SPI clock is ~33MHz; keep at/under this ); if (!ok) { Serial.println("[ETH] begin() failed"); return false; } uint32_t start = millis(); // Shorter timeout here than before — if there's no cable/link, we want // to fall back to WiFi quickly rather than block boot for a long time. while (!ETH.hasIP() && millis() - start < 6000UL) { delay(100); yield(); } if (ETH.hasIP()) { ethPresent = true; Serial.println("[ETH] Connected"); Serial.print("[ETH] IP: "); Serial.println(ETH.localIP()); return true; } Serial.println("[ETH] DHCP/IP timeout - no cable or no DHCP"); return false; } // ===================== WiFi Backup ===================== // Minimal captive-style config page. const char CONFIG_PAGE[] PROGMEM = R"HTML( ESP32 File Hub - WiFi Setup

ESP32 File Hub

Ethernet not found. Enter your WiFi details so the file hub can connect as a backup network.

)HTML"; // Loads saved credentials from NVS and tries to connect to them. // Returns true on success (currentNetworkMode/wifiPresent are set). bool connectSavedWifi() { preferences.begin("wifi", true); String ssid = preferences.getString("ssid", ""); String pass = preferences.getString("pass", ""); preferences.end(); if (ssid.length() == 0) { Serial.println("[WIFI] No saved credentials"); return false; } Serial.println("[WIFI] Connecting to saved network: " + ssid); showBootScreen("Connecting WiFi...", ssid); WiFi.mode(WIFI_STA); WiFi.begin(ssid.c_str(), pass.c_str()); uint32_t start = millis(); while (WiFi.status() != WL_CONNECTED && millis() - start < 15000UL) { delay(200); checkManualReset(); yield(); } if (WiFi.status() == WL_CONNECTED) { wifiPresent = true; currentNetworkMode = NET_WIFI; Serial.println("[WIFI] Connected, IP: " + WiFi.localIP().toString()); return true; } Serial.println("[WIFI] Connection failed/timeout"); WiFi.disconnect(true, true); return false; } // Starts the AP + captive config portal and BLOCKS here until the user // submits new credentials, at which point the device saves them and // reboots (ESP.restart()) to reconnect with a clean state. void startConfigPortal() { currentNetworkMode = NET_NONE; WiFi.mode(WIFI_AP); WiFi.softAP(AP_SSID, (strlen(AP_PASSWORD) > 0) ? AP_PASSWORD : nullptr); delay(200); IPAddress apIP = WiFi.softAPIP(); dnsServer.start(DNS_PORT, "*", apIP); showMessage("WIFI SETUP MODE", String("Connect to: ") + AP_SSID, apIP.toString()); server.on("/", HTTP_GET, []() { server.send_P(200, "text/html", CONFIG_PAGE); }); server.on("/save", HTTP_POST, []() { String ssid = server.arg("ssid"); String pass = server.arg("pass"); if (ssid.length() == 0) { server.send(400, "text/plain", "SSID required"); return; } preferences.begin("wifi", false); preferences.putString("ssid", ssid); preferences.putString("pass", pass); preferences.end(); server.send(200, "text/html", "

Saved!

" "

Rebooting and connecting to your WiFi...

"); showMessage("WIFI SAVED", "Rebooting...", ssid); delay(1500); ESP.restart(); }); // Captive-portal style redirect for anything else (helps phones pop // the "sign in to network" prompt automatically on most OSes). server.onNotFound([]() { server.sendHeader("Location", "http://" + WiFi.softAPIP().toString() + "/", true); server.send(302, "text/plain", ""); }); server.begin(); Serial.println("[WIFI] Config portal started"); Serial.println("[WIFI] AP SSID: " + String(AP_SSID)); Serial.println("[WIFI] AP IP: " + apIP.toString()); // Block here (allowing DNS + HTTP + manual reset) until /save reboots us. while (true) { dnsServer.processNextRequest(); server.handleClient(); checkManualReset(); yield(); } } // Orchestrates the WiFi backup path: try saved creds, else open portal. void startWiFiBackup() { if (!connectSavedWifi()) { startConfigPortal(); // blocks; only returns via ESP.restart() } } // ===================== Hardware ===================== void setupHardware() { pinMode(LED_GREEN, OUTPUT); pinMode(LED_BLUE, OUTPUT); pinMode(LED_RED, OUTPUT); pinMode(RESET_SWITCH, INPUT_PULLUP); pinMode(BUZZER_PIN, OUTPUT); digitalWrite(LED_GREEN, LOW); digitalWrite(LED_BLUE, LOW); digitalWrite(LED_RED, LOW); // Deselect every CS line before either SPI bus is brought up, // so no device can accidentally grab a bus during power-on. pinMode(SD_CS, OUTPUT); digitalWrite(SD_CS, HIGH); pinMode(ETH_CS, OUTPUT); digitalWrite(ETH_CS, HIGH); pinMode(TFT_CS, OUTPUT); digitalWrite(TFT_CS, HIGH); // ---- Shared SPI bus: W5500 + TFT only ---- SPI.begin(SPI_SCK, SPI_MISO, SPI_MOSI, -1); // ---- Dedicated SPI bus: SD card only (isolated from the above) ---- sdSPI.begin(SD_SPI_SCK, SD_SPI_MISO, SD_SPI_MOSI, SD_CS); // TFT tft.begin(40000000); tft.setRotation(1); tft.fillScreen(bgColor); showBootScreen("Starting...", "ESP32-S3 N16R8"); } bool startSD() { Serial.println("[SD] Mounting (dedicated SPI bus)..."); /* * SD now lives on its own SPI peripheral (sdSPI / HSPI), so it can * run at full speed without any risk of contending with the W5500 * on the shared bus. 40 MHz is a good starting point for a quality * SD module/card; drop to 20 MHz if a particular card is unstable. */ if (!SD.begin(SD_CS, sdSPI, 40000000)) { sdPresent = false; Serial.println("[SD] Mount failed"); return false; } sdPresent = checkSDPresent(); if (sdPresent) { Serial.println("[SD] Ready"); Serial.println("[SD] Used: " + formatBytes(computeSDUsedBytes())); } else { Serial.println("[SD] Not detected"); } return sdPresent; } // ===================== Routes ===================== void setupRoutes() { server.collectHeaders(AUTH_HEADERS, 1); server.on("/login", HTTP_GET, [](){ if (hasValidSession()) { server.sendHeader("Location", "/", true); server.send(302, "text/plain", ""); } else sendLoginPage(); }); server.on("/login", HTTP_POST, [](){ String u = server.arg("user"); String p = server.arg("pass"); String role; if (validateUser(u, p, role)) { int slot = -1; for (int i = 0; i < MAX_SESSIONS; i++) { if (!sessions[i].used) { slot = i; break; } if (millis() - sessions[i].issuedAt > AUTH_TTL_MS) { sessions[i].used = false; slot = i; break; } } if (slot < 0) slot = 0; // replace the oldest slot if all are busy sessions[slot].token = makeToken(); sessions[slot].username = u; sessions[slot].issuedAt = millis(); sessions[slot].used = true; server.sendHeader("Set-Cookie", "MTSESSION=" + sessions[slot].token + "; Path=/; HttpOnly; SameSite=Strict"); server.sendHeader("Location", "/", true); server.send(302, "text/plain", ""); } else { sendLoginPage("Invalid username or password"); } }); server.on("/logout", HTTP_GET, [](){ int idx = findSessionByRequest(); if (idx >= 0) sessions[idx].used = false; currentSessionUser = ""; server.sendHeader("Set-Cookie", "MTSESSION=deleted; Path=/; Max-Age=0; HttpOnly; SameSite=Strict"); server.sendHeader("Location", "/login", true); server.send(302, "text/plain", ""); }); server.on("/", HTTP_GET, [](){ if(!requireAuth())return; serveStaticFile("/index.html"); }); server.on("/file", HTTP_GET, [](){ if(!requireAuth())return; serveStaticFile("/files.html"); }); server.on("/about", HTTP_GET, [](){ if(!requireAuth())return; serveStaticFile("/about.html"); }); server.on("/system", HTTP_GET, [](){ if(!requireAuth())return; serveStaticFile("/system.html"); }); server.on("/settings", HTTP_GET, [](){ if(!requireAuth())return; serveStaticFile("/settings.html"); }); server.on("/logs", HTTP_GET, [](){ if(!requireAuth())return; serveStaticFile("/logs.html"); }); server.on("/style.css", HTTP_GET, [](){ if(!requireAuth())return; serveStaticFile("/style.css"); }); server.on("/script.js", HTTP_GET, [](){ if(!requireAuth())return; serveStaticFile("/script.js"); }); server.on("/app.js", HTTP_GET, [](){ if(!requireAuth())return; serveStaticFile("/app.js"); }); server.on("/list", HTTP_GET, handleList); server.on("/delete", HTTP_GET, doDeleteFile); server.on("/api/delete", HTTP_POST, doDeleteFile); server.on("/download", HTTP_GET, handleDownload); server.on("/api/status", HTTP_GET, handleStatus); server.on("/status", HTTP_GET, handleStatus); server.on("/upload-chunk", HTTP_POST, handleChunkUploadResult, handleChunkUpload); server.on("/api/upload-chunk", HTTP_POST, handleChunkUploadResult, handleChunkUpload); server.on("/api/upload/info", HTTP_GET, [](){ if(!requireAuth()) return; String name=server.hasArg("name")?server.arg("name"):""; if(!cleanFileName(name)){server.send(400,"application/json","{\\"error\\":\\"invalid filename\\"}");return;} String part="/"+name+".part"; uint64_t sz=0; if(SD.exists(part)){File f=SD.open(part,FILE_READ); if(f){sz=f.size();f.close();}} server.send(200,"application/json","{\\"part_size\\":"+String((unsigned long long)sz)+"}"); }); server.on("/api/v1/upload/info", HTTP_GET, [](){ if(!requireAuth()) return; String name=server.hasArg("name")?server.arg("name"):""; if(!cleanFileName(name)){server.send(400,"application/json","{\\"error\\":\\"invalid filename\\"}");return;} String part="/"+name+".part"; uint64_t sz=0; if(SD.exists(part)){File f=SD.open(part,FILE_READ); if(f){sz=f.size();f.close();}} server.send(200,"application/json","{\\"part_size\\":"+String((unsigned long long)sz)+"}"); }); server.on("/api/v1/status",HTTP_GET,handleStatus); server.on("/api/v1/files",HTTP_GET,[](){ if(!requireAuth()) return; File root=SD.open("/"); String json="{\\"files\\":["; bool first=true; if(root){ File f=root.openNextFile(); while(f){ if(!f.isDirectory()){ String n=String(f.name()); if(!isProtectedFile(n)){ if(!first)json+=","; n.replace("\\","\\\\"); n.replace("\"","\\\""); json+="{\\"name\\":\\""+n+"\\",\\"size\\":"+String((unsigned long long)f.size())+",\\"protected\\":false}"; first=false; } } f=root.openNextFile(); } root.close(); } json+="]}";server.send(200,"application/json",json); }); server.on("/api/v1/delete",HTTP_POST,doDeleteFile); server.on("/api/v1/upload/chunk",HTTP_POST,handleChunkUploadResult,handleChunkUpload); // ---------- Current user ---------- server.on("/api/v1/me", HTTP_GET, [](){ if(!requireAuth()) return; String role=currentUserRole(); server.send(200,"application/json", "{\\"username\\":\\""+currentSessionUser+"\\",\\"role\\":\\""+role+"\\",\\"admin\\":"+(role=="admin"?String("true"):String("false"))+"}"); }); // ---------- WiFi settings ---------- server.on("/api/v1/wifi/info", HTTP_GET, [](){ if(!requireAdmin()) return; preferences.begin("wifi", true); String ssid=preferences.getString("ssid",""); preferences.end(); String json="{\\"ssid\\":\\""+ssid+"\\",\\"connected\\":"+(wifiPresent?String("true"):String("false"))+ ",\\"ip\\":\\""+(wifiPresent?WiFi.localIP().toString():String(""))+"\\"}"; server.send(200,"application/json",json); }); server.on("/api/v1/wifi/save", HTTP_POST, [](){ if(!requireAdmin()) return; String ssid=server.arg("ssid"), pass=server.arg("pass"); ssid.trim(); if(ssid.length()==0 || ssid.length()>32 || pass.length()>64){ server.send(400,"application/json","{\\"error\\":\\"Invalid WiFi credentials\\"}"); return; } preferences.begin("wifi", false); preferences.putString("ssid",ssid); preferences.putString("pass",pass); preferences.end(); WiFi.disconnect(false, false); delay(100); WiFi.mode(WIFI_STA); WiFi.begin(ssid.c_str(),pass.c_str()); lastWifiRetry=millis(); server.send(200,"application/json","{\\"ok\\":true,\\"message\\":\\"WiFi credentials saved. Connecting...\\"}"); }); server.on("/api/v1/wifi/reset", HTTP_POST, [](){ if(!requireAdmin()) return; preferences.begin("wifi",false); preferences.clear(); preferences.end(); WiFi.disconnect(true,false); wifiPresent=false; if(!ethPresent) currentNetworkMode=NET_NONE; server.send(200,"application/json","{\\"ok\\":true,\\"message\\":\\"Saved WiFi credentials cleared\\"}"); }); // ---------- Multi-user management ---------- server.on("/api/v1/users", HTTP_GET, [](){ if(!requireAdmin()) return; preferences.begin("users", true); int count=preferences.getInt("count",0); String json="{\\"users\\":["; bool first=true; for(int i=0;i= 1500) { lastBeep = now; tone(BUZZER_PIN, 1500, 120); ledState = !ledState; digitalWrite(LED_RED, ledState); } } // ===================== Manual Reset ===================== void checkManualReset() { static uint32_t pressedAt = 0; if (digitalRead(RESET_SWITCH) == LOW) { if (pressedAt == 0) pressedAt = millis(); if (millis() - pressedAt > 1500) { delay(50); ESP.restart(); } } else { pressedAt = 0; } } // ===================== Main ===================== void setup() { Serial.begin(115200); delay(300); Serial.println(); Serial.println("===================================="); Serial.println(" ESP32-S3 N16R8 HIGH SPEED FILE HUB "); Serial.println(" W5500 (primary) + WiFi (backup) "); Serial.println(" ILI9341 + SD (dual SPI bus) "); Serial.println("===================================="); Network.onEvent(onNetworkEvent); setupHardware(); // Create the persistent default admin only on first boot. // Additional users are managed from Settings. ensureDefaultAdmin(); // SD runs on its own dedicated SPI bus (sdSPI), fully isolated // from the W5500 + TFT shared bus. if (!startSD()) { digitalWrite(LED_RED, HIGH); } showBootScreen("Starting W5500...", "Ethernet (primary)"); Network.begin(); // ---- Ethernet primary ---- bool ethOK = startEthernet(); if (ethOK) { currentNetworkMode=NET_ETHERNET; digitalWrite(LED_GREEN,HIGH); showBootScreen("ETHERNET READY",ETH.localIP().toString()); } // ---- WiFi backup: connect in parallel if credentials exist ---- preferences.begin("wifi", true); String savedSSID=preferences.getString("ssid", ""); String savedPass=preferences.getString("pass", ""); preferences.end(); if(savedSSID.length()) { WiFi.mode(WIFI_STA); WiFi.begin(savedSSID.c_str(),savedPass.c_str()); lastWifiRetry=millis(); } // Give WiFi a short chance at boot when Ethernet is absent. if(!ethOK){ uint32_t ws=millis(); while(WiFi.status()!=WL_CONNECTED && millis()-ws<8000UL){server.handleClient();delay(50);yield();} if(WiFi.status()==WL_CONNECTED){wifiPresent=true;currentNetworkMode=NET_WIFI;} } if(!ethOK && !wifiPresent){ startConfigPortal(); } setupRoutes(); server.begin(); Serial.println("[SERVER] HTTP server started on port 80"); Serial.println("[SERVER] Active network: " + activeNetworkLabel()); Serial.println("[SERVER] Open: http://" + getActiveIP()); updateStatusScreen(); } // ===================== Loop ===================== void loop() { // WebServer is based on NetworkServer in Arduino-ESP32 3.x. server.handleClient(); checkManualReset(); uint32_t now = millis(); // Periodic SD check. // Avoid doing this while a large upload is active. if (!uploading && now - lastSDCheck > 5000UL) { lastSDCheck = now; bool presentNow = checkSDPresent(); if (presentNow != sdPresent) { sdPresent = presentNow; if (sdPresent) { digitalWrite(LED_GREEN, HIGH); digitalWrite(LED_RED, LOW); showMessage("SD INSERTED", "Card is ready"); } else { digitalWrite(LED_GREEN, LOW); digitalWrite(LED_RED, HIGH); showMessage("SD REMOVED", "Insert SD card"); } delay(400); updateStatusScreen(); } } // Continuous network failover. Ethernet always has priority when available. if (ethPresent) currentNetworkMode=NET_ETHERNET; else if (wifiPresent) currentNetworkMode=NET_WIFI; else currentNetworkMode=NET_NONE; if(!wifiPresent && now-lastWifiRetry>8000UL){ lastWifiRetry=now; WiFi.reconnect(); } if(currentNetworkMode==NET_NONE && now-lastWifiRetry>12000UL){ lastWifiRetry=now; Serial.println("[NET] No link; retrying WiFi"); WiFi.reconnect(); } // TFT status refresh. if (!uploading && now - lastStatusUpdate > 3000UL) { lastStatusUpdate = now; updateStatusScreen(); } // Fault indicator. if (!networkIsUp() || !sdPresent) { systemFaultAlert(); } else { digitalWrite(LED_RED, LOW); digitalWrite(LED_GREEN, HIGH); } // Smooth TFT animation (icons, pulse and boot loader). animateTFT(); // Keep UI responsive without adding transfer overhead. yield(); }