-
Notifications
You must be signed in to change notification settings - Fork 6
/
esp8266-web-mqtt-fauxmo.ino
319 lines (268 loc) · 8.76 KB
/
esp8266-web-mqtt-fauxmo.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
#include <Arduino.h>
#include <FS.h>
#include <fauxmoESP.h> // https://github.com/makermusings/fauxmo (Fauxmo commit 54e00be from GitHub)
#include <ESP8266WiFi.h> // https://github.com/tzapu/WiFiManager (WiFiManager-0.12.0 from Arduino IDE Libraries)
#include <WiFiManager.h>
#include <PubSubClient.h> // http://pubsubclient.knolleary.net/ (PubSubClient-2.6.0 from Arduino IDE Libraries)
#include <ESP8266WebServer.h>
#include "credentials.h" // Copy credentials.h.example to credentials.h and fill with your private data
// Using latests Arduino/hardware/esp8266 tools from https://github.com/esp8266/Arduino (commit 7b32e6a)
// Pin to name mapping
// If you have your I/O connected to other pin, modify this accordingly
#define SWITCH_PIN D1
// Adafruit IO configuration. Replace {user} and {key} with your own
#define AIO_SERVER "io.adafruit.com"
#define AIO_SERVERPORT 1883
#define AIO_USERNAME AIO_CRED_USERNAME
#define AIO_KEY AIO_CRED_KEY
// Adafruit IO feed (they are autogenerated using the device id)
// Example for the switch: AIO_BASE_FEED + ESP.getChipId() + AIO_SWITCH_FEED =>
// {username}/feeds/CC44DD-switch. No need to change these.
#define AIO_BASE_FEED AIO_USERNAME "/feeds/"
#define AIO_SWITCH_FEED "-switch"
#define AIO_NAME_FEED "-wemo-name"
// Serial speed for the console
#define SERIAL_SPEED 115200
// MQTT connection
WiFiClient espClient;
PubSubClient client(espClient);
String switchFeed;
String nameFeed;
// FauxmoESP
fauxmoESP fauxmo;
String fauxmoId;
// Web server
ESP8266WebServer server(80);
// State
int switchState = 0;
char chipId[6];
void setSwitchHigh(bool publish) {
digitalWrite(SWITCH_PIN, HIGH);
switchState = 1;
Serial.println("Switch: HIGH");
if (publish) {
publishSwitch();
}
}
void setSwitchLow(bool publish) {
digitalWrite(SWITCH_PIN, LOW);
switchState = 0;
Serial.println("Switch: LOW");
if (publish) {
publishSwitch();
}
}
void publishSwitch(void) {
String switchStateString;
switchStateString += switchState;
client.publish(switchFeed.c_str(), switchStateString.c_str());
Serial.print("Publish message [");
Serial.print(switchFeed);
Serial.print("]: ");
Serial.println(switchStateString);
}
void publishName(void) {
client.publish(nameFeed.c_str(), fauxmoId.c_str());
Serial.print("Publish message [");
Serial.print(nameFeed);
Serial.print("]: ");
Serial.println(fauxmoId);
}
String getContentType(String filename) {
if (server.hasArg("download"))
return "application/octet-stream";
else if (filename.endsWith(".htm"))
return "text/html";
else if (filename.endsWith(".html"))
return "text/html";
else if (filename.endsWith(".css"))
return "text/css";
else if (filename.endsWith(".js"))
return "application/javascript";
else if (filename.endsWith(".png"))
return "image/png";
else if (filename.endsWith(".gif"))
return "image/gif";
else if (filename.endsWith(".jpg"))
return "image/jpeg";
else if (filename.endsWith(".ico"))
return "image/x-icon";
else if (filename.endsWith(".xml"))
return "text/xml";
else if (filename.endsWith(".pdf"))
return "application/x-pdf";
else if (filename.endsWith(".zip"))
return "application/x-zip";
else if (filename.endsWith(".gz"))
return "application/x-gzip";
else if (filename.endsWith(".svg"))
return "image/svg+xml";
return "text/plain";
}
bool handleFileRead(String path) {
Serial.println("handleFileRead: " + path);
if (path.endsWith("/")) path += "index.min.html";
String contentType = getContentType(path);
String pathWithGz = path + ".gz";
if (SPIFFS.exists(pathWithGz) || SPIFFS.exists(path)) {
if (SPIFFS.exists(pathWithGz)) path += ".gz";
File file = SPIFFS.open(path, "r");
size_t sent = server.streamFile(file, contentType);
file.close();
return true;
}
return false;
}
void returnActionValue(void( * action)(bool), bool value) {
action(value);
server.send(200, "application/json", "true");
}
void mqttCallback(char * topicChar, byte * payloadBytes, unsigned int length) {
char payloadChar[100];
int i;
for (i = 0; i < length; i++) {
payloadChar[i] = payloadBytes[i];
}
payloadChar[i] = '\0';
String topic = String(topicChar);
String payload = String(payloadChar);
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] (");
Serial.print(length);
Serial.print(" bytes) :");
Serial.print(payload);
Serial.println();
if (topic == switchFeed) {
Serial.print("Processing ");
Serial.println(switchFeed);
if ((char) payload[0] == '0') {
setSwitchLow(false);
} else {
setSwitchHigh(false);
}
}
}
String setFeedId(const char * base, char * id, const char * feed) {
String feedId;
feedId += base;
feedId += id;
feedId += feed;
return feedId;
}
void setupFeedIds(void) {
switchFeed = setFeedId(AIO_BASE_FEED, chipId, AIO_SWITCH_FEED);
nameFeed = setFeedId(AIO_BASE_FEED, chipId, AIO_NAME_FEED);
}
void handleMqttConnection(void) {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(chipId, AIO_USERNAME, AIO_KEY)) {
Serial.println("connected");
// Publish current state
publishSwitch();
publishName();
// Resubscribe
client.subscribe(switchFeed.c_str());
} else {
Serial.print("failed, ClientState=");
Serial.print(client.state());
Serial.println(" trying again in 5000 milliseconds");
// Wait 5 seconds before retrying but continue handling we requests
long retryMillis = millis() + 5000;
while (millis() < retryMillis) {
// Keep processing local server calls in the meantime
server.handleClient();
}
}
}
client.loop();
}
void setup(void) {
// Init serial
Serial.begin(SERIAL_SPEED);
sprintf(chipId, "%06X", ESP.getChipId());
Serial.println("");
Serial.print("----- ESP ID=");
Serial.print(chipId);
Serial.println(" -----");
// Setup pins
pinMode(SWITCH_PIN, OUTPUT);
// Connect to WiFi / AP
WiFiManager wifiManager;
wifiManager.autoConnect();
// Setup MQTT
setupFeedIds();
client.setServer(AIO_SERVER, AIO_SERVERPORT);
client.setCallback(mqttCallback);
// Setup file system
SPIFFS.begin();
// Setup chip id and fauxmo id
fauxmoId = chipId;
if (!SPIFFS.exists("/id.json")) {
File idFile = SPIFFS.open("/id.json", "w");
if (!idFile) {
Serial.println("id.json file failed to open");
}
idFile.println(chipId);
idFile.close();
}
else {
File chipIdForFauxmoId = SPIFFS.open("/id.json", "r");
if (chipIdForFauxmoId) {
fauxmoId = chipIdForFauxmoId.readString();
}
chipIdForFauxmoId.close();
}
// Set up HTTP server handles
server.on("/setSwitchHigh", []() {
returnActionValue(setSwitchHigh, true);
});
server.on("/setSwitchLow", []() {
returnActionValue(setSwitchLow, true);
});
server.on("/getSwitch", []() {
String switchAsString;
switchAsString += switchState;
server.send(200, "application/json", switchAsString);
});
server.on("/setId", []() {
File idFile = SPIFFS.open("/id.json", "w");
if (!idFile) {
Serial.println("id.json file failed to open");
server.send(500, "application/json", "false");
} else {
idFile.println(server.arg("id"));
server.send(200, "application/json", "true");
Serial.print("New id saved (this value will be used for the WeMo switch name after next reset): ");
Serial.println(server.arg("id"));
}
idFile.close();
});
server.onNotFound([]() {
if (!handleFileRead(server.uri())) {
server.send(404, "text/plain", "FileNotFound");
}
});
// Start HTTP server
server.begin();
Serial.println("HTTP server started");
// Fauxmo
Serial.print("WeMo switch name: ");
Serial.println(fauxmoId);
fauxmo.addDevice(fauxmoId.c_str());
fauxmo.onMessage([](const char * device_name, bool state) {
Serial.printf("New WeMo message for device %s, new state: %s", device_name, state ? "ON" : "OFF");
if (state == 1) {
setSwitchHigh(true);
} else {
setSwitchLow(true);
}
});
}
void loop() {
handleMqttConnection();
server.handleClient();
}