ESP32-S3 Advanced Web Portal & File Management System
Table of Contents
- Overview
- Hardware Components
- Pin Connection
- ESP32-S3 β W5500
- ESP32-S3 β 2.4" ILI9341 TFT
- ESP32-S3 β MicroSD Module
- Status LEDs, Reset & Buzzer
- Web Portal
- Dashboard
- File Manager
- System Page
- Settings
- SPI Bus Architecture
- Shared SPI Bus
- Dedicated SD SPI Bus
- Architecture Overview
- How It Works
- 1. ESP32-S3 starts
- 2. MicroSD is mounted
- 3. Ethernet is attempted first
- 4. WiFi backup
- 5. Web Server starts
- 6. User login
- 7. File management
- 8. Upload processing
- Project Structure
- Required Libraries
- Main functions
- Setup Guide
- Step 1 β Install ESP32 Board Package
- Step 2 β Install Libraries
- Step 3 β Connect Hardware
- Step 4 β Insert MicroSD
- Step 5 β Upload Firmware
- Step 6 β Connect Ethernet
- Step 7 β WiFi Configuration
- Step 8 β Open the Web Portal
- Network Modes
- Ethernet β Primary
- WiFi β Backup
- WiFi Configuration Portal
- Security & User Management
- Authentication
- User Roles
- Important Security Note
- Upload System
- TFT Display
- Status & Monitoring
- Important Design Decisions
- 1. W5500 + TFT share SPI
- 2. SD uses a dedicated SPI bus
- 3. Ethernet has priority
- 4. Web Portal is the main interface
- Important Notes
- Future Improvements
Overview
This project turns an ESP32-S3 N16R8 into an embedded Web Portal and local file-management platform.
The main focus of this project is the browser-based Web Portal. After connecting to the ESP32-S3 through Ethernet or WiFi, an authorized user can open the portal and manage files stored on the MicroSD Card.
The system includes:
- π Secure login and session-based authentication
- π₯ Admin and user roles
- π File manager
- β¬οΈ File upload
- β¬οΈ File download
- ποΈ File management/delete operations
- π System and storage status
- π W5500 Ethernet as the primary network
- πΆ WiFi as a backup network
- π₯οΈ 2.4" ILI9341 TFT status display
- πΎ Dedicated SPI bus for the MicroSD card
- π Resumable/chunk upload support
- βοΈ WiFi configuration and persistent settings
The firmware uses an embedded WebServer running on port 80.
Hardware Components
| Component | Description | Quantity |
|---|---|---|
| ESP32-S3 N16R8 | Main microcontroller | 1 |
| W5500 Ethernet Module | Primary Ethernet interface | 1 |
| MicroSD Card Module | File storage | 1 |
| MicroSD Card | Storage media | 1 |
| 2.4" ILI9341 TFT | Web server/device status display | 1 |
| Green LED | Normal/ready status | 1 |
| Blue LED | Network/status indication | 1 |
| Red LED | Fault/error indication | 1 |
| Buzzer | Fault alert | 1 |
| Push Button | Manual reset | 1 |
| Jumper Wires | Connections | As required |
| 5V Power Supply | System power | 1 |
Pin Connection

ESP32-S3 β W5500
| W5500 Pin | ESP32-S3 GPIO | Function |
|---|---|---|
| SCK | GPIO 12 | SPI Clock |
| MISO | GPIO 13 | SPI Data Out |
| MOSI | GPIO 11 | SPI Data In |
| CS / SS | GPIO 10 | Chip Select |
| INT | GPIO 9 | Interrupt |
| RST | GPIO 8 | Hardware Reset |
| VCC | Module-specific | Power |
| GND | GND | Ground |
ESP32-S3 β 2.4" ILI9341 TFT
| TFT Pin | ESP32-S3 GPIO | Function |
|---|---|---|
| SCK / CLK | GPIO 12 | Shared SPI Clock |
| MISO | GPIO 13 | Shared SPI MISO |
| MOSI | GPIO 11 | Shared SPI MOSI |
| CS | GPIO 7 | TFT Chip Select |
| DC | GPIO 6 | Data/Command |
| RST | GPIO 5 | TFT Reset |
| VCC | Module-specific | Power |
| GND | GND | Ground |
ESP32-S3 β MicroSD Module
The MicroSD card uses a dedicated HSPI bus, isolated from the W5500 + TFT shared SPI bus.
| SD Pin | ESP32-S3 GPIO | Function |
|---|---|---|
| SCK / CLK | GPIO 16 | SD SPI Clock |
| MISO | GPIO 17 | SD SPI MISO |
| MOSI | GPIO 18 | SD SPI MOSI |
| CS | GPIO 4 | SD Chip Select |
| VCC | Module-specific | Power |
| GND | GND | Ground |
Status LEDs, Reset & Buzzer
| Device | ESP32-S3 GPIO | Configuration / Function |
|---|---|---|
| Green LED | GPIO 1 | Normal/network ready |
| Blue LED | GPIO 2 | Status indication |
| Red LED | GPIO 3 | Fault indication |
| Reset Switch | GPIO 14 | INPUT_PULLUP, long press resets |
| Buzzer | GPIO 15 | Fault alert |
Important: Check the exact power requirements of your W5500 and TFT/SD modules before wiring. Do not assume every breakout accepts the same supply voltage.
Web Portal
Dashboard
The Web Portal is the primary user interface of this project.

