-
Notifications
You must be signed in to change notification settings - Fork 40
/
DynamicPage.ino
108 lines (94 loc) · 2.54 KB
/
DynamicPage.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
/*
DynamicPage.ino, Example for the PageBuilder library.
Copyright (c) 2017, Hieromon Ikasamo
https://github.com/Hieromon/PageBuilder
This software is released under the MIT License.
https://opensource.org/licenses/MIT
*/
#if defined(ARDUINO_ARCH_ESP8266)
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#elif defined(ARDUINO_ARCH_ESP32)
#include <WiFi.h>
#include <WebServer.h>
#endif
#include <PageBuilder.h>
// Modify according to your Wi-Fi environment.
#define SSID "wifissid"
#define PSK "wifipassword"
#if defined(ARDUINO_ARCH_ESP8266)
ESP8266WebServer server;
#elif defined(ARDUINO_ARCH_ESP32)
WebServer server;
#endif
PageElement elm;
PageBuilder page;
String currentUri;
// The root page content builder
String rootPage(PageArgument& args) {
return String(F("This is root page."));
}
// The hello page content builder
String helloPage(PageArgument& args) {
return String(F("This is hello page."));
}
// This function creates dynamic web page by each request.
// It is called twice at one time URI request that caused by the structure
// of ESP8266WebServer class.
bool handleAcs(HTTPMethod method, String uri) {
if (uri == currentUri) {
// Page is already prepared.
return true;
} else {
currentUri = uri;
page.clearElements(); // Discards the remains of PageElement.
page.addElement(elm); // Register PageElement for current access.
Serial.println("Request:" + uri);
if (uri == "/") { // for the / page
page.setUri(uri.c_str());
elm.setMold(F(
"<html>"
"<body>"
"<h2>{{ROOT}}</h2>"
"</body>"
"</html>"));
elm.addToken("ROOT", rootPage);
return true;
}
else if (uri == "/hello") { // for the /hello page
page.setUri(uri.c_str());
elm.setMold(F(
"<html>"
"<body>"
"<p style=\"color:Tomato;\">{{HELLO}}</p>"
"</body>"
"</html>"));
elm.addToken("HELLO", helloPage);
return true;
}
else {
return false; // Not found to accessing exception URI.
}
}
}
void setup() {
delay(1000);
Serial.begin(115200);
Serial.println();
WiFi.mode(WIFI_STA);
delay(100);
WiFi.begin(SSID, PSK);
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
delay(100);
}
// Prepare dynamic web page
page.exitCanHandle(handleAcs); // Handles for all requests.
page.insert(server);
// Start web server
server.begin();
Serial.print("http server:");
Serial.println(WiFi.localIP());
}
void loop() {
server.handleClient();
}