-
Notifications
You must be signed in to change notification settings - Fork 0
/
MqttEsp8266Switch.ino
317 lines (237 loc) · 6.39 KB
/
MqttEsp8266Switch.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
#define FASTLED_ESP8266_RAW_PIN_ORDER
#include "Config.h"
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
// How many leds are in the strip?
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
const bool TRACE = false;
const bool DEBUG = false;
const bool TEST_RELAIS_ON_INIT = false;
const bool STATE_ON = LOW;
const bool STATE_OFF = HIGH;
unsigned long turnOffTimes[numberOfSwitches];
unsigned long lastActivity = millis();
void connectWifi() {
WiFi.begin(ssid, password);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(F(""));
Serial.print(F("Connected to "));
Serial.println(ssid);
Serial.print(F("IP address: "));
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print(F("Message arrived ["));
Serial.print(topic);
Serial.print(F("] "));
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
handleBody(payload);
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print(F("Attempting MQTT connection..."));
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
// Once connected, publish an announcement...
logMessage("info", "Started");
// ... and resubscribe
client.subscribe(consumeTopic);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void handleBody(byte* payload) {
StaticJsonBuffer<150> newBuffer;
JsonObject& root = newBuffer.parseObject(payload);
JsonVariant id = root["id"];
JsonVariant stateVariant = root["state"];
JsonVariant durationVariant = root["duration"];
if (id.success() == false) {
sendError(F("no switch id specified"));
return;
}
int switchNumber = id.as<int>();
if (switchNumber >= numberOfSwitches) {
sendError(F("id is invalid"));
return;
}
if (stateVariant.success() == false) {
sendError(F("no state specified"));
return;
}
bool state = stateVariant.as<bool>();
if (durationVariant.success()) {
unsigned long duration = durationVariant.as<unsigned long>();
Serial.printf("contains duration: %d\n", duration);
if (duration > 0) {
updateDuration(switchNumber, duration);
} else {
state = false;
}
} else {
Serial.println(F("no duration detected"));
}
if (state == false) {
switchOff(switchNumber);
return;
}
switchOn(switchNumber);
lastActivity = millis();
}
void cleanRetainedMessage(char* topic) {
client.publish(topic, "", true);
}
void sendError(String msg) {
Serial.println(msg);
}
void switchOff(int id) {
changeSwitchState(id, STATE_OFF);
}
void switchOn(int id) {
changeSwitchState(id, STATE_ON);
}
void updateDuration(int id, unsigned long duration) {
unsigned long endTime = millis() + duration;
Serial.printf("updateDuration with value %d\n", duration);
turnOffTimes[id] = endTime;
}
void changeSwitchState(int id, bool state) {
int pin = mapIdToPin(id);
bool isOn = (state == STATE_ON);
digitalWrite(pin, state);
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root["id"] = id;
root["state"] = isOn;
publishMessage(stateTopic, root);
Serial.printf("info: id: %d, state: %d\n", id, isOn);
}
int mapIdToPin(int id) {
return switchPins[id];
}
void setup() {
Serial.begin(115200);
connectWifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
for (int i = 0; i < numberOfSwitches; ++i) {
initRelay(i);
}
}
void initRelay(int id) {
int pin = mapIdToPin(id);
char message[128];
sprintf(message, "Initializing switch id: %d pin: %d", id, pin);
logDebug(F("logging init relay message"));
logMessage("info", message);
pinMode(pin, OUTPUT);
digitalWrite(pin, STATE_OFF);
if (TEST_RELAIS_ON_INIT) {
digitalWrite(pin, STATE_ON);
delay(500);
digitalWrite(pin, STATE_OFF);
delay(500);
}
logDebug(F("Init Relay done."));
}
int iteration = 0;
unsigned long lastRun = 0;
void turnOffIfRequired() {
iteration++;
if (iteration % 100 != 0) {
return;
}
unsigned long now = millis();
if (now - lastRun > 500) {
logTrace(F("processing turnOfIfRequired"));
for (int i = 0; i < numberOfSwitches; ++i) {
unsigned long value = turnOffTimes[i];
if (TRACE) {
Serial.printf("now: %d - i: %d - value: %d\n", now, i, value);
}
if (value == 0) {
continue;
}
if (value < now) {
logDebug(F("Switch needs to be powered off. time exeeded."));
char message[50];
sprintf(message, "Duration for id %d exeeded. Turning off.", i);
logMessage("info", message);
logDebug(F("Switchign off"));
switchOff(i);
logDebug(F("resetting turnOfTimes to zero"));
turnOffTimes[i] = 0;
}
}
iteration = 0;
lastRun = now;
}
}
void logMessage(char* category, char* message) {
logTrace(F("starting logMessage"));
Serial.printf("%s: %s\n", category, message);
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root["category"] = category;
root["message"] = message;
publishMessage(logTopic, root);
logTrace(F("exiting logMessage"));
}
void publishMessage(const char* topic, JsonObject& object) {
char message[256];
object.printTo(message, 256);
client.publish(topic, message);
}
void logDebug(String message) {
if (DEBUG) {
Serial.println(message);
}
}
void logTrace(String message) {
if (TRACE) {
Serial.println(message);
}
}
bool canSleep() {
for (int i = 0; i < numberOfSwitches; ++i) {
int pin = mapIdToPin(i);
if (digitalRead(pin) == STATE_ON) {
return false;
}
}
unsigned long now = millis();
unsigned diff = now - lastActivity;
// Serial.printf("Diff since last activity: %d\n", diff);
return now - lastActivity > 15000;
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
turnOffIfRequired();
if (canSleep()) {
logDebug("Going to sleep");
delay(500);
logDebug("Waking up");
}
}