This repository has been archived by the owner on Jan 11, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 48
/
WebServer.cpp
222 lines (194 loc) · 6.96 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
/*
Basecamp - ESP32 library to simplify the basics of IoT projects
Written by Merlin Schumacher ([email protected]) for c't magazin für computer technik (https://www.ct.de)
Licensed under GPLv3. See LICENSE for details.
*/
#include "WebServer.hpp"
namespace {
template<typename NAMEVALUETYPE>
void debugPrint(std::ostream &stream, NAMEVALUETYPE &nameAndValue)
{
stream << nameAndValue->name().c_str() << ": " << nameAndValue->value().c_str();
}
}
WebServer::WebServer()
: events("/events")
, server(80)
{
server.addHandler(&events);
#ifdef BASECAMP_USEDNS
#ifdef DNSServer_h
server.addHandler(new CaptiveRequestHandler()).setFilter(ON_AP_FILTER);
#endif
#endif
}
void WebServer::begin(Configuration &configuration, std::function<void()> submitFunc) {
SPIFFS.begin();
server.on("/" , HTTP_GET, [](AsyncWebServerRequest * request)
{
AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", index_htm_gz, index_htm_gz_len);
response->addHeader("Content-Encoding", "gzip");
request->send(response);
});
server.on("/basecamp.css" , HTTP_GET, [](AsyncWebServerRequest * request)
{
AsyncWebServerResponse *response = request->beginResponse_P(200, "text/css", basecamp_css_gz, basecamp_css_gz_len);
response->addHeader("Content-Encoding", "gzip");
request->send(response);
});
server.on("/basecamp.js" , HTTP_GET, [](AsyncWebServerRequest * request)
{
AsyncWebServerResponse *response = request->beginResponse_P(200, "text/js", basecamp_js_gz, basecamp_js_gz_len);
response->addHeader("Content-Encoding", "gzip");
request->send(response);
});
server.on("/logo.svg" , HTTP_GET, [](AsyncWebServerRequest * request)
{
AsyncWebServerResponse *response = request->beginResponse_P(200, "image/svg+xml", logo_svg_gz, logo_svg_gz_len);
response->addHeader("Content-Encoding", "gzip");
request->send(response);
});
server.on("/data.json" , HTTP_GET, [&configuration, this](AsyncWebServerRequest * request)
{
AsyncJsonResponse *response = new AsyncJsonResponse();
DynamicJsonBuffer _jsonBuffer;
JsonObject &_jsonData = response->getRoot();
JsonArray &elements = _jsonData.createNestedArray("elements");
for (const auto &interfaceElement : interfaceElements)
{
JsonObject &element = elements.createNestedObject();
JsonObject &attributes = element.createNestedObject("attributes");
element["element"] = _jsonBuffer.strdup(interfaceElement.element);
element["id"] = _jsonBuffer.strdup(interfaceElement.id);
element["content"] = _jsonBuffer.strdup(interfaceElement.content);
element["parent"] = _jsonBuffer.strdup(interfaceElement.parent);
for (const auto &attribute : interfaceElement.attributes)
{
attributes[attribute.first] = String{attribute.second};
}
if (interfaceElement.getAttribute("data-config").length() != 0)
{
if (interfaceElement.getAttribute("type")=="password")
{
attributes["placeholder"] = "Password unchanged";
attributes["value"] = "";
} else {
attributes["value"] = String{configuration.get(interfaceElement.getAttribute("data-config"))};
}
}
}
#ifdef DEBUG
_jsonData.prettyPrintTo(Serial);
#endif
response->setLength();
// NOTE: AsyncServer.send(ptr* foo) deletes `response` after async send.
// As this is not documented in the header there: thanks for nothing.
request->send(response);
});
server.on("/submitconfig", HTTP_POST, [&configuration, submitFunc, this](AsyncWebServerRequest *request)
{
if (request->params() == 0) {
DEBUG_PRINTLN("Refusing to take over an empty configuration submission.");
request->send(500);
return;
}
debugPrintRequest(request);
for (int i = 0; i < request->params(); i++)
{
AsyncWebParameter *webParameter = request->getParam(i);
if (webParameter->isPost() && webParameter->value().length() != 0)
{
configuration.set(webParameter->name().c_str(), webParameter->value().c_str());
}
}
configuration.save();
request->send(201);
// Only call submitFunc when it has been set to something useful
if( submitFunc ) submitFunc();
});
server.onNotFound([this](AsyncWebServerRequest *request)
{
#ifdef DEBUG
DEBUG_PRINTLN("WebServer request not found: ");
debugPrintRequest(request);
#endif
request->send(404);
});
server.begin();
}
void WebServer::debugPrintRequest(AsyncWebServerRequest *request)
{
#ifdef DEBUG
/**
That AsyncWebServer code uses some strange bit-consstructs instead of enum
class. Also no const getter. As I refuse to bring that code to 21st century,
we have to live with it until someone brave fixes it.
*/
const std::map<WebRequestMethodComposite, std::string> requestMethods{
{ HTTP_GET, "GET" },
{ HTTP_POST, "POST" },
{ HTTP_DELETE, "DELETE" },
{ HTTP_PUT, "PUT" },
{ HTTP_PATCH, "PATCH" },
{ HTTP_HEAD, "HEAD" },
{ HTTP_OPTIONS, "OPTIONS" },
};
std::ostringstream output;
output << "Method: ";
auto found = requestMethods.find(request->method());
if (found != requestMethods.end()) {
output << found->second;
} else {
output << "Unknown (" << static_cast<unsigned int>(request->method()) << ")";
}
output << std::endl;
output << "URL: " << request->url().c_str() << std::endl;
output << "Content-Length: " << request->contentLength() << std::endl;
output << "Content-Type: " << request->contentType().c_str() << std::endl;
output << "Headers: " << std::endl;
for (int i = 0; i < request->headers(); i++) {
auto *header = request->getHeader(i);
output << "\t";
debugPrint(output, header);
output << std::endl;
}
output << "Parameters: " << std::endl;
for (int i = 0; i < request->params(); i++) {
auto *parameter = request->getParam(i);
output << "\t";
if (parameter->isFile()) {
output << "This is a file. FileSize: " << parameter->size() << std::endl << "\t\t";
}
debugPrint(output, parameter);
output << std::endl;
}
Serial.println(output.str().c_str());
#endif
}
void WebServer::addInterfaceElement(const String &id, String element, String content, String parent, String configvariable) {
interfaceElements.emplace_back(id, std::move(element), std::move(content), std::move(parent));
if (configvariable.length() != 0) {
setInterfaceElementAttribute(id, "data-config", std::move(configvariable));
}
}
void WebServer::setInterfaceElementAttribute(const String &id, const String &key, String value)
{
for (auto &element : interfaceElements) {
if (element.getId() == id) {
element.setAttribute(key, std::move(value));
return;
}
}
}
void WebServer::reset() {
interfaceElements.clear();
// We should also reset the server itself, according to documentation, but it will cause a crash.
// It works without reset, if you only configure one server after a reboot. Not sure what happens if you want to reconfigure during runtime.
//server.reset();
//server.addHandler(&events);
//#ifdef BASECAMP_USEDNS
//#ifdef DNSServer_h
//server.addHandler(new CaptiveRequestHandler()).setFilter(ON_AP_FILTER);
//#endif
//#endif
}