forked from alonf/WebControlledSwitch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebServer.cpp
More file actions
278 lines (244 loc) · 9.34 KB
/
Copy pathWebServer.cpp
File metadata and controls
278 lines (244 loc) · 9.34 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
#include "WebServer.h"
#include "Util.h"
#include "WebSettings.h"
#include <algorithm>
using namespace std;
///*static*/ char WebServer::_setupHtmlBuffer[3072]; //for setup html result
WebServer::WebServer(WiFiManagerPtr_t wifiManager, int port, const char *appKey, std::unique_ptr<DeviceSettings> deviceSettings, std::function<bool()> relayStateUpdater) :
_deviceSettings(move(deviceSettings)),
_server(port),
_authorizedUrl(String("/") + appKey),
_relayStateUpdater(relayStateUpdater)
{
_server.on("/", [this]() { HandleError(); });
_server.on((_authorizedUrl + "/view.css").c_str(), [this]() { HandleSendViewCSS(); });
_server.on((_authorizedUrl + "/ap_script.js").c_str(), [this]() { HandleSendAPScript(); });
_server.on((_authorizedUrl + "/aplist.html").c_str(), [this]() { HandleSendAPList(); });
_server.on((_authorizedUrl + "/setup").c_str(), [this]() { HandleSetup(); });
_server.on((_authorizedUrl + "/setconfiguration").c_str(),HTTP_POST, [this]() { HandleSetConfiguration(); });
_server.on((_authorizedUrl + "/resetaccesspoint").c_str(), [this]() { HandleResetAccessPoint(); });
_server.on(_authorizedUrl.c_str(), [this]() { HandleMain(); });
_server.on((_authorizedUrl + "/").c_str(), [this]() { HandleMain(); });
_server.onNotFound([this]() { HandleError(); });
wifiManager->RegisterClient([this](ConnectionStatus status) { UpdateStatus(status); });
}
void WebServer::RegisterCommand(WebCommandPtr_t command)
{
_webCommands.push_back(command);
auto url = String(CreateUrl(command->TriggerUrl()));
_server.on(url.c_str(), [=]() { HandleCommand(command); });
}
void WebServer::SendBackHtml(const String &message)
{
auto html = String("<html><body><h2>") + _header + "</h2>"
+ message + "</body></html>";
_server.send(200,
"text/html",
html.c_str());
}
void WebServer::HandleError()
{
_server.send(401,
"text/plain",
"Unauthorized");
}
void WebServer::HandleMain()
{
auto html = String("<p><h3>The current switch status is ") +
(_relayState ? "on" : "off") + "</h3></p>";
for (auto webCommand : _webCommands)
{
html += String(R"(<p><a href=")") + CreateUrl(webCommand->TriggerUrl()) + String(R"(">)") + webCommand->MenuEntry() + String("</a></p>");
}
html += String(R"(<br/><p><a href=")") + CreateUrl("resetaccesspoint") + String(R"(">Factory Reset!</a></p>)");
SendBackHtml(html);
}
void WebServer::ProcessHTTPSetupRequest()
{
bool result = PopulateHTMLSetupFromTemplate(WebSettingHtmlTemplate, _templateValuesMap);
if (result) //finished
{
_isHttpSetupRequestOn = false;
_server.send_P(200, "text/html", _setupHtmlBuffer);
}
}
void WebServer::HandleSendAPScript()
{
_server.send_P(200, "text/javascript", APScript);
}
void WebServer::HandleSetup()
{
_templateValuesMap.clear();
_templateValuesMap["WFPwd"] = _deviceSettings->accessPointPassword;
_templateValuesMap["DeviceId"] = _deviceSettings->AzureIoTDeviceId;
_templateValuesMap["IoTConStr"] = _deviceSettings->azureIoTHubConnectionString;;
_templateValuesMap["PBLng"] = String(_deviceSettings->longButtonPeriod).c_str();
_templateValuesMap["PBVLng"] = String(_deviceSettings->veryLongButtonPeriod).c_str();
_templateValuesMap["PBActPrd"] = String(_deviceSettings->PulseActivationPeriod).c_str();
const String checked = R"(checked="checked")";
if (_deviceSettings->shouldUseAzureIoT)
{
_templateValuesMap["IoT"] = checked;
_templateValuesMap["WebSrv"] = "";
}
else
{
_templateValuesMap["WebSrv"] = checked;
_templateValuesMap["IoT"] = "";
}
if (_deviceSettings->PBBehavior == PushButtonBehaviour::Toggle)
{
_templateValuesMap["PBBTgl"] = checked;
_templateValuesMap["PBBPls"] = "";
}
else
{
_templateValuesMap["PBBPls"] = checked;
_templateValuesMap["PBBTgl"] = "";
}
_isHttpSetupRequestOn = true; //start request processing
ProcessHTTPSetupRequest();
}
void WebServer::HandleSendViewCSS()
{
_server.send_P(200, "text/css", ViewCSS);
}
void WebServer::HandleSendAPList()
{
auto AccessPointList = ConnectionStatus::GetAccessPoints();
String html;
for (auto &&ap : AccessPointList)
{
html += R"(<input type = "radio" class="element radio" name = "ap" value = ")";
html += ap.SSID.c_str();
html += R"(" )";
if (ap.SSID == _deviceSettings->ssidName)
html += R"( checked="checked" )";
html += R"("/> <label class="choice">)";
html += ap.SSID.c_str();
html += R"( <font color="purple"> Signal:)";
html += String(100 + ap.RSSI).c_str();
if (!ap.isEncripted)
html += " Secure";
html += "</font></label>";
}
_server.send(200, "text/html", html);
}
//extern void pp_soft_wdt_stop();
//extern void pp_soft_wdt_restart();
bool WebServer::PopulateHTMLSetupFromTemplate(const String &htmlTemplate, const Util::StringMap & map)
{
int startTime = millis();
do
{
if (millis() - startTime > 25) //0.025 seconds per parsing iteration
return false;
Serial.printf("Continue setup template processing, index: %d\n", _templateIndex);
int beginVariable = htmlTemplate.indexOf('%', _templateIndex); //search <%= by searching %
int endVariable = -1;
if (beginVariable >= 0) //only if beginVariable didn't reach the end of html
endVariable = htmlTemplate.indexOf('%', beginVariable + 1);
if (beginVariable < 0 || endVariable < 0) //no more variables
{
auto rest = htmlTemplate.substring(_templateIndex); //add the template end
memcpy(_setupHtmlBuffer + _templateBufferIndex, rest.c_str(), rest.length()); //copy the template tail
_templateBufferIndex += rest.length();
break;
}
if (htmlTemplate[beginVariable - 1] != '<' || htmlTemplate[beginVariable + 1] != '=' || htmlTemplate[endVariable + 1] != '>') //not <%= ... %>
{
_setupHtmlBuffer[_templateBufferIndex++] = htmlTemplate[_templateIndex];
++_templateIndex;
continue;
}
auto variableName = htmlTemplate.substring(beginVariable + 2, endVariable);
String replacedValue = map.at(variableName); //extract only the variable name and replace it
String htmlUntilVariable = htmlTemplate.substring(_templateIndex, beginVariable - 1);
//Add all text before the variable and the replacement
memcpy(_setupHtmlBuffer + _templateBufferIndex, htmlUntilVariable.c_str(), htmlUntilVariable.length());
_templateBufferIndex += htmlUntilVariable.length();
memcpy(_setupHtmlBuffer + _templateBufferIndex, replacedValue.c_str(), replacedValue.length());
_templateBufferIndex += replacedValue.length();
_setupHtmlBuffer[_templateBufferIndex] = 0;
_templateIndex = endVariable + 2;
} while (_templateIndex != _templateEnd);
//reset for nect time
_templateIndex = 0;
_templateBufferIndex = 0;
_templateEnd = -1;
return true;
}
void WebServer::HandleSetConfiguration()
{
_deviceSettings->ssidName = _server.arg("ap").c_str();
_deviceSettings->accessPointPassword = _server.arg("WFPwd").c_str();
_deviceSettings->AzureIoTDeviceId = _server.arg("DeviceId").c_str();
_deviceSettings->azureIoTHubConnectionString = _server.arg("IoTConStr").c_str();
_deviceSettings->longButtonPeriod = atoi(_server.arg("PBLng").c_str());
_deviceSettings->veryLongButtonPeriod = atoi(_server.arg("PBVLng").c_str());
_deviceSettings->PulseActivationPeriod = atoi(_server.arg("PBActPrd").c_str());
_deviceSettings->shouldUseAzureIoT = _server.arg("WebOrIoT") == "IoT";
_deviceSettings->PBBehavior = _server.arg("PBB") == "PBBTgl" ? PushButtonBehaviour::Toggle : PushButtonBehaviour::Pulse;
printf("Server arguments:\n");
for (int i = 0; i < _server.args(); ++i)
{
Serial.printf("%s=%s\n", _server.argName(i).c_str(), _server.arg(_server.argName(i)).c_str());
}
String html =
R"(<p><center><h3>The device will reboot and try to connect to:</h3></center></p><p>)";
html += _deviceSettings->ssidName;
html += "</p><br/>";
html += "If after the reboot the two Leds are blinking or the green led is not turned on, do a factory reset by pressing the button for more than ";
html += String(_deviceSettings->veryLongButtonPeriod / 1000).c_str();
html += " seconds. The two leds should blink very fast.";
SendBackHtml(html.c_str());
_configurationUpdater(*_deviceSettings.get());
Util::software_Reboot();
}
void WebServer::HandleResetAccessPoint()
{
_deviceSettings->isFactoryReset = true;
String html =
R"(<p><h3>Access point credentials has been reset.</h3></p><br/><p>Reset device to activate access point mode.</p><br/>)";
html += R"(<p>Set new access point SSID information by surfing to )";
html += String(R"(http://192.168.4.1/)") + CreateUrl("setup").c_str();
html += "</p>";
SendBackHtml(html.c_str());
_configurationUpdater(*_deviceSettings.get()); //this will reset the device
}
void WebServer::HandleCommand(WebCommandPtr_t webCommand)
{
auto html = String("<p><h3>") + webCommand->ResultHTML() +String("</h3></p>");
_pubsub.NotifyAll(webCommand->Name(), webCommand->Id());
SendBackHtml(html);
}
bool WebServer::IsConnected() const
{
return WiFi.status() == WL_CONNECTED;
}
void WebServer::Loop()
{
if (_relayStateUpdater)
_relayState = _relayStateUpdater();
if (_isHttpSetupRequestOn)
ProcessHTTPSetupRequest();
_server.handleClient();
}
void WebServer::SetUpdateConfiguration(std::function<void(const DeviceSettings&)> configurationUpdater)
{
_configurationUpdater = configurationUpdater;
}
void WebServer::UpdateStatus(ConnectionStatus status)
{
if (!_isInit && status.IsJustConnected()) //new connection, only once
{
Serial.println("Web Server begins...");
_isInit = true;
MDNS.begin("esp8266");
_server.begin();
}
}
String WebServer::CreateUrl(const String& s) const
{
return _authorizedUrl + "/" + s;
}