-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRegnerdings.ino
547 lines (471 loc) · 15.9 KB
/
Regnerdings.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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ArduinoOTA.h>
#include <WiFiUdp.h>
#include "include/WiFiSecret.h"
#include "include/lcd.h"
#include "include/th_sensor.h"
#include "Arduino.h"
#define NUMPORTS 5
const char m_CompileDate[] = __DATE__ " " __TIME__;
WiFiClient espClient;
PubSubClient client(espClient);
// activity LED config
const byte m_ActivityLed = D8;
// D1 Pinout guide https://randomnerdtutorials.com/esp8266-pinout-reference-gpios/
// relay/switch config
const byte m_Ports[NUMPORTS] = {D1, D2, D5, D6, D7};
bool m_SwitchState[NUMPORTS];
const unsigned long m_MaxOnDuration = 3600 * 1000; // max one hour
unsigned long m_LastOnTime[NUMPORTS];
// temperature/humidity sensor config
const byte m_i2cPorts[] = {D3, D4}; // SDA, SCL: GPIO0, GPIO2, must be HIGH during boot
unsigned long m_LastTempTransmit = 0;
int m_LastTemperature = 0;
int m_LastHumidity = 0;
// button config
const byte m_Button = D0;
unsigned long m_LastButtonPressed = 0;
bool m_ButtonPressed = false;
enum buttonAction
{
HANDLED = -1,
NONE = 0,
SHORT = 1,
LONG = 2
};
int m_LastButtonAction = NONE;
// screen config
unsigned long m_LastScreenUpdate = 0;
int m_EditPort = 0;
void setup()
{
Serial.begin(115200);
sensor_init(m_i2cPorts[0], m_i2cPorts[1]);
setupLcd();
button_setup();
activityLed_setup();
ota_setup();
wifi_setup();
mqtt_setup();
txSwitchState();
txTemperatureState();
Serial.println("Setup complete, starting loop...");
}
void loop()
{
handleScreen();
handleButton();
ArduinoOTA.handle();
if (!client.loop())
{
mqtt_setup();
}
// transmit temperature and humidity
if (millis() > m_LastTempTransmit + (60 * 1000))
{
txTemperatureState();
m_LastTempTransmit = millis();
}
// safeguard max on duration
for (int i = 1; i <= NUMPORTS; i++)
{
if ((getSwitch(i) == "ON") && (millis() > (m_LastOnTime[i - 1] + m_MaxOnDuration)))
{
setSwitch(i, false);
Serial.printf("Emergency shutoff on port: %d!\n", i);
}
}
}
void button_setup()
{
pinMode(m_Button, INPUT);
}
void activityLed_setup()
{
pinMode(m_ActivityLed, OUTPUT);
digitalWrite(m_ActivityLed, LOW);
}
void ota_setup()
{
Serial.println("OTA setup...");
m_Lcd.clear();
m_Lcd.print("OTA setup...");
m_Lcd.setCursor(0, 1);
ArduinoOTA.onStart([]()
{
String type;
if (ArduinoOTA.getCommand() == U_FLASH)
{
type = "sketch";
}
else
{ // U_FS
type = "filesystem";
}
// NOTE: if updating FS this would be the place to unmount FS using FS.end()
Serial.println("OTA Start updating " + type);
m_Lcd.clear();
m_Lcd.print("OTA Start...");
m_Lcd.setCursor(0, 1); });
ArduinoOTA.onEnd([]()
{
Serial.println("\nOTA End");
m_Lcd.clear();
m_Lcd.print("OTA End");
delay(1000); });
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total)
{
Serial.printf("OTA Progress: %u%%\r\n", (progress / (total / 100)));
if ((progress / (total / 100)) % 10 == 0)
{
m_Lcd.setCursor(0, 1);
m_Lcd.print("OTA progress ");
m_Lcd.print(progress / (total / 100));
m_Lcd.print("%");
} });
ArduinoOTA.onError([](ota_error_t error)
{
Serial.printf("OTA Error[%u]: ", error);
m_Lcd.clear();
m_Lcd.print("OTA Error:");
m_Lcd.setCursor(0, 1);
if (error == OTA_AUTH_ERROR)
{
Serial.println("Auth Failed");
m_Lcd.print("Auth Failed");
}
else if (error == OTA_BEGIN_ERROR)
{
Serial.println("Begin Failed");
m_Lcd.print("Begin Failed");
}
else if (error == OTA_CONNECT_ERROR)
{
Serial.println("Connect Failed");
m_Lcd.print("Connect Failed");
}
else if (error == OTA_RECEIVE_ERROR)
{
Serial.println("Receive Failed");
m_Lcd.print("Receive Failed");
}
else if (error == OTA_END_ERROR)
{
Serial.println("End Failed");
m_Lcd.print("End Failed");
}
delay(1000); });
ArduinoOTA.setPassword("admin");
ArduinoOTA.begin();
Serial.println("OTA setup done");
m_Lcd.print("OTA setup done");
delay(1000);
}
void wifi_setup()
{
// Connect to WiFi
WiFi.mode(WIFI_STA);
WiFi.hostname("Regnerdings");
WiFi.begin(m_Ssid, m_Pass);
Serial.println("Connecting to WiFi...");
m_Lcd.clear();
m_Lcd.print("WiFi connecting");
m_Lcd.setCursor(0, 1);
while (WiFi.status() != WL_CONNECTED)
{
delay(100);
}
Serial.printf("WiFi connected: %s, RSSI: %d\n", WiFi.localIP().toString().c_str(), WiFi.RSSI());
m_Lcd.print("WiFi connected!");
delay(2000);
m_Lcd.clear();
}
void mqtt_setup()
{
client.setServer("homeassistant.home", 1883);
client.setCallback(mqtt_callback);
client.setBufferSize(1024);
// connect to MQTT broker
if (!client.connected())
{
while (!client.connected())
{
Serial.println("Connecting to MQTT...");
m_Lcd.setCursor(0, 0);
m_Lcd.print("MQTT connecting");
m_Lcd.setCursor(0, 1);
client.connect("Regnerdings", "mosquitto", "mosquitto", "/home/state", 1, true, "offline");
delay(100);
if (!client.connected())
{
Serial.printf("MQTT Error: %d\n", client.state());
m_Lcd.print("Error: ");
m_Lcd.print(client.state());
}
delay(1000);
}
Serial.println("Connected to MQTT");
m_Lcd.print("MQTT connected!");
delay(2000);
m_Lcd.clear();
char topic[100];
char cfgMsg[1024];
m_Lcd.print("HA config...");
m_Lcd.setCursor(0, 1);
// configure device temp
strcpy(topic, "disc/sensor/Regnerdings/T/config");
strcpy(cfgMsg, "{");
sprintf(cfgMsg + strlen(cfgMsg), " \"name\": \"Temperature\",");
sprintf(cfgMsg + strlen(cfgMsg), " \"unique_id\": \"Regnerdings_Temperature\",");
sprintf(cfgMsg + strlen(cfgMsg), " \"device\": { \"ids\" : [\"Regnerdings\"], \"name\" : \"Regnerdings\", \"mf\": \"xmirakulix\", \"mdl\": \"Regnerdings\", \"sw\": \"%s\" },", m_CompileDate);
sprintf(cfgMsg + strlen(cfgMsg), " \"device_class\": \"temperature\",");
sprintf(cfgMsg + strlen(cfgMsg), " \"unit_of_measurement\": \"°C\",");
sprintf(cfgMsg + strlen(cfgMsg), " \"value_template\":\"{{ value_json.temperature}}\",");
sprintf(cfgMsg + strlen(cfgMsg), " \"state_topic\": \"disc/sensor/Regnerdings/state\"");
sprintf(cfgMsg + strlen(cfgMsg), "}");
Serial.println("Sending temperature config message to HA");
client.publish(topic, cfgMsg, true);
// configure device humidity
strcpy(topic, "disc/sensor/Regnerdings/H/config");
strcpy(cfgMsg, "{");
sprintf(cfgMsg + strlen(cfgMsg), " \"name\": \"Humidity\",");
sprintf(cfgMsg + strlen(cfgMsg), " \"unique_id\": \"Regnerdings_Humidity\",");
sprintf(cfgMsg + strlen(cfgMsg), " \"device\": { \"identifiers\" : [\"Regnerdings\"], \"name\" : \"Regnerdings\" },");
sprintf(cfgMsg + strlen(cfgMsg), " \"device_class\": \"humidity\",");
sprintf(cfgMsg + strlen(cfgMsg), " \"unit_of_measurement\": \"%%\",");
sprintf(cfgMsg + strlen(cfgMsg), " \"value_template\":\"{{ value_json.humidity}}\",");
sprintf(cfgMsg + strlen(cfgMsg), " \"state_topic\": \"disc/sensor/Regnerdings/state\"");
sprintf(cfgMsg + strlen(cfgMsg), "}");
Serial.println("Sending humidity config message to HA");
client.publish(topic, cfgMsg, true);
for (int i = 1; i <= NUMPORTS; i++)
{
char cmd_topic[50];
// configure Ports
sprintf(topic, "disc/valve/Regnerdings/P%d/config", i);
sprintf(cmd_topic, "disc/valve/Regnerdings/P%d/set", i);
strcpy(cfgMsg, "{");
sprintf(cfgMsg + strlen(cfgMsg), " \"name\": \"P%d\",", i);
sprintf(cfgMsg + strlen(cfgMsg), " \"unique_id\": \"Regnerdings_P%d\",", i);
sprintf(cfgMsg + strlen(cfgMsg), " \"device\": { \"identifiers\" : [\"Regnerdings\"], \"name\" : \"Regnerdings\" },");
sprintf(cfgMsg + strlen(cfgMsg), " \"device_class\": \"water\",");
sprintf(cfgMsg + strlen(cfgMsg), " \"icon\": \"mdi:sprinkler\",");
sprintf(cfgMsg + strlen(cfgMsg), " \"value_template\":\"{{ value_json.P%d}}\",", i);
sprintf(cfgMsg + strlen(cfgMsg), " \"payload_open\": \"ON\",");
sprintf(cfgMsg + strlen(cfgMsg), " \"state_open\": \"ON\",");
sprintf(cfgMsg + strlen(cfgMsg), " \"payload_close\": \"OFF\",");
sprintf(cfgMsg + strlen(cfgMsg), " \"state_closed\": \"OFF\",");
sprintf(cfgMsg + strlen(cfgMsg), " \"state_topic\": \"disc/valve/Regnerdings/state\",");
sprintf(cfgMsg + strlen(cfgMsg), " \"command_topic\": \"%s\"", cmd_topic);
sprintf(cfgMsg + strlen(cfgMsg), "}");
Serial.printf("Sending P%d config message to HA\n", i);
client.publish(topic, cfgMsg, true);
client.subscribe(cmd_topic);
pinMode(m_Ports[i - 1], OUTPUT);
setSwitch(i, false);
}
Serial.println("Config message sent, client state: " + String(client.state()));
enableLcdBacklight();
m_Lcd.print("HA config sent!");
delay(2000);
m_Lcd.clear();
}
}
void handleScreen()
{
handleLcdBacklight();
if (m_LastButtonAction == SHORT)
{
m_LastButtonAction = HANDLED;
enableLcdBacklight();
if (++m_EditPort > NUMPORTS)
{
m_EditPort = 1;
}
Serial.printf("Screen handling SHORT, port: %d\n", m_EditPort);
m_LastScreenUpdate = 0;
}
else if (m_LastButtonAction == LONG)
{
m_LastButtonAction = HANDLED;
enableLcdBacklight();
if (m_EditPort > 0)
{
if (getSwitch(m_EditPort) == "ON")
{
setSwitch(m_EditPort, false);
}
else
{
setSwitch(m_EditPort, true);
}
}
Serial.printf("Screen handling LONG, port %d: %s\n", m_EditPort, getSwitch(m_EditPort).c_str());
m_LastScreenUpdate = 0;
}
if ((m_EditPort != 0) && (millis() > (m_LastButtonPressed + 10 * 1000)))
{
m_EditPort = 0;
}
if (millis() > (m_LastScreenUpdate + 300))
{
m_LastScreenUpdate = millis();
char line[17];
// m_Lcd.clear();
m_Lcd.setCursor(0, 0);
sprintf(line, " T:%d%cC H:%d%% ", m_LastTemperature, 0xDF, m_LastHumidity);
m_Lcd.print(line);
m_Lcd.setCursor(0, 1);
strcpy(line, "Ports:");
for (int i = 1; i <= NUMPORTS; i++)
{
bool act = getSwitch(i) == "ON" ? true : false;
strcat(line, " ");
if (m_EditPort == i)
{
enableLcdBacklight();
char c = getEditChar();
if (c == 'x')
{
sprintf(line + strlen(line), "%c", act ? '>' : '-');
}
else
{
sprintf(line + strlen(line), "%c", c);
}
}
else
{
sprintf(line + strlen(line), "%c", act ? '>' : '-');
}
}
m_Lcd.print(line);
}
}
void handleButton()
{
// still unhandled button press active
if (m_LastButtonAction > 0)
{
return;
}
int newState = digitalRead(m_Button);
// new button press detected
if (!m_ButtonPressed && (newState == LOW))
{
m_LastButtonPressed = millis();
m_ButtonPressed = true;
Serial.println("Button pressed");
return;
}
// button no longer presssed and was short
if (m_ButtonPressed && (newState == HIGH) && ((millis() - m_LastButtonPressed) < 500) && (m_LastButtonAction == NONE))
{
m_LastButtonAction = SHORT;
m_ButtonPressed = false;
Serial.println("Button action short detected");
}
// button still pressed, but already long
else if (m_ButtonPressed && (millis() > (m_LastButtonPressed + 1000)) && (m_LastButtonAction == NONE))
{
m_LastButtonAction = LONG;
Serial.println("Button action long detected");
}
// button no longer pressed
else if (m_ButtonPressed && (newState == HIGH))
{
m_ButtonPressed = false;
Serial.println("Button no longer pressed, no action detected");
}
if (!m_ButtonPressed && (m_LastButtonAction == HANDLED))
{
m_LastButtonAction = NONE;
Serial.println("Button not pressed and handle finished");
}
}
void mqtt_callback(char *topic, byte *payload, unsigned int length)
{
char msg[50] = "";
for (byte i = 0; i < length; i++)
{
msg[i] = (char)payload[i];
}
int port = parsePort(topic);
Serial.printf("Message received on port '%d': %s\n", port, msg);
if (strcmp(msg, "ON") == 0)
{
setSwitch(port, true);
}
else if (strcmp(msg, "OFF") == 0)
{
setSwitch(port, false);
}
else
{
Serial.printf("Unknown message: %s\n", msg);
}
}
// transmit temperature and humidity to HA
void txTemperatureState()
{
m_LastTemperature = read_temperature();
m_LastHumidity = read_humidity();
char mqtt_state[100];
sprintf(mqtt_state, "{ \"temperature\": %d, \"humidity\": %d }", m_LastTemperature, m_LastHumidity);
Serial.printf("Temp/Humid state: %s\n", mqtt_state);
client.publish("disc/sensor/Regnerdings/state", mqtt_state, false);
}
// transmit state of all switches to HA
void txSwitchState()
{
String mqtt_state = "{";
for (int i = 1; i <= NUMPORTS; i++)
{
mqtt_state += "\"P" + String(i) + "\" : \"" + getSwitch(i) + "\", ";
}
mqtt_state = mqtt_state.substring(0, mqtt_state.length() - 2);
mqtt_state += "}";
Serial.printf("Switch state: %s\n", mqtt_state.c_str());
client.publish("disc/valve/Regnerdings/state", mqtt_state.c_str(), false);
setActivityLed();
}
// get the state of a switch, "ON" or "OFF"
String getSwitch(int port)
{
return m_SwitchState[port - 1] ? "ON" : "OFF";
}
// operate the switch on the given port
void setSwitch(int port, bool state)
{
if (state)
{
digitalWrite(m_Ports[port - 1], HIGH); // ON
m_LastOnTime[port - 1] = millis();
}
else
{
digitalWrite(m_Ports[port - 1], LOW); // OFF
m_LastOnTime[port - 1] = 0;
}
m_SwitchState[port - 1] = state;
txSwitchState();
m_LastScreenUpdate = 0;
}
void setActivityLed()
{
for (int i = 1; i <= NUMPORTS; i++)
{
if (getSwitch(i) == "ON")
{
digitalWrite(m_ActivityLed, HIGH);
return;
}
}
digitalWrite(m_ActivityLed, LOW);
}
// parse port from topic
int parsePort(String msg)
{
return msg.substring(msg.lastIndexOf("dings/P") + 7, msg.lastIndexOf("/")).toInt();
}