-
Notifications
You must be signed in to change notification settings - Fork 19
/
serverFunctions.ino
298 lines (273 loc) · 9.32 KB
/
serverFunctions.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
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
void initWiFi(){
Serial.println();
Serial.println();
Serial.println("Startup");
// test esid
WiFi.disconnect();
delay(100);
WiFi.mode(WIFI_STA);
Serial.print("Connecting to WiFi ");
Serial.println(esid);
Debugln(epass);
WiFi.begin((char*)esid.c_str(), (char*)epass.c_str());
if ( testWifi() == 20 ) {
launchWeb(0);
return;
}
Serial.println("Opening AP");
setupAP();
}
int testWifi(void) {
int c = 0;
Debugln("Wifi test...");
while ( c < 30 ) {
if (WiFi.status() == WL_CONNECTED) { return(20); }
delay(500);
Serial.print(".");
c++;
}
Serial.println("WiFi Connect timed out!");
return(10);
}
void setupAP(void) {
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
int n = WiFi.scanNetworks();
Serial.println("scan done");
if (n == 0){
Serial.println("no networks found");
st ="<b>No networks found:</b>";
} else {
Serial.print(n);
Serial.println(" Networks found");
st = "<ul>";
for (int i = 0; i < n; ++i)
{
// Print SSID and RSSI for each network found
Serial.print(i + 1);
Serial.print(": ");
Serial.print(WiFi.SSID(i));
Serial.print(" (");
Serial.print(WiFi.RSSI(i));
Serial.print(")");
Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" (OPEN)":"*");
// Print to web SSID and RSSI for each network found
st += "<li>";
st +=i + 1;
st += ": ";
st += WiFi.SSID(i);
st += " (";
st += WiFi.RSSI(i);
st += ")";
st += (WiFi.encryptionType(i) == ENC_TYPE_NONE)?" (OPEN)":"*";
st += "</li>";
delay(10);
}
st += "</ul>";
}
Serial.println("");
WiFi.disconnect();
delay(100);
WiFi.mode(WIFI_AP);
WiFi.softAP(host);
WiFi.begin(host); // not sure if need but works
Serial.print("Access point started with name ");
Serial.println(host);
inApMode=1;
launchWeb(1);
}
void launchWeb(int webtype) {
Serial.println("");
Serial.println("WiFi connected");
//Start the web server or MQTT
if(otaFlag==1 && !inApMode){
Serial.println("Starting OTA mode.");
Serial.printf("Sketch size: %u\n", ESP.getSketchSize());
Serial.printf("Free size: %u\n", ESP.getFreeSketchSpace());
MDNS.begin(host);
server.on("/", HTTP_GET, [](){
server.sendHeader("Connection", "close");
server.sendHeader("Access-Control-Allow-Origin", "*");
server.send(200, "text/html", otaServerIndex);
});
server.on("/update", HTTP_POST, [](){
server.sendHeader("Connection", "close");
server.sendHeader("Access-Control-Allow-Origin", "*");
server.send(200, "text/plain", (Update.hasError())?"FAIL":"OK");
setOtaFlag(0);
ESP.restart();
},[](){
HTTPUpload& upload = server.upload();
if(upload.status == UPLOAD_FILE_START){
//Serial.setDebugOutput(true);
WiFiUDP::stopAll();
Serial.printf("Update: %s\n", upload.filename.c_str());
otaCount=300;
uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
if(!Update.begin(maxSketchSpace)){//start with max available size
Update.printError(Serial);
}
} else if(upload.status == UPLOAD_FILE_WRITE){
if(Update.write(upload.buf, upload.currentSize) != upload.currentSize){
Update.printError(Serial);
}
} else if(upload.status == UPLOAD_FILE_END){
if(Update.end(true)){ //true to set the size to the current progress
Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
} else {
Update.printError(Serial);
}
Serial.setDebugOutput(false);
}
yield();
});
server.begin();
Serial.printf("Ready! Open http://%s.local in your browser\n", host);
MDNS.addService("http", "tcp", 80);
otaTickLoop.attach(1, otaCountown);
} else {
//setOtaFlag(1);
if (webtype==1 || iotMode==0){ //in config mode or WebControle
if (webtype==1) {
webtypeGlob == 1;
Serial.println(WiFi.softAPIP());
server.on("/", webHandleConfig);
server.on("/a", webHandleConfigSave);
} else {
//setup DNS since we are a client in WiFi net
if (!MDNS.begin(host)) {
Serial.println("Error setting up MDNS responder!");
} else {
Serial.println("mDNS responder started");
MDNS.addService("http", "tcp", 80);
}
Serial.println(WiFi.localIP());
server.on("/", webHandleRoot);
server.on("/cleareeprom", webHandleClearRom);
server.on("/gpio", webHandleGpio);
}
//server.onNotFound(webHandleRoot);
server.begin();
Serial.println("Web server started");
webtypeGlob=webtype; //Store global to use in loop()
} else if(webtype!=1 && iotMode==1){ // in MQTT and not in config mode
mqttClient.setBrokerDomain((char*) mqttServer.c_str());
mqttClient.setPort(1883);
mqttClient.setCallback(mqtt_arrived);
mqttClient.setClient(wifiClient);
if (WiFi.status() == WL_CONNECTED){
if (!connectMQTT()){
delay(2000);
if (!connectMQTT()){
Serial.println("Could not connect MQTT.");
Serial.println("Starting web server instead.");
iotMode=0;
launchWeb(0);
webtypeGlob=webtype;
}
}
}
}
}
}
void webHandleConfig(){
IPAddress ip = WiFi.softAPIP();
String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
String s;
s = "Configuration of " + hostName + " at ";
s += ipStr;
s += "<p>";
s += st;
s += "<form method='get' action='a'>";
s += "<label>SSID: </label><input name='ssid' length=32><label> Pass: </label><input name='pass' type='password' length=64></br>";
s += "The following is not ready yet!</br>";
s += "<label>IOT mode: </label><input type='radio' name='iot' value='0'> HTTP<input type='radio' name='iot' value='1' checked> MQTT</br>";
s += "<label>MQTT Broker IP/DNS: </label><input name='host' length=15></br>";
s += "<label>MQTT Publish topic: </label><input name='pubtop' length=64></br>";
s += "<label>MQTT Subscribe topic: </label><input name='subtop' length=64></br>";
s += "<input type='submit'></form></p>";
s += "\r\n\r\n";
Serial.println("Sending 200");
server.send(200, "text/html", s);
}
void webHandleConfigSave(){
// /a?ssid=blahhhh&pass=poooo
String s;
s = "<p>Settings saved to eeprom and reset to boot into new settings</p>\r\n\r\n";
server.send(200, "text/html", s);
Serial.println("clearing EEPROM.");
clearConfig();
String qsid;
qsid = server.arg("ssid");
qsid.replace("%2F","/");
Serial.println("Got SSID: " + qsid);
esid = (char*) qsid.c_str();
String qpass;
qpass = server.arg("pass");
qpass.replace("%2F","/");
Serial.println("Got pass: " + qpass);
epass = (char*) qpass.c_str();
String qiot;
qiot= server.arg("iot");
Serial.println("Got iot mode: " + qiot);
qiot=="0"? iotMode = 0 : iotMode = 1 ;
String qsubTop;
qsubTop = server.arg("subtop");
qsubTop.replace("%2F","/");
Serial.println("Got subtop: " + qsubTop);
subTopic = (char*) qsubTop.c_str();
String qpubTop;
qpubTop = server.arg("pubtop");
qpubTop.replace("%2F","/");
Serial.println("Got pubtop: " + qpubTop);
pubTopic = (char*) qpubTop.c_str();
mqttServer = (char*) server.arg("host").c_str();
Serial.print("Got mqtt Server: ");
Serial.println(mqttServer);
Serial.print("Settings written ");
saveConfig()? Serial.println("sucessfully.") : Serial.println("not succesfully!");;
Serial.println("Restarting!");
delay(1000);
ESP.reset();
}
void webHandleRoot(){
String s;
s = "<p>Hello from ESP8266";
s += "</p>";
s += "<a href=\"/gpio\">Controle GPIO</a><br />";
s += "<a href=\"/cleareeprom\">Clear settings an boot into Config mode</a><br />";
s += "\r\n\r\n";
Serial.println("Sending 200");
server.send(200, "text/html", s);
}
void webHandleClearRom(){
String s;
s = "<p>Clearing the config and reset to configure new wifi<p>";
s += "</html>\r\n\r\n";
Serial.println("Sending 200");
server.send(200, "text/html", s);
Serial.println("clearing config");
clearConfig();
delay(10);
Serial.println("Done, restarting!");
ESP.reset();
}
void webHandleGpio(){
String s;
// Set GPIO according to the request
if (server.arg("state")=="1" || server.arg("state")=="0" ) {
int state = server.arg("state").toInt();
digitalWrite(OUTPIN, state);
Serial.print("Light switched via web request to ");
Serial.println(state);
}
s = "Light is now ";
s += (digitalRead(OUTPIN))?"on":"off";
s += "<p>Change to <form action='gpio'><input type='radio' name='state' value='1' ";
s += (digitalRead(OUTPIN))?"checked":"";
s += ">On<input type='radio' name='state' value='0' ";
s += (digitalRead(OUTPIN))?"":"checked";
s += ">Off <input type='submit' value='Submit'></form></p>";
server.send(200, "text/html", s);
}