-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path03_WebServerDef.ino
429 lines (398 loc) · 16.2 KB
/
03_WebServerDef.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
void setMainPageVars() {
mainPageVars = String("<data><clientid>")
+ clientId + String("</clientid><repeat>")
+ String(repeatDefault) + String("</repeat><buzzer>")
+ String(buzzerDefault) + String("</buzzer><delay>")
+ String(scrollDelayDefault) + String("</delay><brightness>")
+ String(ledBrightnessDefault) + String("</brightness><version>")
+ String(version) + String("</version></data>");
}
void setMqttPageVars() {
mqttPageVars = String("<data><clientid>")
+ clientId + String("</clientid><mqttonoff>")
+ String(mqttOnOff) + String("</mqttonoff><mqttanonymous>")
+ String(mqttAnonymous) + String("</mqttanonymous><mqttalert>")
+ String(mqttAlert) + String("</mqttalert><mqttusername>")
+ String(mqttUsername) + String("</mqttusername><mqttserveraddress>")
+ String(mqttServerAddress) + String("</mqttserveraddress><mqttserverport>")
+ String(mqttServerPort) + String("</mqttserverport><mqtttopicprefix>")
+ String(mqttTopicPrefix) + String("</mqtttopicprefix><version>")
+ String(version) + String("</version></data>");
}
void setChangeCredVars() {
changeCredVars = String("<data><clientid>")
+ clientId + String("</clientid><username>")
+ String(web_username) + String("</username><version>")
+ String(version) + String("</version></data>");
}
void setUpdateVars() {
updateVars = String("<data><clientid>")
+ clientId + String("</clientid><version>")
+ String(version) + String("</version></data>");
}
// Loads the configuration from a file
void loadConfiguration(const char *webConfigFile, webConfigObj &webConfig) {
File file = LittleFS.open(webConfigFile, "r");
if (!file) {
Serial.println("Failed to open data file");
return;
}
// Allocate a temporary JsonDocument
// Don't forget to change the capacity to match your requirements.
// Use arduinojson.org/v6/assistant to compute the capacity.
StaticJsonDocument<512> doc;
// Deserialize the JSON document
DeserializationError error = deserializeJson(doc, file);
if (error)
Serial.println(F("Failed to read file, using default configuration"));
// Copy values from the JsonDocument to the webConfig
strlcpy(webConfig.usernameWebHolder, // <- destination
doc["usernameWebHolder"], // <- source
sizeof(webConfig.usernameWebHolder)); // <- destination's capacity
strlcpy(webConfig.passwordWebHolder, // <- destination
doc["passwordWebHolder"], // <- source
sizeof(webConfig.passwordWebHolder)); // <- destination's capacity
// Close the file (Curiously, File's destructor doesn't close the file)
file.close();
}
// Saves the configuration to a file
void saveConfiguration(const char *webConfigFile, const webConfigObj &webConfig) {
// Delete existing file, otherwise the configuration is appended to the file
//LittleFS.remove(webConfigFile);
// Open file for writing
File file = LittleFS.open(webConfigFile, "w");
if (!file) {
Serial.println("Failed to open config file for writing");
return;
}
// Allocate a temporary JsonDocument
// Don't forget to change the capacity to match your requirements.
// Use arduinojson.org/assistant to compute the capacity.
StaticJsonDocument<512> doc;
// Set the values in the document
doc["usernameWebHolder"] = webConfig.usernameWebHolder;
doc["passwordWebHolder"] = webConfig.passwordWebHolder;
// Serialize JSON to file
if (serializeJson(doc, file) == 0) {
Serial.println(F("Failed to write to file"));
}
// Close the file
file.close();
}
// Prints the content of a file to the Serial
void printWebFile(const char *webConfigFile) {
// Open file for reading
File file = LittleFS.open(webConfigFile, "r");
if (!file) {
Serial.println("Failed to open data file");
return;
}
// Extract each characters by one by one
while (file.available()) {
Serial.print((char)file.read());
}
Serial.println();
// Close the file
file.close();
}
//change login credentials and store into config file
void changeWebLoginCredentials() {
//set username and password from webpage to config object
strlcpy(webConfig.usernameWebHolder, newWebUsername, sizeof(webConfig.usernameWebHolder));
strlcpy(webConfig.passwordWebHolder, newWebPassword, sizeof(webConfig.passwordWebHolder));
//save username and password from config object to config file
saveConfiguration(webConfigFile, webConfig);
//set the http/https credentials to the new password
strlcpy(web_username, webConfig.usernameWebHolder, sizeof(web_username));
strlcpy(web_password, webConfig.passwordWebHolder, sizeof(web_password));
// Dump config file
PRINTS("Username and Password changed\nPrinting web user config file:\n");
printWebFile(webConfigFile);
}
void initWebStoreConfig() {
//load config stored in config file
Serial.println(F("Loading web configuration...\n"));
loadConfiguration(webConfigFile, webConfig);
//if no username is defined in config file store default
if ((webConfig.usernameWebHolder != NULL) && (webConfig.usernameWebHolder[0] == '\0')) {
PRINT("no username set, setting default username: ", web_username);
strlcpy(webConfig.usernameWebHolder, web_username, sizeof(webConfig.usernameWebHolder));
saveWebConfigAtStart = true;
}
//if no password is defined in config file store default
if ((webConfig.passwordWebHolder != NULL) && (webConfig.passwordWebHolder[0] == '\0')) {
PRINTS("\n")
PRINT("no password set, setting default password: ", web_password);
strlcpy(webConfig.passwordWebHolder, web_password, sizeof(webConfig.passwordWebHolder));
saveWebConfigAtStart = true;
}
PRINTS("\n")
//set http/https server to config file defined values or defined default
strlcpy(web_username, webConfig.usernameWebHolder, sizeof(web_username));
strlcpy(web_password, webConfig.passwordWebHolder, sizeof(web_password));
// Create configuration file
if (saveWebConfigAtStart) {
Serial.println(F("Saving web user configuration..."));
saveConfiguration(webConfigFile, webConfig);
}
// Dump config file
Serial.println(F("Print web user config file...\n"));
printWebFile(webConfigFile);
}
//################################ START OF SPECIFIC HTTP SERVER FUNCTIONS ################################//
void showWebpageHttp() {
String s = MAIN_page; //Read HTML contents
serverHttp.send(200, "text/html", s); //Send web page
}
void showChangeCredentialsHttp() {
String s = CHANGECREDENTIALS_page; //Read HTML contents
serverHttp.send(200, "text/html", s); //Send web page
}
void usernamePasswordHttp() {
String message = "\nReceived request:\n";
message += "URI: ";
message += serverHttp.uri();
message += "\nMethod: ";
message += (serverHttp.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += serverHttp.args();
message += "\n";
for (uint8_t i = 0; i < serverHttp.args(); i++) {
message += " " + serverHttp.argName(i) + ": " + serverHttp.arg(i) + "\n";
if (serverHttp.argName(i) == "Username") {
serverHttp.arg(i).toCharArray(newWebUsername, STDSIZE);
newWebUsernameAvailable = true;
}
if (serverHttp.argName(i) == "Password") {
serverHttp.arg(i).toCharArray(newWebPassword, STDSIZE);
newWebPasswordAvailable = true;
}
}
Serial.println(message);
}
void showChangeMqttConfigHttp() {
String s = CHANGEMQTTCONFIG_page; //Read HTML contents
serverHttp.send(200, "text/html", s); //Send web page
}
void onMqttConfigChangeHttp() {
String message = "\nReceived request:\n";
message += "URI: ";
message += serverHttp.uri();
message += "\nMethod: ";
message += (serverHttp.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += serverHttp.args();
message += "\n";
for (uint8_t i = 0; i < serverHttp.args(); i++) {
message += " " + serverHttp.argName(i) + ": " + serverHttp.arg(i) + "\n";
if (serverHttp.argName(i) == "MQTTONOFF") {
serverHttp.arg(i).toCharArray(newMqttOnOff, STDSIZE);
if ((newMqttOnOff != NULL) && (newMqttOnOff[0] == '\0')) {
newMqttOnOffAvailable = false;
} else { newMqttOnOffAvailable = true; }
}
if (serverHttp.argName(i) == "MQTTANONYMOUS") {
serverHttp.arg(i).toCharArray(newMqttAnonymous, STDSIZE);
if ((newMqttAnonymous != NULL) && (newMqttAnonymous[0] == '\0')) {
newMqttAnonymousAvailable = false;
} else { newMqttAnonymousAvailable = true; }
}
if (serverHttp.argName(i) == "MQTTALERT") {
serverHttp.arg(i).toCharArray(newMqttAlert, STDSIZE);
if ((newMqttAlert != NULL) && (newMqttAlert[0] == '\0')) {
newMqttAlertAvailable = false;
} else { newMqttAlertAvailable = true; }
}
if (serverHttp.argName(i) == "MQTTUSERNAME") {
serverHttp.arg(i).toCharArray(newMqttUsername, STDSIZE);
if ((newMqttUsername != NULL) && (newMqttUsername[0] == '\0')) {
newMqttUsernameAvailable = false;
} else { newMqttUsernameAvailable = true; }
}
if (serverHttp.argName(i) == "MQTTPASSWORD") {
serverHttp.arg(i).toCharArray(newMqttPassword, STDSIZE);
if ((newMqttPassword != NULL) && (newMqttPassword[0] == '\0')) {
newMqttPasswordAvailable = false;
} else { newMqttPasswordAvailable = true; }
}
if (serverHttp.argName(i) == "MQTTSERVERADDRESS") {
serverHttp.arg(i).toCharArray(newMqttServerAddress, STDSIZE);
if ((newMqttServerAddress != NULL) && (newMqttServerAddress[0] == '\0')) {
newMqttServerAddressAvailable = false;
} else { newMqttServerAddressAvailable = true; }
}
if (serverHttp.argName(i) == "MQTTSERVERPORT") {
serverHttp.arg(i).toCharArray(newMqttServerPort, STDSIZE);
if ((newMqttServerPort != NULL) && (newMqttServerPort[0] == '\0')) {
newMqttServerPortAvailable = false;
} else { newMqttServerPortAvailable = true; }
}
if (serverHttp.argName(i) == "MQTTTOPICPREFIX") {
serverHttp.arg(i).toCharArray(newMqttTopicPrefix, STDSIZE);
if ((newMqttTopicPrefix != NULL) && (newMqttTopicPrefix[0] == '\0')) {
newMqttTopicPrefixAvailable = false;
} else { newMqttTopicPrefixAvailable = true; }
}
}
Serial.println(message);
}
void onNotFoundUriHttp() {
serverHttp.send(404, "text/plain", "404: Not found"); // Send HTTP status 404 (Not Found) when there's no handler for the URI in the request
}
void httpWebDirDef(){
serverHttp.on("/", []() {
if (!serverHttp.authenticate(web_username, web_password)) {
return serverHttp.requestAuthentication();
}
showWebpageHttp();
});
serverHttp.on("/mainpagevars", []() {
if (!serverHttp.authenticate(web_username, web_password)) {
return serverHttp.requestAuthentication();
}
setMainPageVars();
serverHttp.send(200, "text/plane", mainPageVars);
});
serverHttp.on("/changecredvars", []() {
if (!serverHttp.authenticate(web_username, web_password)) {
return serverHttp.requestAuthentication();
}
setChangeCredVars();
serverHttp.send(200, "text/plane", changeCredVars);
});
serverHttp.on("/updatevars", []() {
if (!serverHttp.authenticate(web_username, web_password)) {
return serverHttp.requestAuthentication();
}
setUpdateVars();
serverHttp.send(200, "text/plane", updateVars);
});
serverHttp.on("/arg", []() {
if (!serverHttp.authenticate(web_username, web_password)) {
return serverHttp.requestAuthentication();
}
onMessageCallHttp();
});
serverHttp.on("/api", HTTP_POST, [](){
if (!serverHttp.authenticate(web_username, web_password)) {
return serverHttp.requestAuthentication();
}
PRINTS("\nHTTP JSON Message Arrived!\nHTTP Message: ");
onMessageCallJson(serverHttp.arg("plain").c_str());
serverHttp.send(204,"");
});
serverHttp.on("/changeuserpass", [](){
if (!serverHttp.authenticate(web_username, web_password)) {
return serverHttp.requestAuthentication();
}
showChangeCredentialsHttp();
});
serverHttp.on("/changecredentials", [](){
if (!serverHttp.authenticate(web_username, web_password)) {
return serverHttp.requestAuthentication();
}
usernamePasswordHttp();
changeWebLoginCredentials();
serverHttp.sendHeader("Connection", "close");
serverHttp.send(200, "text/html", APPLYUSERPASS_page);
});
serverHttp.on("/changemqttconfig", [](){
if (!serverHttp.authenticate(web_username, web_password)) {
return serverHttp.requestAuthentication();
}
showChangeMqttConfigHttp();
});
serverHttp.on("/mqttpagevars", []() {
if (!serverHttp.authenticate(web_username, web_password)) {
return serverHttp.requestAuthentication();
}
setMqttPageVars();
serverHttp.send(200, "text/plane", mqttPageVars);
});
serverHttp.on("/applymqttconfig", [](){
if (!serverHttp.authenticate(web_username, web_password)) {
return serverHttp.requestAuthentication();
}
onMqttConfigChangeHttp();
changeMqttConfig();
serverHttp.sendHeader("Connection", "close");
serverHttp.send(200, "text/html", APPLYMQTTCONFIG_page);
});
serverHttp.on("/update", HTTP_GET, []() {
if (!serverHttp.authenticate(web_username, web_password)) {
return serverHttp.requestAuthentication();
}
serverHttp.sendHeader("Connection", "close");
serverHttp.send(200, "text/html", UPDATE_page);
});
serverHttp.on("/reboot", HTTP_GET, []() {
if (!serverHttp.authenticate(web_username, web_password)) {
return serverHttp.requestAuthentication();
}
serverHttp.sendHeader("Connection", "close");
serverHttp.send(200, "text/html", REBOOT_page);
delay(2000);
rebootDevice();
});
serverHttp.on("/factoryreset", HTTP_GET, []() {
if (!serverHttp.authenticate(web_username, web_password)) {
return serverHttp.requestAuthentication();
}
serverHttp.sendHeader("Connection", "close");
serverHttp.send(200, "text/html", FACTORYRESET_page);
factoryReset();
});
serverHttp.on("/submitupdate", HTTP_POST, []() {
if (!serverHttp.authenticate(web_username, web_password)) {
return serverHttp.requestAuthentication();
}
serverHttp.sendHeader("Connection", "close");
serverHttp.send(200, "text/html", (Update.hasError()) ? SUBMITUPDATEFAIL_page : SUBMITUPDATEOK_page);
}, []() {
if (!serverHttp.authenticate(web_username, web_password)) {
return serverHttp.requestAuthentication();
}
HTTPUpload& upload = serverHttp.upload();
if (upload.status == UPLOAD_FILE_START) {
Serial.setDebugOutput(true);
WiFiUDP::stopAll();
Serial.printf("Update: %s\n", upload.filename.c_str());
uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
if (!Update.begin(maxSketchSpace)) { //start with max available size
Update.printError(Serial);
}
}
else if (upload.status == UPLOAD_FILE_WRITE) {
if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
Update.printError(Serial);
}
}
else if (upload.status == UPLOAD_FILE_END) {
if (Update.end(true)) { //true to set the size to the current progress
Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
serverHttp.send(200, "text/html", SUBMITUPDATESUCCESS_page);
delay(1000);
ESP.restart();
}
else {
Update.printError(Serial);
}
Serial.setDebugOutput(false);
}
yield();
});
serverHttp.onNotFound([]() {
if (!serverHttp.authenticate(web_username, web_password)) {
return serverHttp.requestAuthentication();
}
onNotFoundUriHttp();
});
// Start the http server
serverHttp.begin();
PRINTS("HTTP Server started on port 80\n");
Serial.printf("You can update firmware from the browser opening! -> Open http://%s/update in your browser\n\n", assignedIP);
}
void handleHttpServer() {
serverHttp.handleClient();
}
//################################ END OF SPECIFIC HTTP SERVER FUNCTIONS ################################//