-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathBaseSupport.h
More file actions
395 lines (363 loc) · 9.84 KB
/
BaseSupport.h
File metadata and controls
395 lines (363 loc) · 9.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
/*
R. J. Tidey 2019/12/30
Basic support include
A common core of functions often used in applications
WifiManager
WebServer
UpdateServer
Spiffs or LittleFS
FileBrowsing
*/
//#define ESP8266
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <ESP8266HTTPUpdateServer.h>
#include <DNSServer.h>
#include <WiFiManager.h>
#ifndef FILESYSTYPE
#define FILESYSTYPE 0
#endif
#ifndef FILECMD_START
#define FILECMD_START
#endif
#ifndef FILECMD_END
#define FILECMD_END
#endif
#ifndef WM_PORTALTIMEOUT
#define WM_PORTALTIMEOUT 180
#endif
#if FILESYSTYPE == 0
#include "LittleFS.h"
#define FILESYS LittleFS
#else
#include "FS.h"
#define FILESYS SPIFFS
#endif
int setupWifi = 1;
/*
Wifi Manager Web set up
*/
#ifdef WM_NAME
WiFiManager wifiManager;
#endif
char wmName[33];
#define WIFI_CHECK_TIMEOUT 30000
unsigned long wifiCheckTime;
//holds the current upload
File fsUploadFile;
//For update service
const char* update_path = "/firmware";
const char* update_username = "admin";
//AP definitions
#define AP_MAX_WAIT 10
#ifndef AP_PORT
#define AP_PORT 80
#endif
String macAddr;
ESP8266WebServer server(AP_PORT);
ESP8266HTTPUpdateServer httpUpdater;
void IRAM_ATTR delaymSec(unsigned long mSec) {
unsigned long ms = mSec;
while(ms > 100) {
delay(100);
ms -= 100;
ESP.wdtFeed();
}
delay(ms);
ESP.wdtFeed();
yield();
}
void IRAM_ATTR delayuSec(unsigned long uSec) {
unsigned long us = uSec;
while(us > 100000) {
delay(100);
us -= 100000;
ESP.wdtFeed();
}
delayMicroseconds(us);
ESP.wdtFeed();
yield();
}
void defaultIO() {
pinMode(0,INPUT_PULLUP);
pinMode(2,INPUT_PULLUP);
pinMode(4,INPUT_PULLUP);
pinMode(5,INPUT_PULLUP);
pinMode(12,INPUT_PULLUP);
pinMode(13,INPUT_PULLUP);
pinMode(14,INPUT_PULLUP);
pinMode(15,INPUT_PULLUP);
pinMode(16,INPUT_PULLDOWN_16);
}
/*
Connect to local wifi with retries
If check is set then test the connection and re-establish if timed out
*/
int wifiConnect(int check) {
unsigned long m = millis();
if(check) {
if((m - wifiCheckTime) > WIFI_CHECK_TIMEOUT) {
if(WiFi.status() != WL_CONNECTED) {
Serial.println(F("Wifi connection timed out. Try to relink"));
} else {
wifiCheckTime = m;
return 1;
}
} else {
return 1;
}
}
wifiCheckTime = m;
Serial.println(F("Set up managed Web"));
#ifdef WM_STATIC_IP
wifiManager.setSTAStaticIPConfig(IPAddress(WM_STATIC_IP), IPAddress(WM_STATIC_GATEWAY), IPAddress(255,255,255,0));
#endif
#ifdef FASTCONNECT
wifiManager.setFastConnectMode(FASTCONNECT);
#endif
wifiManager.setConfigPortalTimeout(WM_PORTALTIMEOUT);
//Revert to STA if wifimanager times out as otherwise APA is left on.
strcpy(wmName, WM_NAME);
strcat(wmName, macAddr.c_str());
wifiManager.autoConnect(wmName, WM_PASSWORD);
WiFi.mode(WIFI_STA);
return 1;
}
#if SETUP_FILESYS == 1
void initFS() {
if(!FILESYS.begin()) {
Serial.println(F("No SIFFS found. Format it"));
if(FILESYS.format()) {
FILESYS.begin();
} else {
Serial.println(F("No SIFFS found. Format it"));
}
} else {
Serial.println(F("FILESYS file list"));
Dir dir = FILESYS.openDir("/");
while (dir.next()) {
Serial.print(dir.fileName());
Serial.print(F(" - "));
Serial.println(dir.fileSize());
}
}
}
String getContentType(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){
bool ret = false;
FILECMD_START
Serial.printf_P(PSTR("handleFileRead: %s\r\n"), path.c_str());
if(path.endsWith("/")) path += "index.htm";
String contentType = getContentType(path);
String pathWithGz = path + ".gz";
if(FILESYS.exists(pathWithGz) || FILESYS.exists(path)){
if(FILESYS.exists(pathWithGz))
path += ".gz";
File file = FILESYS.open(path, "r");
size_t sent = server.streamFile(file, contentType);
file.close();
ret = true;
}
FILECMD_END
return ret;
}
void handleFileUpload(){
if(server.uri() != "/edit") return;
HTTPUpload& upload = server.upload();
if(upload.status == UPLOAD_FILE_START){
String filename = upload.filename;
if(!filename.startsWith("/")) filename = "/"+filename;
Serial.printf_P(PSTR("handleFileUpload Name: %s\r\n"), filename.c_str());
FILECMD_START
fsUploadFile = FILESYS.open(filename, "w");
FILECMD_END
filename = String();
} else if(upload.status == UPLOAD_FILE_WRITE){
Serial.printf_P(PSTR("handleFileUpload Data: %d\r\n"), upload.currentSize);
if(fsUploadFile) {
FILECMD_START
fsUploadFile.write(upload.buf, upload.currentSize);
FILECMD_END
}
} else if(upload.status == UPLOAD_FILE_END){
if(fsUploadFile) {
FILECMD_START
fsUploadFile.close();
FILECMD_END
}
Serial.printf_P(PSTR("handleFileUpload Size: %d\r\n"), upload.totalSize);
}
}
void handleFileDelete(){
if(server.args() == 0) return server.send(500, "text/plain", "BAD ARGS");
String path = server.arg(0);
Serial.printf_P(PSTR("handleFileDelete: %s\r\n"),path.c_str());
if(path == "/")
return server.send(500, "text/plain", "BAD PATH");
FILECMD_START
if(!FILESYS.exists(path))
return server.send(404, "text/plain", "FileNotFound");
FILESYS.remove(path);
FILECMD_END
server.send(200, "text/plain", "");
path = String();
}
void handleFileCreate(){
String status = "";
int ret;
if(server.args() == 0)
return server.send(500, "text/plain", "BAD ARGS");
String path = server.arg(0);
Serial.printf_P(PSTR("handleFileCreate: %s\r\n"),path.c_str());
if(path == "/")
return server.send(500, "text/plain", "BAD PATH");
FILECMD_START;
if(SPIFFS.exists(path)) {
status = "FILE EXISTS";
ret = 500;
} else {
File file = SPIFFS.open(path, "w");
if(file) {
file.close();
ret = 200;
} else {
status = "CREATE FAILED";
ret = 500;
}
}
FILECMD_END;
server.send(ret, "text/plain", status);
}
void handleFileList() {
if(!server.hasArg("dir")) {server.send(500, "text/plain", "BAD ARGS"); return;}
String path = server.arg("dir");
Serial.printf_P(PSTR("handleFileList: %s\r\n"),path.c_str());
FILECMD_START
Dir dir = FILESYS.openDir(path);
path = String();
String output = "[";
while(dir.next()){
File entry = dir.openFile("r");
if (output != "[") output += ',';
bool isDir = false;
output += "{\"type\":\"";
output += (isDir)?"dir":"file";
output += "\",\"name\":\"";
output += String(entry.name()).substring(1);
output += "\"}";
entry.close();
}
output += "]";
FILECMD_END
server.send(200, "text/json", output);
}
void handleMinimalUpload() {
char temp[700];
snprintf ( temp, 700,
"<!DOCTYPE html>\
<html>\
<head>\
<title>ESP8266 Upload</title>\
<meta charset=\"utf-8\">\
<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
</head>\
<body>\
<form action=\"/edit\" method=\"post\" enctype=\"multipart/form-data\">\
<input type=\"file\" name=\"data\">\
<input type=\"text\" name=\"path\" value=\"/\">\
<button>Upload</button>\
</form>\
</body>\
</html>"
);
server.send ( 200, "text/html", temp );
}
#endif
/*
Set up
*/
extern void setupStart();
extern void loadConfig();
extern void extraHandlers();
extern void setupEnd();
void handleFileSysFormat() {
Serial.println(F("format start"));
FILECMD_START
FILESYS.format();
FILECMD_END
Serial.println(F("format complete"));
server.send(200, "text/json", "format complete");
}
void setup() {
defaultIO();
Serial.begin(115200);
#ifdef SETUP_START
setupStart();
#endif
#if SETUP_FILESYS == 1
Serial.println(F("Set up filing system"));
initFS();
#endif
macAddr = WiFi.macAddress();
macAddr.replace(":","");
Serial.println(macAddr);
#ifdef CONFIG_FILE
loadConfig();
#endif
if(setupWifi) {
Serial.println(F("Set up Wifi services"));
wifiConnect(0);
//Update service
MDNS.begin(host.c_str());
httpUpdater.setup(&server, update_path, update_username, update_password);
#ifdef SETUP_SERVER
Serial.println(F("Set up web server"));
server.on("/format", handleFileSysFormat);
#if SETUP_FILESYS == 1
//Simple upload
server.on("/upload", handleMinimalUpload);
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 File System
server.onNotFound([](){if(!handleFileRead(server.uri())) server.send(404, "text/plain", "FileNotFound");});
#endif
#ifdef SETUP_START
extraHandlers();
#endif
server.begin();
#endif
MDNS.addService("http", "tcp", 80);
}
#ifdef SETUP_END
setupEnd();
#endif
Serial.println(F("Set up complete"));
}