-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathwebserver.cpp
649 lines (607 loc) · 21.1 KB
/
webserver.cpp
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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
// ESP8266 Wordclock
// Copyright (C) 2016 Thoralt Franz, https://github.com/thoralt
//
// This module encapsulates a small webserver. It replies to requests on port 80
// and triggers actions, manipulates configuration attributes or serves files
// from the internal flash file system.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include <Arduino.h>
#include <FS.h>
#include <ArduinoJson.h>
#include "ledfunctions.h"
#include "brightness.h"
#include "webserver.h"
#include "ntp.h"
//---------------------------------------------------------------------------------------
// global instance
//---------------------------------------------------------------------------------------
WebServerClass WebServer = WebServerClass();
//---------------------------------------------------------------------------------------
// WebServerClass
//
// Constructor, currently empty
//
// -> --
// <- --
//---------------------------------------------------------------------------------------
WebServerClass::WebServerClass()
{
}
//---------------------------------------------------------------------------------------
// ~WebServerClass
//
// Destructor, removes allocated web server object
//
// -> --
// <- --
//---------------------------------------------------------------------------------------
WebServerClass::~WebServerClass()
{
if (this->server)
delete this->server;
}
//---------------------------------------------------------------------------------------
// begin
//
// Sets up internal handlers and starts the server at port 80
//
// -> --
// <- --
//---------------------------------------------------------------------------------------
void WebServerClass::begin()
{
SPIFFS.begin();
this->server = new ESP8266WebServer(80);
this->server->on("/setcolor", std::bind(&WebServerClass::handleSetColor, this));
this->server->on("/info", std::bind(&WebServerClass::handleInfo, this));
this->server->on("/saveconfig", std::bind(&WebServerClass::handleSaveConfig, this));
this->server->on("/loadconfig", std::bind(&WebServerClass::handleLoadConfig, this));
this->server->on("/setheartbeat", std::bind(&WebServerClass::handleSetHeartbeat, this));
this->server->on("/getheartbeat", std::bind(&WebServerClass::handleGetHeartbeat, this));
this->server->on("/getcolors", std::bind(&WebServerClass::handleGetColors, this));
this->server->on("/getntpserver", std::bind(&WebServerClass::handleGetNtpServer, this));
this->server->on("/setntpserver", std::bind(&WebServerClass::handleSetNtpServer, this));
this->server->on("/h", std::bind(&WebServerClass::handleH, this));
this->server->on("/m", std::bind(&WebServerClass::handleM, this));
this->server->on("/r", std::bind(&WebServerClass::handleR, this));
this->server->on("/g", std::bind(&WebServerClass::handleG, this));
this->server->on("/b", std::bind(&WebServerClass::handleB, this));
this->server->on("/brightness", std::bind(&WebServerClass::handleSetBrightness, this));
this->server->on("/getadc", std::bind(&WebServerClass::handleGetADC, this));
this->server->on("/setmode", std::bind(&WebServerClass::handleSetMode, this));
this->server->on("/getmode", std::bind(&WebServerClass::handleGetMode, this));
this->server->on("/settimezone", std::bind(&WebServerClass::handleSetTimeZone, this));
this->server->on("/gettimezone", std::bind(&WebServerClass::handleGetTimeZone, this));
this->server->on("/debug", std::bind(&WebServerClass::handleDebug, this));
this->server->onNotFound(std::bind(&WebServerClass::handleNotFound, this));
this->server->begin();
}
//---------------------------------------------------------------------------------------
// process
//
// Must be called repeatedly from main loop
//
// ->
// <- --
//---------------------------------------------------------------------------------------
void WebServerClass::process()
{
this->server->handleClient();
}
//---------------------------------------------------------------------------------------
// serveFile
//
// Looks up a given file name in internal flash file system, streams the file if found
//
// -> path: name of the file; "index.html" will be added if name ends with "/"
// <- true: file was found and served to client
// false: file not found
//---------------------------------------------------------------------------------------
bool WebServerClass::serveFile(String path)
{
Serial.println("WebServerClass::serveFile(): " + path);
if (path.endsWith("/"))
path += "index.html";
if (SPIFFS.exists(path))
{
File file = SPIFFS.open(path, "r");
this->server->streamFile(file, this->contentType(path));
file.close();
return true;
}
return false;
}
//---------------------------------------------------------------------------------------
// contentType
//
// Returns an HTML content type based on a given file name extension
//
// -> filename: name of the file
// <- HTML content type matching file extension
//---------------------------------------------------------------------------------------
String WebServerClass::contentType(String filename)
{
if (this->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";
}
//---------------------------------------------------------------------------------------
// handleM
//
// Handles the /m request, increments the minutes counter (for testing purposes)
//
// -> --
// <- --
//---------------------------------------------------------------------------------------
extern int h, m;
void WebServerClass::handleM()
{
if(++m>59) m = 0;
this->server->send(200, "text/plain", "OK");
}
//---------------------------------------------------------------------------------------
// handleH
//
// Handles the /h request, increments the hours counter (for testing purposes)
//
// -> --
// <- --
//---------------------------------------------------------------------------------------
void WebServerClass::handleH()
{
if(++h>23) h = 0;
this->server->send(200, "text/plain", "OK");
}
//---------------------------------------------------------------------------------------
// handleR
//
// Handles the /r request, sets LED matrix to all red (for testing purposes)
//
// -> --
// <- --
//---------------------------------------------------------------------------------------
void WebServerClass::handleR()
{
LED.setMode(DisplayMode::red);
this->server->send(200, "text/plain", "OK");
}
//---------------------------------------------------------------------------------------
// handleG
//
// Handles the /g request, sets LED matrix to all green (for testing purposes)
//
// -> --
// <- --
//---------------------------------------------------------------------------------------
void WebServerClass::handleG()
{
LED.setMode(DisplayMode::green);
this->server->send(200, "text/plain", "OK");
}
//---------------------------------------------------------------------------------------
// handleB
//
// Handles the /b request, sets LED matrix to all blue (for testing purposes)
//
// -> --
// <- --
//---------------------------------------------------------------------------------------
void WebServerClass::handleB()
{
LED.setMode(DisplayMode::blue);
this->server->send(200, "text/plain", "OK");
}
void WebServerClass::handleSetBrightness()
{
if(this->server->hasArg("value"))
{
Brightness.brightnessOverride = this->server->arg("value").toInt();
this->server->send(200, "text/plain", "OK");
}
}
void WebServerClass::handleDebug()
{
if(this->server->hasArg("led") &&
this->server->hasArg("r") &&
this->server->hasArg("g") &&
this->server->hasArg("b"))
{
int led = this->server->arg("led").toInt();
int r = this->server->arg("r").toInt();
int g = this->server->arg("g").toInt();
int b = this->server->arg("b").toInt();
if(led < 0) led = 0;
if(led >= NUM_PIXELS) led = NUM_PIXELS - 1;
if(r < 0) r = 0;
if(r > 255) r = 255;
if(g < 0) g = 0;
if(g > 255) g = 255;
if(b < 0) b = 0;
if(b > 255) b = 255;
LED.currentValues[led*3+0] = r;
LED.currentValues[led*3+1] = g;
LED.currentValues[led*3+2] = b;
LED.show();
Config.debugMode = 1;
}
if(this->server->hasArg("clear"))
{
for(int i=0; i<3*NUM_PIXELS; i++) LED.currentValues[i] = 0;
LED.show();
}
if(this->server->hasArg("end"))
{
Config.debugMode = 0;
}
this->server->send(200, "text/plain", "OK");
}
void WebServerClass::handleGetADC()
{
int __attribute__ ((unused)) temp = Brightness.value(); // to trigger A/D conversion
this->server->send(200, "text/plain", String(Brightness.avg));
}
//---------------------------------------------------------------------------------------
// handleSetTimeZone
//
// Handles the /settimezone request. Saves the time zone
//
// -> --
// <- --
//---------------------------------------------------------------------------------------
void WebServerClass::handleSetTimeZone()
{
int newTimeZone = -999;
if(this->server->hasArg("value"))
{
newTimeZone = this->server->arg("value").toInt();
if(newTimeZone < - 12 || newTimeZone > 14)
{
this->server->send(400, "text/plain", "ERR");
}
else
{
Config.timeZone = newTimeZone;
Config.save();
NTP.setTimeZone(Config.timeZone);
this->server->send(200, "text/plain", "OK");
}
}
}
//---------------------------------------------------------------------------------------
// handleGetTimeZone
//
// Handles the /gettimezone request, delivers offset to UTC in hours.
//
// -> --
// <- --
//---------------------------------------------------------------------------------------
void WebServerClass::handleGetTimeZone()
{
this->server->send(200, "text/plain", String(Config.timeZone));
}
//---------------------------------------------------------------------------------------
// handleSetMode
//
// Handles the /setmode request. Sets the display mode to one of the allowed values,
// saves it as the new default mode.
//
// -> --
// <- --
//---------------------------------------------------------------------------------------
void WebServerClass::handleSetMode()
{
DisplayMode mode = DisplayMode::invalid;
if(this->server->hasArg("value"))
{
// handle each allowed value for safety
if(this->server->arg("value") == "0") mode = DisplayMode::plain;
if(this->server->arg("value") == "1") mode = DisplayMode::fade;
if(this->server->arg("value") == "2") mode = DisplayMode::flyingLettersVerticalUp;
if(this->server->arg("value") == "3") mode = DisplayMode::flyingLettersVerticalDown;
if(this->server->arg("value") == "4") mode = DisplayMode::explode;
}
if(mode == DisplayMode::invalid)
{
this->server->send(400, "text/plain", "ERR");
}
else
{
LED.setMode(mode);
Config.defaultMode = mode;
Config.save();
this->server->send(200, "text/plain", "OK");
}
}
//---------------------------------------------------------------------------------------
// handleGetMode
//
// Handles the /getmode request and returns the current default display mode.
//
// -> --
// <- --
//---------------------------------------------------------------------------------------
void WebServerClass::handleGetMode()
{
int mode = 0;
switch(Config.defaultMode)
{
case DisplayMode::plain:
mode = 0; break;
case DisplayMode::fade:
mode = 1; break;
case DisplayMode::flyingLettersVerticalUp:
mode = 2; break;
case DisplayMode::flyingLettersVerticalDown:
mode = 3; break;
case DisplayMode::explode:
mode = 4; break;
default:
mode = 0; break;
}
this->server->send(200, "text/plain", String(mode));
}
//---------------------------------------------------------------------------------------
// handleNotFound
//
// Handles all requests not bound to other handlers, tries to serve a file if found in
// flash, responds with 404 otherwise
//
// -> --
// <- --
//---------------------------------------------------------------------------------------
void WebServerClass::handleNotFound()
{
// first, try to serve the requested file from flash
if (!serveFile(this->server->uri()))
{
// create 404 message if no file was found for this URI
String message = "File Not Found\n\n";
message += "URI: ";
message += this->server->uri();
message += "\nMethod: ";
message += (this->server->method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += this->server->args();
message += "\n";
for (uint8_t i = 0; i < this->server->args(); i++)
{
message += " " + this->server->argName(i) + ": "
+ this->server->arg(i) + "\n";
}
this->server->send(404, "text/plain", message);
}
}
//---------------------------------------------------------------------------------------
// handleGetNtpServer
//
// Delivers the currently configured NTP server IP address
//
// -> --
// <- --
//---------------------------------------------------------------------------------------
void WebServerClass::handleGetNtpServer()
{
this->server->send(200, "application/json", Config.ntpserver.toString());
}
//---------------------------------------------------------------------------------------
// handleSetNtpServer
//
// Sets a new IP address for the NTP client
//
// -> --
// <- --
//---------------------------------------------------------------------------------------
void WebServerClass::handleSetNtpServer()
{
if (this->server->hasArg("ip"))
{
IPAddress ip;
if (ip.fromString(this->server->arg("ip")))
{
// set IP address in config
Config.ntpserver = ip;
Config.save();
// set IP address in client
NTP.setServer(ip);
}
}
this->server->send(200, "application/json", "OK");
}
//---------------------------------------------------------------------------------------
// handleInfo
//
// Handles requests to "/info", replies with JSON structure containing system status
//
// -> --
// <- --
//---------------------------------------------------------------------------------------
void WebServerClass::handleInfo()
{
StaticJsonBuffer<512> jsonBuffer;
char buf[512];
JsonObject& json = jsonBuffer.createObject();
json["heap"] = ESP.getFreeHeap();
json["sketchsize"] = ESP.getSketchSize();
json["sketchspace"] = ESP.getFreeSketchSpace();
json["cpufrequency"] = ESP.getCpuFreqMHz();
json["chipid"] = ESP.getChipId();
json["sdkversion"] = ESP.getSdkVersion();
json["bootversion"] = ESP.getBootVersion();
json["bootmode"] = ESP.getBootMode();
json["flashid"] = ESP.getFlashChipId();
json["flashspeed"] = ESP.getFlashChipSpeed();
json["flashsize"] = ESP.getFlashChipRealSize();
json["resetreason"] = ESP.getResetReason();
json["resetinfo"] = ESP.getResetInfo();
// switch(LED.getMode())
// {
// case DisplayMode::plain:
// json["mode"] = "plain"; break;
// case DisplayMode::fade:
// json["mode"] = "fade"; break;
// case DisplayMode::flyingLettersVertical:
// json["mode"] = "flyingLettersVertical"; break;
// case DisplayMode::matrix:
// json["mode"] = "matrix"; break;
// case DisplayMode::heart:
// json["mode"] = "heart"; break;
// case DisplayMode::stars:
// json["mode"] = "stars"; break;
// case DisplayMode::red:
// json["mode"] = "red"; break;
// case DisplayMode::green:
// json["mode"] = "green"; break;
// case DisplayMode::blue:
// json["mode"] = "blue"; break;
// case DisplayMode::yellowHourglass:
// json["mode"] = "yellowHourglass"; break;
// case DisplayMode::greenHourglass:
// json["mode"] = "greenHourglass"; break;
// case DisplayMode::update:
// json["mode"] = "update"; break;
// case DisplayMode::updateComplete:
// json["mode"] = "updateComplete"; break;
// case DisplayMode::updateError:
// json["mode"] = "updateError"; break;
// case DisplayMode::wifiManager:
// json["mode"] = "wifiManager"; break;
// default:
// json["mode"] = "unknown"; break;
// }
json.printTo(buf, sizeof(buf));
this->server->send(200, "application/json", buf);
}
//---------------------------------------------------------------------------------------
// extractColor
//
// Converts the given web server argument to a color struct
// -> argName: Name of the web server argument
// result: Pointer to palette_entry struct to receive result
// <- --
//---------------------------------------------------------------------------------------
void WebServerClass::extractColor(String argName, palette_entry& result)
{
char c[3];
if (this->server->hasArg(argName) && this->server->arg(argName).length() == 6)
{
String color = this->server->arg(argName);
color.substring(0, 2).toCharArray(c, sizeof(c));
result.r = strtol(c, NULL, 16);
color.substring(2, 4).toCharArray(c, sizeof(c));
result.g = strtol(c, NULL, 16);
color.substring(4, 6).toCharArray(c, sizeof(c));
result.b = strtol(c, NULL, 16);
}
}
//---------------------------------------------------------------------------------------
// handleSetColor
//
// Handles the "/setcolor" request, expects arguments:
// /setcolor?fg=xxxxxx&bg=yyyyyy&s=zzzzzz
// with xxxxxx, yyyyyy and zzzzzz being hexadecimal HTML colors (without leading '#')
//
// -> --
// <- --
//---------------------------------------------------------------------------------------
void WebServerClass::handleSetColor()
{
this->extractColor("fg", Config.fg);
this->extractColor("bg", Config.bg);
this->extractColor("s", Config.s);
this->server->send(200, "text/plain", "OK");
Config.saveDelayed();
}
//---------------------------------------------------------------------------------------
// handleSaveConfig
//
// Saves the current configuration to EEPROM
//
// -> --
// <- --
//---------------------------------------------------------------------------------------
void WebServerClass::handleSaveConfig()
{
Config.save();
this->server->send(200, "text/plain", "OK");
}
//---------------------------------------------------------------------------------------
// handleLoadConfig
//
// Loads the current configuration from EEPROM
//
// -> --
// <- --
//---------------------------------------------------------------------------------------
void WebServerClass::handleLoadConfig()
{
Config.load();
this->server->send(200, "text/plain", "OK");
}
//---------------------------------------------------------------------------------------
// handleSetHeartbeat
//
// Sets or resets the heartbeat flag in the configuration based on argument "state"
//
// -> --
// <- --
//---------------------------------------------------------------------------------------
void WebServerClass::handleSetHeartbeat()
{
Config.heartbeat = (this->server->hasArg("value") && this->server->arg("value") == "1");
Config.save();
this->server->send(200, "text/plain", "OK");
}
//---------------------------------------------------------------------------------------
// handleGetHeartbeat
//
// Returns the state of the heartbeat flag.
//
// -> --
// <- --
//---------------------------------------------------------------------------------------
void WebServerClass::handleGetHeartbeat()
{
if(Config.heartbeat) this->server->send(200, "text/plain", "1");
else this->server->send(200, "text/plain", "0");
}
//---------------------------------------------------------------------------------------
// handleGetColors
//
// Outputs the currently active colors as comma separated list for background, foreground
// and seconds color with 3 values each (red, green, blue)
//
// -> --
// <- --
//---------------------------------------------------------------------------------------
void WebServerClass::handleGetColors()
{
String message = String(Config.bg.r) + "," + String(Config.bg.g) + ","
+ String(Config.bg.b) + "," + String(Config.fg.r) + ","
+ String(Config.fg.g) + "," + String(Config.fg.b) + ","
+ String(Config.s.r) + "," + String(Config.s.g) + ","
+ String(Config.s.b);
this->server->send(200, "text/plain", message);
}