forked from Jorgen-VikingGod/ESP8266-WiFi-Relay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ESP8266-WiFi-Relay.ino
378 lines (361 loc) · 12.4 KB
/
ESP8266-WiFi-Relay.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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
/*
* ESP8266-WiFi-Relay.ino
* ----------------------------------------------------------------------------
* simple sketch of using ESP8266WebServer to switch relays on GPIO pins
* it serves a simple website with toggle buttons for each relay
* ----------------------------------------------------------------------------
* Source: https://github.com/Jorgen-VikingGod/ESP8266-WiFi-Relay
* Copyright: Copyright (c) 2017 Juergen Skrotzky
* Author: Juergen Skrotzky <[email protected]>
* License: MIT License
* Created on: 23.Nov. 2017
* ----------------------------------------------------------------------------
*/
extern "C" {
#include "user_interface.h"
}
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <EEPROM.h>
#include <Wire.h>
#include <Hash.h>
#include <FS.h>
#include "ArduinoJson.h" //https://github.com/bblanchon/ArduinoJson
#include "webserver.h"
// declare and initial list of default relay settings
sRelay relay[8] = {sRelay(D5), sRelay(D6), sRelay(D7), sRelay(D8), sRelay(D3), sRelay(D4), sRelay(D2), sRelay(D1)};
uint8_t relayCount = sizeof(relay) / sizeof(sRelay);
// declare WiFiMulti
ESP8266WiFiMulti WiFiMulti;
/*
* setup function
* ----------------------------------------------------------------------------
*/
void setup() {
// serial interface for debug messages
if (_debug) {
Serial.begin(115200);
}
// initial all relay pins as OUTPUT pin
for (uint8_t idx = 0; idx < relayCount; ++idx) {
pinMode(relay[idx].pin, OUTPUT);
}
DEBUG_PRINT(F("\n"));
// use EEPROM
EEPROM.begin(512);
// use SPIFFS
SPIFFS.begin();
// handle requests
server.on("/list", HTTP_GET, handleFileList);
server.on("/edit", HTTP_GET, handleGetEditor);
server.on("/edit", HTTP_PUT, handleFileCreate);
server.on("/edit", HTTP_DELETE, handleFileDelete);
server.on("/edit", HTTP_POST, []() {
server.send(200, "text/plain", "");
}, handleFileUpload);
server.onNotFound([]() {
if (!handleFileRead(server.uri()))
server.send(404, "text/plain", "FileNotFound");
});
server.on("/all", HTTP_GET, handleGetAll);
server.on("/current", HTTP_GET, sendCurrentStates);
server.on("/relay", HTTP_GET, handleGetRelay);
server.on("/toggle", HTTP_POST, handlePostToggle);
server.on("/settings/status", HTTP_GET, handleGetStatus);
server.on("/settings/configfile", HTTP_GET, handleGetConfigfile);
server.on("/settings/configfile", HTTP_POST, handlePostConfigfile);
server.begin();
// Add service to MDNS
MDNS.addService("http", "tcp", 80);
// load config.json and connect to WiFI
if (!loadConfiguration()) {
// if no configuration found,
// try to connect hard coded multi APs
connectSTA(nullptr, nullptr, "wifi-relay");
}
// load last states from EEPROM
loadSettings();
}
/*
* main loop function
* ----------------------------------------------------------------------------
*/
void loop() {
// handle http clients
server.handleClient();
}
/*
* load stored settings from EEPROM
* ----------------------------------------------------------------------------
*/
void loadSettings() {
// load relay states set outputs
DEBUG_PRINT(F("loadSettings: "));
for (uint8_t idx = 0; idx < relayCount; ++idx) {
relay[idx].state = EEPROM.read(idx);
DEBUG_PRINTF("relay%d: %d, ", idx+1, relay[idx].state);
// initialize IO pin
pinMode(relay[idx].pin, OUTPUT);
// set relay state
setRelay(idx, relay[idx].state);
}
DEBUG_PRINTLN("");
}
/*
* load config.json file and try to connect
* ----------------------------------------------------------------------------
*/
bool loadConfiguration() {
// try to open config.json file
File configFile = SPIFFS.open("/config.json", "r");
if (!configFile) {
DEBUG_PRINTLN(F("[WARN] Failed to open config file"));
return false;
}
size_t size = configFile.size();
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
// We don't use String here because ArduinoJson library requires the input
// buffer to be mutable. If you don't use ArduinoJson, you may as well
// use configFile.readString instead.
configFile.readBytes(buf.get(), size);
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.parseObject(buf.get());
if (!json.success()) {
DEBUG_PRINTLN(F("[WARN] Failed to parse config file"));
return false;
}
DEBUG_PRINTLN(F("[INFO] Config file found"));
if (_debug) {
json.prettyPrintTo(Serial);
}
// get relay settings
for (uint8_t idx = 0; idx < relayCount; ++idx) {
relay[idx].type = json["relay"+String(idx+1)]["type"];
relay[idx].pin = json["relay"+String(idx+1)]["pin"];
}
// get stored wifi settings
const char * ssid = json["ssid"];
const char * password = json["wifipwd"];
const char * hostname = json["hostname"];
// try to connect with stored settings and hard coded ones
if (!connectSTA(ssid, password, hostname)) {
return false;
}
return true;
}
/*
* try to connect WiFi
* ----------------------------------------------------------------------------
*/
bool connectSTA(const char* ssid, const char* password, const char * hostname) {
WiFi.mode(WIFI_STA);
// add here your hard coded backfall wifi ssid and password
// WiFiMulti.addAP("<YOUR-SSID-1>", "<YOUR-WIFI-PASS-1>");
// WiFiMulti.addAP("<YOUR-SSID-2>", "<YOUR-WIFI-PASS-2>");
if (ssid && password) {
WiFiMulti.addAP(ssid, password);
}
// We try it for 30 seconds and give up on if we can't connect
unsigned long now = millis();
uint8_t timeout = 30; // define when to time out in seconds
DEBUG_PRINT(F("[INFO] Trying to connect WiFi: "));
while (WiFiMulti.run() != WL_CONNECTED) {
if (millis() - now < timeout * 1000) {
delay(200);
DEBUG_PRINT(F("."));
} else {
DEBUG_PRINTLN("");
DEBUG_PRINTLN(F("[WARN] Couldn't connect in time"));
return false;
}
}
if (hostname) {
if (MDNS.begin(hostname)) {
DEBUG_PRINTLN(F("MDNS responder started"));
}
}
DEBUG_PRINTLN("");
DEBUG_PRINT(F("[INFO] Client IP address: ")); // Great, we connected, inform
DEBUG_PRINTLN(WiFi.localIP());
return true;
}
/*
* send ESP8266 status
* ----------------------------------------------------------------------------
*/
void sendStatus() {
DEBUG_PRINTLN("sendStatus()");
struct ip_info info;
FSInfo fsinfo;
if (!SPIFFS.info(fsinfo)) {
DEBUG_PRINTLN(F("[ WARN ] Error getting info on SPIFFS"));
}
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root["command"] = "status";
root["heap"] = ESP.getFreeHeap();
root["chipid"] = String(ESP.getChipId(), HEX);
root["cpu"] = ESP.getCpuFreqMHz();
root["availsize"] = ESP.getFreeSketchSpace();
root["availspiffs"] = fsinfo.totalBytes - fsinfo.usedBytes;
root["spiffssize"] = fsinfo.totalBytes;
wifi_get_ip_info(STATION_IF, &info);
struct station_config conf;
wifi_station_get_config(&conf);
root["ssid"] = String(reinterpret_cast<char*>(conf.ssid));
root["dns"] = printIP(WiFi.dnsIP());
root["mac"] = WiFi.macAddress();
IPAddress ipaddr = IPAddress(info.ip.addr);
IPAddress gwaddr = IPAddress(info.gw.addr);
IPAddress nmaddr = IPAddress(info.netmask.addr);
root["ip"] = printIP(ipaddr);
root["gateway"] = printIP(gwaddr);
root["netmask"] = printIP(nmaddr);
String json;
root.printTo(json);
DEBUG_PRINTLN(json);
server.setContentLength(root.measureLength());
server.send(200, "application/json", json);
}
/*
* send whole configfile and status
* ----------------------------------------------------------------------------
*/
void sendConfigfile() {
// try to open config.json file
File configFile = SPIFFS.open("/config.json", "r");
if (!configFile) {
DEBUG_PRINTLN(F("[WARN] Failed to open config file"));
}
size_t size = configFile.size();
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
// We don't use String here because ArduinoJson library requires the input
// buffer to be mutable. If you don't use ArduinoJson, you may as well
// use configFile.readString instead.
configFile.readBytes(buf.get(), size);
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(buf.get());
if (!root.success()) {
DEBUG_PRINTLN(F("[WARN] Failed to parse config file"));
}
DEBUG_PRINTLN(F("[INFO] Config file found"));
struct ip_info info;
FSInfo fsinfo;
if (!SPIFFS.info(fsinfo)) {
DEBUG_PRINTLN(F("[ WARN ] Error getting info on SPIFFS"));
}
root["heap"] = ESP.getFreeHeap();
root["chipid"] = String(ESP.getChipId(), HEX);
root["cpu"] = ESP.getCpuFreqMHz();
root["availsize"] = ESP.getFreeSketchSpace();
root["availspiffs"] = fsinfo.totalBytes - fsinfo.usedBytes;
root["spiffssize"] = fsinfo.totalBytes;
wifi_get_ip_info(STATION_IF, &info);
struct station_config conf;
wifi_station_get_config(&conf);
root["ssid"] = String(reinterpret_cast<char*>(conf.ssid));
root["dns"] = printIP(WiFi.dnsIP());
root["mac"] = WiFi.macAddress();
IPAddress ipaddr = IPAddress(info.ip.addr);
IPAddress gwaddr = IPAddress(info.gw.addr);
IPAddress nmaddr = IPAddress(info.netmask.addr);
root["ip"] = printIP(ipaddr);
root["gateway"] = printIP(gwaddr);
root["netmask"] = printIP(nmaddr);
String json;
root.printTo(json);
DEBUG_PRINTLN(json);
server.setContentLength(root.measureLength());
server.send(200, "application/json", json);
}
/*
* send all states
* ----------------------------------------------------------------------------
*/
void sendAll() {
DEBUG_PRINTLN("sendAll()");
// try to open config.json file
File configFile = SPIFFS.open("/config.json", "r");
if (!configFile) {
DEBUG_PRINTLN(F("[WARN] Failed to open config file"));
}
size_t size = configFile.size();
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
// We don't use String here because ArduinoJson library requires the input
// buffer to be mutable. If you don't use ArduinoJson, you may as well
// use configFile.readString instead.
configFile.readBytes(buf.get(), size);
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.parseObject(buf.get());
if (!json.success()) {
DEBUG_PRINTLN(F("[WARN] Failed to parse config file"));
}
DynamicJsonBuffer jsonBuffer2;
JsonObject &root = jsonBuffer2.createObject();
// create relay json objects
for (uint8_t idx = 0; idx < relayCount; ++idx) {
JsonObject& relayJson = jsonBuffer2.createObject();
relayJson["name"] = json["relay"+String(idx+1)]["name"];
relayJson["state"] = relay[idx].state;
root.set("relay"+String(idx+1), relayJson);
}
String jsonStr;
root.printTo(jsonStr);
DEBUG_PRINTLN(jsonStr);
server.setContentLength(root.measureLength());
server.send(200, "application/json", jsonStr);
}
/*
* send current states
* ----------------------------------------------------------------------------
*/
void sendCurrentStates() {
DEBUG_PRINTLN("sendCurrentStates()");
DynamicJsonBuffer jsonBuffer;
JsonObject &root = jsonBuffer.createObject();
// create relay json values
for (uint8_t idx = 0; idx < relayCount; ++idx) {
JsonObject& relayJson = jsonBuffer.createObject();
relayJson["state"] = relay[idx].state;
root.set("relay"+String(idx+1), relayJson);
}
String jsonStr;
root.printTo(jsonStr);
DEBUG_PRINTLN(jsonStr);
server.setContentLength(root.measureLength());
server.send(200, "application/json", jsonStr);
}
/*
* set current relay state and store it in EEPROM
* ----------------------------------------------------------------------------
*/
void setRelay(uint8_t idx, uint8_t value) {
DEBUG_PRINTF("setRelay(%d, %d)\n", idx, value);
uint8_t lowValue = (relay[idx].type == 0 ? HIGH : LOW);
uint8_t highValue = (relay[idx].type == 0 ? LOW : HIGH);
relay[idx].state = (value == 0 ? LOW : HIGH);
digitalWrite(relay[idx].pin, (relay[idx].state == LOW ? lowValue : highValue));
EEPROM.write(idx, relay[idx].state);
EEPROM.commit();
}
/*
* send relay state back to website (idx = index of relay)
* ----------------------------------------------------------------------------
*/
void sendRelay(uint8_t idx) {
DEBUG_PRINTF("sendRelay(%d)\n", idx);
DynamicJsonBuffer jsonBuffer;
JsonObject &root = jsonBuffer.createObject();
root["relay"+String(idx+1)] = relay[idx].state;
String json;
root.printTo(json);
DEBUG_PRINTLN(json);
server.setContentLength(root.measureLength());
server.send(200, "application/json", json);
}