This repository has been archived by the owner on Feb 4, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 51
/
ESP32_FS_EthernetWebServer.ino
564 lines (467 loc) · 14.4 KB
/
ESP32_FS_EthernetWebServer.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
/****************************************************************************************************************************
ESP32_FS_EthernetWebServer.ino - Dead simple FS Ethernet WebServer for ES32 using Ethernet shields
EthernetWebServer is a library for the Ethernet shields to run WebServer
Based on and modified from ESP8266 https://github.com/esp8266/Arduino/releases
Built by Khoi Hoang https://github.com/khoih-prog/EthernetWebServer
Licensed under MIT license
*****************************************************************************************************************************/
/*****************************************************************************************************************************
The Arduino board communicates with the shield using the SPI bus. This is on digital pins 11, 12, and 13 on the Uno
and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used as SS. On the Mega, the hardware SS pin, 53,
is not used to select the Ethernet controller chip, but it must be kept as an output or the SPI interface won't work.
*****************************************************************************************************************************/
/*****************************************************************************************************************************
How To Use:
1) Upload the contents of the data folder with MkSPIFFS Tool ("ESP8266 Sketch Data Upload" in Tools menu in Arduino IDE)
2) or you can upload the contents of a folder if you CD in that folder and run the following command:
for file in `\ls -A1`; do curl -F "file=@$PWD/$file" localIPAddress/edit; done
3) access the sample web page at http://localIPAddress/
*****************************************************************************************************************************/
// Important: Check https://github.com/khoih-prog/EthernetWebServer#7-for-fixing-esp32-compile-error
// and replace cores/esp32/Server.h to avoid compile error
#include "defines.h"
EthernetWebServer server(80);
//holds the current upload
File fsUploadFile;
void heartBeatPrint()
{
static int num = 1;
Serial.print(F("H")); // H means alive
if (num == 80)
{
Serial.println();
num = 1;
}
else if (num++ % 10 == 0)
{
Serial.print(F(" "));
}
}
void check_status()
{
static ulong checkstatus_timeout = 0;
static ulong current_millis;
#define HEARTBEAT_INTERVAL 10000L
current_millis = millis();
// Print hearbeat every HEARTBEAT_INTERVAL (10) seconds.
if ((current_millis > checkstatus_timeout) || (checkstatus_timeout == 0))
{
heartBeatPrint();
checkstatus_timeout = current_millis + HEARTBEAT_INTERVAL;
}
}
//format bytes
String formatBytes(size_t bytes)
{
if (bytes < 1024)
{
return String(bytes) + "B";
}
else if (bytes < (1024 * 1024))
{
return String(bytes / 1024.0) + "KB";
}
else if (bytes < (1024 * 1024 * 1024))
{
return String(bytes / 1024.0 / 1024.0) + "MB";
}
else
{
return String(bytes / 1024.0 / 1024.0 / 1024.0) + "GB";
}
}
String getContentType(const String& filename)
{
if (server.hasArg("download"))
{
return "application/octet-stream";
}
else if (filename.endsWith(".htm"))
{
return "text/html";
}
else if (filename.endsWith(".html"))
{
return "text/html";
}
else if (filename.endsWith(".css"))
{
return "text/css";
}
else if (filename.endsWith(".js"))
{
return "application/javascript";
}
else if (filename.endsWith(".png"))
{
return "image/png";
}
else if (filename.endsWith(".gif"))
{
return "image/gif";
}
else if (filename.endsWith(".jpg"))
{
return "image/jpeg";
}
else if (filename.endsWith(".ico"))
{
return "image/x-icon";
}
else if (filename.endsWith(".xml"))
{
return "text/xml";
}
else if (filename.endsWith(".pdf"))
{
return "application/x-pdf";
}
else if (filename.endsWith(".zip"))
{
return "application/x-zip";
}
else if (filename.endsWith(".gz"))
{
return "application/x-gzip";
}
return "text/plain";
}
bool handleFileRead(String path)
{
Serial.println("handleFileRead: " + path);
if (path.endsWith("/"))
{
path += "index.htm";
}
String contentType = getContentType(path);
String pathWithGz = path + ".gz";
if (filesystem->exists(pathWithGz) || filesystem->exists(path))
{
if (filesystem->exists(pathWithGz))
{
path += ".gz";
}
File file = filesystem->open(path, "r");
server.streamFile(file, contentType);
file.close();
return true;
}
return false;
}
void handleFileDelete()
{
if (server.args() == 0)
{
return server.send(500, "text/plain", "BAD ARGS");
}
String path = server.arg(0);
Serial.println("handleFileDelete: " + path);
if (path == "/")
{
return server.send(500, "text/plain", "BAD PATH");
}
if (!filesystem->exists(path))
{
return server.send(404, "text/plain", "FileNotFound");
}
filesystem->remove(path);
server.send(200, "text/plain", "");
path.clear();
}
void handleFileCreate()
{
if (server.args() == 0)
{
return server.send(500, "text/plain", "BAD ARGS");
}
String path = server.arg(0);
Serial.println("handleFileCreate: " + path);
if (path == "/")
{
return server.send(500, "text/plain", "BAD PATH");
}
if (filesystem->exists(path))
{
return server.send(500, "text/plain", "FILE EXISTS");
}
File file = filesystem->open(path, "w");
if (file)
{
file.close();
}
else
{
return server.send(500, "text/plain", "CREATE FAILED");
}
server.send(200, "text/plain", "");
path.clear();
}
void handleFileUpload()
{
if (server.uri() != "/edit")
{
return;
}
ethernetHTTPUpload& upload = server.upload();
if (upload.status == UPLOAD_FILE_START)
{
String filename = upload.filename;
if (!filename.startsWith("/"))
{
filename = "/" + filename;
}
Serial.print(F("handleFileUpload Name: "));
Serial.println(filename);
fsUploadFile = filesystem->open(filename, "w");
filename.clear();
}
else if (upload.status == UPLOAD_FILE_WRITE)
{
//Serial.print(F("handleFileUpload Data: ")); Serial.println(upload.currentSize);
if (fsUploadFile)
{
fsUploadFile.write(upload.buf, upload.currentSize);
}
}
else if (upload.status == UPLOAD_FILE_END)
{
if (fsUploadFile)
{
fsUploadFile.close();
}
Serial.print(F("handleFileUpload Size: "));
Serial.println(upload.totalSize);
}
}
void handleFileList()
{
if (!server.hasArg("dir"))
{
server.send(500, "text/plain", "BAD ARGS");
return;
}
String path = server.arg("dir");
Serial.println("handleFileList: " + path);
File root = FileFS.open(path);
path = String();
String output = "[";
if (root.isDirectory())
{
File file = root.openNextFile();
while (file)
{
if (output != "[")
{
output += ',';
}
output += "{\"type\":\"";
output += (file.isDirectory()) ? "dir" : "file";
output += "\",\"name\":\"";
output += String(file.name()).substring(1);
output += "\"}";
file = root.openNextFile();
}
}
output += "]";
Serial.println("handleFileList: " + output);
server.send(200, "text/json", output);
}
void initFS()
{
// Initialize LittleFS/SPIFFS file-system
// Format SPIFFS if not yet
if (!FileFS.begin(true))
{
Serial.println(F("SPIFFS/LittleFS failed! Formatting."));
if (!FileFS.begin())
{
while (true)
{
#if USE_LITTLEFS
Serial.println(F("LittleFS failed!. Please use SPIFFS."));
#else
Serial.println(F("SPIFFS failed!. Please use LittleFS."));
#endif
// Stay forever here as useless to go further
delay(5000);
}
}
}
}
void listDir()
{
File root = FileFS.open("/");
File file = root.openNextFile();
while (file)
{
String fileName = file.name();
size_t fileSize = file.size();
Serial.printf("FS File: %s, size: %s\n", fileName.c_str(), formatBytes(fileSize).c_str());
file = root.openNextFile();
}
Serial.println();
}
void initWebserver()
{
//SERVER INIT
//list directory
server.on("/list", HTTP_GET, handleFileList);
//load editor
server.on("/edit", HTTP_GET, []()
{
if (!handleFileRead("/edit.htm"))
{
server.send(404, "text/plain", "FileNotFound");
}
});
//create file
server.on("/edit", HTTP_PUT, handleFileCreate);
//delete file
server.on("/edit", HTTP_DELETE, handleFileDelete);
//first callback is called after the request has ended with all parsed arguments
//second callback handles file uploads at that location
server.on("/edit", HTTP_POST, []()
{
server.send(200, "text/plain", "");
}, handleFileUpload);
//called when the url is not defined here
//use it to load content from SPIFFS
server.onNotFound([]()
{
if (!handleFileRead(server.uri()))
{
server.send(404, "text/plain", "FileNotFound");
}
});
//get heap status, analog input value and all GPIO statuses in one json call
server.on("/all", HTTP_GET, []()
{
String json = "{";
json += "\"heap\":" + String(ESP.getFreeHeap());
json += ", \"analog\":" + String(analogRead(A0));
json += ", \"gpio\":" + String((uint32_t)(0));
json += "}";
server.send(200, "text/json", json);
json = String();
});
// Web Page handlers
server.serveStatic("/", FileFS, "/page1.html");
server.serveStatic("/page2", FileFS, "/page2.html");
server.serveStatic("/page3", FileFS, "/page3.html");
//server.serveStatic("/", SPIFFS, "/page1.html");
//server.serveStatic("/page2", SPIFFS, "/page2.html");
//server.serveStatic("/page3", SPIFFS, "/page3.html");
// Other usage with various web site assets:
// server.serveStatic("/assets/css/test.css", SPIFFS, "/assets/css/test.css"); // Style sheet
// server.serveStatic("/assets/js/test_script.js", SPIFFS,"/assets/js/test_script.js"); // Javascript
// server.serveStatic("/assets/font/fonticons.ttf", SPIFFS,"/assets/font/fonticons.ttf"); // font
// server.serveStatic("/assets/picture.png", SPIFFS,"/assets/picture.png"); // Picture
server.begin();
}
void setup()
{
Serial.begin(115200);
while (!Serial);
delay(200);
Serial.print("\nStarting ESP32_FS_EthernetWebServer on " + String(BOARD_TYPE));
Serial.print(" using ");
Serial.println(FS_Name);
Serial.println("With " + String(SHIELD_TYPE));
Serial.println(ETHERNET_WEBSERVER_VERSION);
#if USE_ETHERNET_GENERIC
ET_LOGWARN(F("=========== USE_ETHERNET_GENERIC ==========="));
#elif USE_ETHERNET_ESP8266
ET_LOGWARN(F("=========== USE_ETHERNET_ESP8266 ==========="));
#elif USE_ETHERNET_ENC
ET_LOGWARN(F("=========== USE_ETHERNET_ENC ==========="));
#else
ET_LOGWARN(F("========================="));
#endif
ET_LOGWARN(F("Default SPI pinout:"));
ET_LOGWARN1(F("MOSI:"), MOSI);
ET_LOGWARN1(F("MISO:"), MISO);
ET_LOGWARN1(F("SCK:"), SCK);
ET_LOGWARN1(F("SS:"), SS);
ET_LOGWARN(F("========================="));
#if defined(ESP8266)
// For ESP8266, change for other boards if necessary
#ifndef USE_THIS_SS_PIN
#define USE_THIS_SS_PIN D2 // For ESP8266
#endif
ET_LOGWARN1(F("ESP8266 setCsPin:"), USE_THIS_SS_PIN);
#if ( USE_ETHERNET_GENERIC || USE_ETHERNET_ENC )
// For ESP8266
// Pin D0(GPIO16) D1(GPIO5) D2(GPIO4) D3(GPIO0) D4(GPIO2) D8
// Ethernet 0 X X X X 0
// Ethernet2 X X X X X 0
// Ethernet3 X X X X X 0
// EthernetLarge X X X X X 0
// Ethernet_ESP8266 0 0 0 0 0 0
// D2 is safe to used for Ethernet, Ethernet2, Ethernet3, EthernetLarge libs
// Must use library patch for Ethernet, EthernetLarge libraries
Ethernet.init (USE_THIS_SS_PIN);
#elif USE_CUSTOM_ETHERNET
// You have to add initialization for your Custom Ethernet here
// This is just an example to setCSPin to USE_THIS_SS_PIN, and can be not correct and enough
Ethernet.init(USE_THIS_SS_PIN);
#endif //( USE_ETHERNET_GENERIC || USE_ETHERNET_ENC )
#elif defined(ESP32)
// You can use Ethernet.init(pin) to configure the CS pin
//Ethernet.init(10); // Most Arduino shields
//Ethernet.init(5); // MKR ETH shield
//Ethernet.init(0); // Teensy 2.0
//Ethernet.init(20); // Teensy++ 2.0
//Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet
//Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet
#ifndef USE_THIS_SS_PIN
#define USE_THIS_SS_PIN 5 //22 // For ESP32
#endif
ET_LOGWARN1(F("ESP32 setCsPin:"), USE_THIS_SS_PIN);
// For other boards, to change if necessary
#if ( USE_ETHERNET_GENERIC || USE_ETHERNET_ENC )
// Must use library patch for Ethernet, EthernetLarge libraries
// ESP32 => GPIO2,4,5,13,15,21,22 OK with Ethernet, Ethernet2, EthernetLarge
// ESP32 => GPIO2,4,5,15,21,22 OK with Ethernet3
//Ethernet.setCsPin (USE_THIS_SS_PIN);
Ethernet.init (USE_THIS_SS_PIN);
#elif USE_CUSTOM_ETHERNET
// You have to add initialization for your Custom Ethernet here
// This is just an example to setCSPin to USE_THIS_SS_PIN, and can be not correct and enough
Ethernet.init(USE_THIS_SS_PIN);
#endif //( USE_ETHERNET_GENERIC || USE_ETHERNET_ENC )
#endif //defined(ESP8266)
// start the ethernet connection and the server:
// Use DHCP dynamic IP and random mac
uint16_t index = millis() % NUMBER_OF_MAC;
// Use Static IP
//Ethernet.begin(mac[index], ip);
Ethernet.begin(mac[index]);
// Just info to know how to connect correctly
Serial.println("=========================");
Serial.println("Currently Used SPI pinout:");
Serial.print("MOSI:");
Serial.println(MOSI);
Serial.print("MISO:");
Serial.println(MISO);
Serial.print("SCK:");
Serial.println(SCK);
Serial.print("CS/SS:");
Serial.println(USE_THIS_SS_PIN);
Serial.println(F("========================="));
Serial.print(F("Using mac index = "));
Serial.println(index);
Serial.print(F("Connected! IP address: "));
Serial.println(Ethernet.localIP());
initFS();
listDir();
initWebserver();
Serial.print("HTTP server started @");
Serial.println(Ethernet.localIP());
Serial.print(F("Open http://"));
Serial.print(Ethernet.localIP());
Serial.println(F("/edit to see the file browser"));
}
void loop()
{
server.handleClient();
}