-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebserver.h
80 lines (63 loc) · 2 KB
/
webserver.h
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
#ifndef WEBSERVER_H
#define WEBSERVER_H
#include <ESP8266WebServer.h>
typedef std::function<boolean (const char *ssid, const char *password)> ConnectToWifiCB;
ConnectToWifiCB connect_cb;
ESP8266WebServer server = ESP8266WebServer(80);
void handleConfigRoot() {
String page = "<html><body><h1>WiFi Connection Setup</h1><form method=\"POST\" action=\"/login\"><input name=\"ssid\" placeholder=\"ssid\"><br /><input type=\"password\" name=\"password\" placeholder=\"password\"><br /><input type=\"submit\"></form></body></html>";
server.send(200, "text/html", page);
}
void handleRoot() {
if(WiFi.status() == WL_CONNECTED) {
server.send(200, "text/html", "<html><body><h1>YEP</h1></body></html>");
}
else{
handleConfigRoot();
}
}
void handleNotFound() {
if(WiFi.status() != WL_CONNECTED) {
//serve up the config page (captive portal reasons)
handleConfigRoot();
}else{
server.send(404, "text/plain", "Nothing here, try again.");
}
}
void handleWiFiConfigPOST() {
String ssid;
String password;
for ( uint8_t i = 0; i < server.args(); i++ ) {
if(server.argName(i) == "ssid") {
ssid = server.arg(i);
Serial.println("");
Serial.println(ssid);
}
if(server.argName(i) == "password") {
password = server.arg(i);
Serial.println("");
Serial.println(password);
}
}
String out = "<html><body><h1>Attempting to connect to " + ssid + "</h1></body></html>";
server.send( 200, "text/html", out);
//do connection to wifi here
if (!connect_cb(ssid.c_str(), password.c_str())) {
Serial.println("Failed to connect.");
} else {
//connected
WiFi.mode(WIFI_STA);
}
}
void setupWebserver(ConnectToWifiCB cb) {
connect_cb = cb;
// handle index
server.on("/", handleRoot);
server.on("/login", handleWiFiConfigPOST);
server.onNotFound(handleNotFound);
server.begin();
}
void webserverLoop() {
server.handleClient();
}
#endif // WEBSERVER_H