The dashboard is intended to provide a central view of:
- Current network mode
- IP address
- Ethernet/WiFi state
- SD card availability
- Storage usage
- Free heap / memory information
- PSRAM information
- Uptime
- Upload status/speed
File Manager

The file-management interface provides browser-based access to files stored on the MicroSD card.
Typical operations include:
- Browse files
- Upload files
- Download files
- Delete/manage files
- Monitor upload progress
System Page

The System page is intended for hardware and runtime information such as:
- ESP32-S3 status
- Network status
- IP information
- Storage status
- Memory information
- Runtime/uptime
- Upload information
Settings

The Settings area handles administrative configuration such as:
- Portal users
- User roles
- WiFi configuration
- Administrative controls
- System-related settings
Note: Put your actual Web Portal screenshots inside the WebPortal/ folder using the filenames shown above. This keeps the README structure similar to the previous project README while matching the new firmware.SPI Bus Architecture
One of the important design decisions in this project is separating the SD card from the W5500/TFT SPI bus.
Shared SPI Bus
W5500 + ILI9341 TFT
| Signal | GPIO |
|---|---|
| SCK | GPIO 12 |
| MISO | GPIO 13 |
| MOSI | GPIO 11 |
| W5500 CS | GPIO 10 |
| TFT CS | GPIO 7 |
Dedicated SD SPI Bus
MicroSD only
| Signal | GPIO |
|---|---|
| SD SCK | GPIO 16 |
| SD MISO | GPIO 17 |
| SD MOSI | GPIO 18 |
| SD CS | GPIO 4 |
This architecture prevents the SD card from sharing the same SPI peripheral with the W5500 and TFT.
Architecture Overview
ββββββββββββββββββββββββ β ESP32-S3 N16R8 β β β β Web Server β β Authentication β β File Manager β β Upload System β β Status API β ββββββββββββ¬ββββββββββββ β ββββββββββββββββββββββΌβββββββββββββββββββββ β β β βΌ βΌ βΌ βββββββββββββββ βββββββββββββββ βββββββββββββββ β W5500 β β MicroSD β β ILI9341 TFTβ β Ethernet β β Storage β β Status β β Primary β β Dedicated SPIβ β Display β ββββββββ¬βββββββ βββββββββββββββ βββββββββββββββ β βΌ βββββββββββββββ β LAN / Routerβ ββββββββ¬βββββββ β βΌ Browser Client WiFi β Backup Network / Configuration Portal
How It Works
1. ESP32-S3 starts
The firmware initializes:
- GPIO
- W5500/TFT shared SPI
- Dedicated SD SPI
- TFT
- MicroSD
- Authentication system
- Ethernet
- WiFi backup
2. MicroSD is mounted
The SD card is initialized through the dedicated HSPI bus.
The card becomes the main file-storage backend for the Web Portal.
3. Ethernet is attempted first
W5500 is initialized as the primary network interface.
If Ethernet obtains an IP address, the system operates in Ethernet mode.
4. WiFi backup
Saved WiFi credentials can be used as a backup network.
If no saved credentials are available, the firmware can expose the WiFi configuration portal:
ESP32-FileHub-Setup
The WiFi credentials are saved using ESP32 Preferences.
5. Web Server starts
The ESP32-S3 hosts the Web Portal on:
HTTP Port: 80
6. User login
Protected portal pages require authentication.
The firmware maintains login sessions and supports administrator/user roles.
7. File management
After authentication, users can interact with files stored on the MicroSD card through the browser.
8. Upload processing
The project supports normal upload handling and a chunk/resumable upload mechanism with offset/progress tracking.
Project Structure
ESP32_S3_ADVANCED_WEB_PORTAL/ β βββ Program/ β βββ ESP32_S3_Advanced_Web_Portal.ino β βββ WebPortal/ β βββ Dashboard.png β βββ Files.png β βββ System.png β βββ Settings.png β βββ Login.png β βββ Diagram/ β βββ ESP32_S3_Web_Portal_System_Architecture.png β βββ ESP32_S3_W5500_Connection_Diagram.png β βββ ESP32_S3_SD_Connection_Diagram.png β βββ ESP32_S3_TFT_Connection_Diagram.png β βββ README.md βββ LICENSE
The WebPortal/ image names are documentation assets. Replace them with screenshots from the actual running portal.Required Libraries
The firmware uses the following Arduino/ESP32 libraries:
#include <Arduino.h> #include <SPI.h> #include <SD.h> #include <Preferences.h> #include <DNSServer.h> #include <WiFi.h> #include <WebServer.h> #include <ETH.h> #include <Adafruit_GFX.h> #include <Adafruit_ILI9341.h>
Main functions
| Library | Purpose |
|---|---|
| Arduino.h | Core Arduino functionality |
| SPI.h | SPI communication |
| SD.h | MicroSD filesystem |
| Preferences.h | Persistent settings |
| DNSServer.h | WiFi configuration/captive-style portal |
| WiFi.h | WiFi networking |
| WebServer.h | Embedded HTTP server |
| ETH.h | W5500 Ethernet support |
| Adafruit_GFX.h | Graphics framework |
| Adafruit_ILI9341.h | ILI9341 TFT driver |
Setup Guide
Step 1 β Install ESP32 Board Package
Use an ESP32-S3 compatible Arduino board configuration.
Step 2 β Install Libraries
Install:
- Adafruit GFX Library
- Adafruit ILI9341
- ESP32 core libraries
The remaining libraries are provided by the ESP32 Arduino environment.
Step 3 β Connect Hardware
Follow the connection tables in this README.
Step 4 β Insert MicroSD
Insert a compatible MicroSD card into the SD module.
Step 5 β Upload Firmware
Open the project in Arduino IDE and upload the firmware to the ESP32-S3.
Step 6 β Connect Ethernet
Connect the W5500 Ethernet module to a LAN/router.
The firmware attempts Ethernet as the primary network.
Step 7 β WiFi Configuration
If Ethernet is unavailable and no saved WiFi credentials exist, use:
ESP32-FileHub-Setup
to configure the backup WiFi connection.
Step 8 β Open the Web Portal
Find the IP address shown by the system/TFT or serial output and open:
http://ESP32_IP/
Network Modes
Ethernet β Primary
ESP32-S3
β
βΌ
W5500
β
βΌ
LAN / Router
β
βΌ
Browser
WiFi β Backup
ESP32-S3
β
βΌ
WiFi STA
β
βΌ
Router
β
βΌ
Browser
WiFi Configuration Portal
When saved WiFi credentials are unavailable, the device can start the configuration portal:
ESP32-FileHub-Setup
The entered SSID/password are stored in ESP32 Preferences and the device reboots to use the saved configuration.
Security & User Management
The portal includes session-based authentication.
Authentication
- Login page
- Session token
- Cookie-based session handling
- Session timeout
- Protected routes
User Roles
The firmware supports:
ADMIN USER
Administrative functions are protected separately from normal authenticated access.
Important Security Note
The firmware contains a default administrator configuration in the source code.
Change the default administrator credentials before deploying the project outside your test environment.
Also note that this project is primarily designed as a local/embedded Web Portal. If you expose it directly to an untrusted network or the public Internet, additional security such as HTTPS/TLS, stronger credential storage and hardened authentication should be considered.
Upload System
The project contains a resumable/chunk upload mechanism.
The firmware keeps track of:
- Upload file
- Final file path
- Temporary/chunk path
- Current offset
- Total size
- Written bytes
- Error state
Conceptually:
Browser β β File Upload βΌ ESP32-S3 Web Server β β Chunks / Offset βΌ MicroSD β βΌ Completed File
This approach is useful when handling larger uploads than a single blocking upload operation.
TFT Display
The 2.4" ILI9341 TFT is used as a local status interface.
The firmware can display information such as:
- Boot status
- ESP32-S3 identification
- Ethernet initialization
- IP address
- Network state
- Upload/status information
- System messages
The TFT operates on the shared SPI bus with the W5500 but has its own chip-select pin.
Status & Monitoring
The Web Portal exposes system information such as:
| Status | Information |
|---|---|
| Network | Ethernet / WiFi / none |
| IP | Current network IP |
| Link | Ethernet link information |
| Storage | SD card usage |
| Heap | Free heap information |
| PSRAM | PSRAM status |
| Uptime | System runtime |
| Upload | Upload state/speed |
This makes the Web Portal useful not only for file management but also for monitoring the embedded server.
Important Design Decisions
1. W5500 + TFT share SPI
GPIO 11 β MOSI GPIO 12 β SCK GPIO 13 β MISO
Separate CS pins select the individual device.
2. SD uses a dedicated SPI bus
GPIO 16 β SD SCK GPIO 17 β SD MISO GPIO 18 β SD MOSI GPIO 4 β SD CS
This keeps SD traffic isolated from W5500/TFT traffic.
3. Ethernet has priority
The firmware attempts W5500 Ethernet first and uses WiFi as the backup path.
4. Web Portal is the main interface
The TFT provides local status, while the browser provides the main user interface for:
Login Dashboard Files Upload Download System Settings Logs About
Important Notes
- This project is based on ESP32-S3 N16R8 hardware configuration.
- GPIO assignments must match the firmware before powering the system.
- W5500 and TFT share the main SPI bus.
- MicroSD uses a separate HSPI bus.
- The actual W5500 breakout power requirements may vary by module.
- The actual TFT/SD module power requirements may vary by breakout.
- Do not expose the portal directly to the public Internet without additional security hardening.
- Do not publish administrator credentials in screenshots, videos or README files.
- Actual transfer performance depends on the ESP32-S3, W5500, SD card, network, file size and other system conditions.
- The project should be treated as an embedded/local file-management server rather than assuming enterprise NAS functionality.
Future Improvements
Possible future upgrades:
- HTTPS / TLS
- Password hashing
- Stronger credential storage
- File encryption
- More granular permissions
- Multiple simultaneous upload sessions
- Folder creation/management
- File search
- File preview improvements
- Remote access through a secure tunnel
- Mobile-friendly PWA
- Mobile application
- OTA firmware update
- Advanced network diagnostics
- Long-term stability testing
- Improved storage management
Source Code
MicroTronic_Server.inoDownload
// ===================== Libraries =====================
#include <Arduino.h>
#include <SPI.h>
#include <SD.h>
#include <Preferences.h>
#include <DNSServer.h>
#include <WiFi.h>
// 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 <WebServer.h>
#include <ETH.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
// ===================== 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(<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Micro Tronic Server β Login</title><style>
*{box-sizing:border-box}body{margin:0;min-height:100vh;display:grid;place-items:center;background:radial-gradient(circle at 50% -10%,#12314a,#05080e 55%);color:#eef7ff;font-family:system-ui,Segoe UI,sans-serif}.box{width:min(420px,92vw);padding:34px;border:1px solid #20354b;border-radius:24px;background:rgba(9,16,26,.92);box-shadow:0 30px 80px #0008}.logo{width:52px;height:52px;border:1px solid #20d9ff66;border-radius:15px;display:grid;place-items:center;color:#20d9ff;font-size:28px;margin-bottom:20px}.eyebrow{color:#20d9ff;font-size:10px;letter-spacing:.2em;font-weight:700}.box h1{margin:7px 0;font-size:29px}.sub{color:#7e91a7;margin-bottom:24px}.field{margin:12px 0}.field label{display:block;font-size:11px;color:#7e91a7;margin-bottom:6px}.field input{width:100%;padding:13px;border-radius:11px;border:1px solid #21344a;background:#07101a;color:#fff;outline:none}.field input:focus{border-color:#20d9ff}.btn{width:100%;padding:13px;border:0;border-radius:11px;background:#20d9ff;color:#031018;font-weight:800;cursor:pointer;margin-top:8px}.err{padding:10px;border-radius:10px;background:#ff5e6c14;border:1px solid #ff5e6c55;color:#ff8e98;font-size:12px;margin-bottom:12px}.foot{margin-top:20px;color:#50647a;font-size:10px;text-align:center}</style></head><body><form class="box" method="POST" action="/login"><div class="logo">β</div><div class="eyebrow">MICRO TRONIC SERVER</div><h1>Portal Sign In</h1><div class="sub">Secure multi-user local server access</div>)HTML";
if(error.length()) html += "<div class='err'>" + error + "</div>";
html += R"HTML(<div class="field"><label>USER ID</label><input name="user" autocomplete="username" required></div><div class="field"><label>PASSWORD</label><input name="pass" type="password" autocomplete="current-password" required></div><button class="btn">Sign in</button><div class="foot">ESP32-S3 β’ W5500 β’ SD Server</div></form></body></html>)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(
<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width,initial-scale=1">
<title>ESP32 File Hub - WiFi Setup</title>
<style>
body{font-family:sans-serif;background:#0d0d0d;color:#eee;padding:24px;max-width:420px;margin:0 auto}
h2{color:#0af}
input{width:100%;padding:10px;margin:8px 0 16px;box-sizing:border-box;border-radius:6px;border:1px solid #444;background:#1a1a1a;color:#eee}
button{width:100%;padding:12px;background:#0af;color:#000;border:none;border-radius:6px;font-weight:bold;font-size:16px}
p{color:#aaa;font-size:14px}
</style></head><body>
<h2>ESP32 File Hub</h2>
<p>Ethernet not found. Enter your WiFi details so the file hub can connect as a backup network.</p>
<form action="/save" method="POST">
<label>WiFi SSID</label>
<input name="ssid" required maxlength="32">
<label>WiFi Password</label>
<input name="pass" type="password" maxlength="64">
<button type="submit">Save & Connect</button>
</form>
</body></html>
)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",
"<html><body style='font-family:sans-serif;background:#0d0d0d;color:#eee;"
"text-align:center;padding-top:60px'><h2>Saved!</h2>"
"<p>Rebooting and connecting to your WiFi...</p></body></html>");
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<count && i<MAX_USERS;i++){
String base="u"+String(i);
String n=preferences.getString((base+"n").c_str(),"");
String r=preferences.getString((base+"r").c_str(),"user");
if(!n.length()) continue;
if(!first)json+=",";
json+="{\\"username\\":\\""+n+"\\",\\"role\\":\\""+r+"\\",\\"current\\":"+(n==currentSessionUser?String("true"):String("false"))+"}";
first=false;
}
preferences.end();
json+="]}";
server.send(200,"application/json",json);
});
server.on("/api/v1/users/add", HTTP_POST, [](){
if(!requireAdmin()) return;
String u=server.arg("username"), p=server.arg("password"), r=server.arg("role");
u.trim();
if(!addPortalUser(u,p,r)){
server.send(400,"application/json","{\\"error\\":\\"Unable to create user. Username may already exist, password must be 6+ characters, and maximum users is 8.\\"}");
return;
}
server.send(200,"application/json","{\\"ok\\":true}");
});
server.on("/api/v1/users/delete", HTTP_POST, [](){
if(!requireAdmin()) return;
String u=server.arg("username");
if(u==currentSessionUser){
server.send(400,"application/json","{\\"error\\":\\"You cannot remove the account currently in use\\"}");
return;
}
if(!removePortalUser(u)){
server.send(400,"application/json","{\\"error\\":\\"User could not be removed\\"}");
return;
}
server.send(200,"application/json","{\\"ok\\":true}");
});
server.on("/api/v1/users/password", HTTP_POST, [](){
if(!requireAuth()) return;
String oldPass=server.arg("old"), newPass=server.arg("password");
if(!updatePortalPassword(currentSessionUser,oldPass,newPass)){
server.send(400,"application/json","{\\"error\\":\\"Current password is incorrect or new password is too short\\"}");
return;
}
server.send(200,"application/json","{\\"ok\\":true}");
});
// Backward-compatible WiFi reset endpoint.
server.on("/wifi-reset", HTTP_GET, [](){
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,"text/plain","WiFi credentials cleared.");
});
server.onNotFound([](){
if(!hasValidSession()){requireAuth();return;}
server.send(404,"text/plain","404 - Not Found");
});
}
// ===================== Fault Alert =====================
void systemFaultAlert() {
static uint32_t lastBeep = 0;
static bool ledState = false;
uint32_t now = millis();
if (now - lastBeep >= 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();
}








