-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathblinds2mqtt.ino
355 lines (284 loc) · 9.07 KB
/
blinds2mqtt.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
// DIY Smart Blinds Controller for ESP8266 (Wemos D1 Mini)
// Supports Home Assistant MQTT auto discovery straight out of the box
// (c) Toni Korhonen 2021
// https://www.creatingsmarthome.com/?p=629
#include <ESP8266WiFi.h>
#include <Servo.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <ArduinoOTA.h>
#include <ESP8266mDNS.h>
#include "blinds2mqtt.h"
#include "BlindsServo.h"
#define SW_VERSION "0.4.0"
#define JSON_BUFFER_LENGTH 2048
#define MQTT_TOPIC_MAX_LENGTH 256
#define DEBUG false // default value for debug
// Callbacks
void mqttCallback(char* topic, byte* payload, unsigned int payloadLength);
// Wifi
WiFiClient wifiClient;
// MQTT
PubSubClient client(mqtt_server, mqtt_port, mqttCallback, wifiClient);
BlindsServo servos[sizeof(servoPins)];
// debug
bool debug = DEBUG;
int numberOfServos = 0;
int pos = 0;
String uniqueId;
unsigned long loopStart;
void setup() {
// Setup serial port
Serial.begin(115200);
uniqueId = WiFi.macAddress();
uniqueId.replace(":", "-");
wifiConnect();
// Setup OTA
initOTA();
numberOfServos = sizeof(servoPins) / sizeof(servoPins[0]);
int numberOfReversedServos = sizeof(reversedPins) / sizeof(servoPins[0]); // We might not have any servos as reversed, thus using servoPin size
Serial.print("numberOfServos = ");
Serial.println(numberOfServos);
for (int i = 0; i < numberOfServos; i++) {
unsigned int servoPin = servoPins[i];
boolean reversed = false;
// Check if servo is in reversed array
for (int r = 0; r < numberOfReversedServos; r++) {
unsigned int reversedPin = reversedPins[r];
if(servoPin == reversedPin) {
reversed = true;
break;
}
}
servos[i] = BlindsServo(i+1, servoPin, servo_min_pulse, servo_max_pulse, servo_max_angle, reversed, debug);
servos[i].setDebugPrintCallback(debugPrint);
servos[i].setStatusChangedCallback(statusChanged);
servos[i].setPositionChangedCallback(positionChanged);
}
mqttConnect();
client.setCallback(mqttCallback);
}
void wifiConnect() {
Serial.println("Connecting wifi..");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
// wait 500ms
Serial.print(".");
delay(500);
}
WiFi.mode(WIFI_STA);
// Connected to WiFi
Serial.println();
Serial.print("Connected! IP address: ");
Serial.println(WiFi.localIP());
}
void mqttConnect() {
if (!!!client.connected()) {
Serial.println("Try to connect mqtt..");
int count = 20;
while (count-- > 0 && !!!client.connect(client_id, mqtt_username, mqtt_password)) {
delay(500);
}
for (int i = 0; i < numberOfServos; i++) {
BlindsServo s = servos[i];
Serial.print("Publishing ha config for servo ");
Serial.println(String(s.getId()));
subscribeAndPublishConfig(s.getId());
}
}
}
void initOTA() {
ArduinoOTA.setHostname(client_id);
ArduinoOTA.setPassword(ota_password);
ArduinoOTA.begin();
}
void loop()
{
// check that we are connected
if (!client.loop()) {
mqttConnect();
}
unsigned long now = millis();
if(now - loopStart >= turnTime) {
// Over one sec from start loop passed
loopStart = now;
// Main servo loop
for (int i = 0; i < numberOfServos; i++) {
servos[i].loop();
}
}
// Rest of the loop
MDNS.update();
ArduinoOTA.handle();
}
BlindsServo& servoById(int id) {
for (int i = 0; i < numberOfServos; i++) {
BlindsServo& s = servos[i];
if (s.getId() == id) {
return s;
}
}
}
String getValue(String data, char separator, int index)
{
int found = 0;
int strIndex[] = {0, -1};
int maxIndex = data.length()-1;
for(int i=0; i<=maxIndex && found<=index; i++){
if(data.charAt(i)==separator || i==maxIndex){
found++;
strIndex[0] = strIndex[1]+1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}
// MQTT
void subscribeAndPublishConfig(int servoId) {
// Subscribe to servo topic
char topic[MQTT_TOPIC_MAX_LENGTH];
sprintf(topic, blinds_command_topic, uniqueId.c_str(), servoId);
if (client.subscribe(topic)) {
// OK
debugPrint("Subscribed to blinds set topic (" + String(servoId) + "), uniqueId = " + uniqueId);
} else {
// FAIL
debugPrint("Failed to subscribe to blinds set topic (" + String(servoId) + ")");
}
char set_position_t[MQTT_TOPIC_MAX_LENGTH];
sprintf(set_position_t, blinds_set_position_topic, uniqueId.c_str(), servoId);
if (client.subscribe(set_position_t)) {
// OK
debugPrint("Subscribed to blinds set position topic (" + String(servoId) + "), uniqueId = " + uniqueId);
publishConfig(servoId); // Publish config right after subscribed to command topic
} else {
// FAIL
debugPrint("Failed to subscribe to blinds set topic (" + String(servoId) + ")");
}
publishConfig(servoId); // Publish config right after subscribed to command topic
}
void mqttCallback(char* topic, byte * payload, unsigned int length) {
Serial.print("Got MQTT callback! ");
Serial.print("topic = ");
Serial.println(topic);
String myString = String(topic);
String v = getValue(topic, '/', 2); // Get the second value
if (!v.length()) {
return;
}
int servoId = v.toInt(); // Get servo id
// Check
if (getValue(topic, '/', 0) == "blinds") { //Ensure blinds topic
if(getValue(topic, '/', 1) == uniqueId) { // Ensure correct device
String thirdValue = getValue(topic, '/', 3);
if(thirdValue == "set") { // Ensure set topic
handleSet(payload, length, servoId);
} else if(thirdValue == "position") {
String fourthValue = getValue(topic, '/', 4);
if(fourthValue == "set") { // Ensure set topic
handleSetPosition(payload, length, servoId);
}
}
}
}
}
void handleSet(byte * payload, unsigned int length, int servoId) {
BlindsServo& s = servoById(servoId);
if (!strncmp((char *)payload, "OPEN", length)) {
s.setOpen();
} else if (!strncmp((char *)payload, "CLOSE", length)) {
s.setClose();
} else if (!strncmp((char *)payload, "STOP", length)) {
s.setStop();
}
}
void handleSetPosition(byte * payload, unsigned int length, int servoId) {
BlindsServo& s = servoById(servoId);
String myString = (char*)payload;
int pos = myString.toInt();
if(pos >= 0 && pos <= 100) {
s.goToPosition(pos);
}
}
void publishConfig(int servoId) {
Serial.println("Publishing ha config.");
DynamicJsonDocument root(JSON_BUFFER_LENGTH);
// State topic
char state_t[MQTT_TOPIC_MAX_LENGTH];
sprintf(state_t, blinds_state_topic, uniqueId.c_str(), servoId);
root["state_topic"] = state_t;
// Command topic
char command_t[MQTT_TOPIC_MAX_LENGTH];
sprintf(command_t, blinds_command_topic, uniqueId.c_str(), servoId);
root["command_topic"] = command_t;
// Position topics
char position_t[MQTT_TOPIC_MAX_LENGTH];
sprintf(position_t, blinds_position_topic, uniqueId.c_str(), servoId);
root["position_topic"] = position_t;
char set_position_t[MQTT_TOPIC_MAX_LENGTH];
sprintf(set_position_t, blinds_set_position_topic, uniqueId.c_str(), servoId);
root["set_position_topic"] = set_position_t;
// Others
root["name"] = numberOfServos > 1 ? friendly_name + " " + String(servoId) : friendly_name;
root["device_class"] = "blind";
root["unique_id"] = "blinds/" + uniqueId + "/servo" + String(servoId);
// Device
addDevice(root);
// Publish
String mqttOutput;
serializeJson(root, mqttOutput);
char t[MQTT_TOPIC_MAX_LENGTH];
sprintf(t, ha_config_topic, uniqueId.c_str(), servoId);
client.beginPublish(t, mqttOutput.length(), true);
client.print(mqttOutput);
client.endPublish();
}
void addDevice(DynamicJsonDocument& root) {
JsonObject device = root.createNestedObject("device");
JsonArray identifiers = device.createNestedArray("identifiers");
identifiers.add(uniqueId.c_str());
device["name"] = "blinds2mqtt";
device["model"] = "esp8266";
device["sw_version"] = SW_VERSION;
}
//Callbacks
void debugPrint(String message) {
if (debug) {
Serial.println(message);
// publish to debug topic
char t[MQTT_TOPIC_MAX_LENGTH];
sprintf(t, blinds_debug_topic, uniqueId.c_str());
client.publish(t, message.c_str());
}
}
void positionChanged(int servoId) {
// Do nothing, only inform position when status is changed
}
void statusChanged(int servoId) {
BlindsServo& s = servoById(servoId);
String statusMsg = "OPEN";
switch(s.getStatus()) {
case BlindsServo::OPEN:
statusMsg = "open";
break;
case BlindsServo::CLOSED:
statusMsg = "closed";
break;
case BlindsServo::CLOSING:
statusMsg = "closing";
break;
case BlindsServo::OPENING:
statusMsg = "opening";
break;
default:
break;
}
// Publish status
char t[MQTT_TOPIC_MAX_LENGTH];
sprintf(t, blinds_state_topic, uniqueId.c_str(), servoId);
client.publish(t, statusMsg.c_str(), retain_status);
// Publish position
char position_t[MQTT_TOPIC_MAX_LENGTH];
sprintf(position_t, blinds_position_topic, uniqueId.c_str(), servoId);
client.publish(position_t, String(s.currentAngleInPercent()).c_str(), retain_position);
}