-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathhass.c
570 lines (456 loc) · 18.3 KB
/
hass.c
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
//***************************************************************************
// Automation Control
// File hass.c
// This code is distributed under the terms and conditions of the
// GNU GENERAL PUBLIC LICENSE. See the file LICENSE for details.
// Date 04.11.2010 - 25.04.2020 Jörg Wendel
//***************************************************************************
#include <jansson.h>
#include <algorithm>
#include "lib/json.h"
#include "daemon.h"
//***************************************************************************
// Push Value to MQTT for Home Automation Systems
//***************************************************************************
int Daemon::mqttHaPublish(SensorData& sensor, bool forceConfig)
{
if (isEmpty(mqttUrl) || mqttHaInterfaceStyle == misNone)
return done;
if (mqttCheckConnection() != success)
return fail;
if (mqttHaInterfaceStyle == misGroupedTopic)
{
if (!groups[sensor.group].oHaJson)
groups[sensor.group].oHaJson = json_object();
}
if (mqttHaInterfaceStyle == misSingleTopic || mqttHaInterfaceStyle == misGroupedTopic)
jsonAddValue(mqttHaInterfaceStyle == misSingleTopic ? oHaJson : groups[sensor.group].oHaJson, sensor, forceConfig);
else if (mqttHaInterfaceStyle == misMultiTopic)
mqttHaPublishSensor(sensor, forceConfig);
// write
if (mqttHaInterfaceStyle == misSingleTopic)
{
mqttHaWrite(oHaJson, 0);
json_decref(oHaJson);
oHaJson = nullptr;
}
else if (mqttHaInterfaceStyle == misGroupedTopic)
{
tell(eloDebug2, "Debug: Writing MQTT for %zu groups", groups.size());
for (auto it : groups)
{
if (it.second.oHaJson)
{
mqttHaWrite(it.second.oHaJson, it.first);
json_decref(groups[it.first].oHaJson);
groups[it.first].oHaJson = nullptr;
}
}
}
return done;
}
//***************************************************************************
// Push Value to MQTT for Home Automation Systems
//***************************************************************************
int Daemon::mqttHaPublishSensor(SensorData& sensor, bool forceConfig)
{
if (sensor.type == "")
return done;
// publish actual value
if (!mqttWriter->isConnected())
{
tell(eloAlways, "Aborting MQTT publish, not connected!");
return fail;
}
// check if state topic already exists
MemoryStruct message;
std::string tp;
std::string sName = sensor.name;
IoType iot = sensor.type == "DZL" ? iotLight : iotSensor;
sName = strReplace("ß", "ss", sName);
sName = strReplace("ü", "ue", sName);
sName = strReplace("ö", "oe", sName);
sName = strReplace("ä", "ae", sName);
sName = strReplace(" ", "_", sName);
// mqttHaDataTopic like "XXX2mqtt/<TYPE>/<NAME>/state"
std::string sDataTopic = mqttHaDataTopic;
sDataTopic = strReplace("<NAME>", sName, sDataTopic);
sDataTopic = strReplace("<TYPE>", iot == iotLight ? "light" : "sensor", sDataTopic);
// mqttHaDataTopic like "XXX2mqtt/<TYPE>/<NAME>/state"
if (mqttHaHaveConfigTopic && sensor.title.length())
{
// Interface description:
// https://www.home-assistant.io/docs/mqtt/discovery/
bool exists = std::find(configTopicsFor.begin(), configTopicsFor.end(), sDataTopic) != configTopicsFor.end();
if (forceConfig || !exists)
{
char* configTopic {};
char* configJson {};
// topic don't exists -> create sensor
if (strcmp(sensor.unit.c_str(), "°") == 0)
sensor.unit = "°C";
else if (sensor.unit == "Heizungsstatus" ||
sensor.unit == "zst" ||
sensor.unit == "txt")
sensor.unit = "";
asprintf(&configTopic, "homeassistant/%s/%s/%s/config",
iot == iotLight ? "light" : "sensor", myTitle(), sName.c_str());
tell(eloMqtt, "Info: Sensor '%s' not found at home assistants MQTT, "
"sendig config message to '%s'", sName.c_str(), configTopic);
if (iot == iotLight)
{
char* cmdTopic {};
asprintf(&cmdTopic, TARGET "2mqtt/light/%s/set", sName.c_str());
asprintf(&configJson, "{"
"\"state_topic\" : \"%s\","
"\"command_topic\" : \"%s\","
"\"name\" : \"%s %s\","
"\"unique_id\" : \"%s_" TARGET "2mqtt\","
"\"schema\" : \"json\","
"\"brightness\" : \"false\","
"\"device\": {"
"\"identifiers\": ["
"\"%s\""
"],"
"\"name\" : \"%s\","
"\"model\" : \"p4-daemon\","
"\"manufacturer\" : \"@horchi\","
"\"sw_version\" : \"" _VERSION "\""
"}"
"}",
sDataTopic.c_str(), cmdTopic, myTitle(), sensor.title.c_str(), sName.c_str(), myTitle(), myTitle());
hassCmdTopicMap[cmdTopic] = sensor.name;
free(cmdTopic);
}
else
{
if (!sensor.unit.empty())
asprintf(&configJson, "{"
"\"state_topic\" : \"%s\","
"\"unit_of_measurement\" : \"%s\","
"\"value_template\" : \"{{ value_json.value }}\","
"\"name\" : \"%s\","
"\"unique_id\" : \"%s_" TARGET "2mqtt\","
"\"device\": {"
"\"identifiers\": ["
"\"%s\""
"],"
"\"name\" : \"%s\","
"\"model\" : \"p4-daemon\","
"\"manufacturer\" : \"@horchi\","
"\"sw_version\" : \"" _VERSION "\""
"}"
"}",
sDataTopic.c_str(), sensor.unit.c_str(), sensor.title.c_str(), sName.c_str(), myTitle(), myTitle());
else
asprintf(&configJson, "{"
"\"state_topic\" : \"%s\","
"\"value_template\" : \"{{ value_json.value }}\","
"\"name\" : \"%s\","
"\"unique_id\" : \"%s_" TARGET "2mqtt\","
"\"device\": {"
"\"identifiers\": ["
"\"%s\""
"],"
"\"name\" : \"%s\","
"\"model\" : \"p4-daemon\","
"\"manufacturer\" : \"@horchi\","
"\"sw_version\" : \"" _VERSION "\""
"}"
"}",
sDataTopic.c_str(), sensor.title.c_str(), sName.c_str(), myTitle(), myTitle());
}
mqttWriter->writeRetained(configTopic, configJson);
configTopicsFor.push_back(sDataTopic);
free(configTopic);
free(configJson);
}
}
json_t* oValue = json_object();
if (sensor.kind == "status")
{
json_object_set_new(oValue, "state", json_string(sensor.state ? "ON" :"OFF"));
json_object_set_new(oValue, "brightness", json_integer(255));
}
else if (sensor.text.length())
json_object_set_new(oValue, "value", json_string(sensor.text.c_str()));
else if (sensor.kind == "value")
json_object_set_new(oValue, "value", json_real(sensor.value));
char* j = json_dumps(oValue, JSON_PRESERVE_ORDER); // |JSON_REAL_PRECISION(5));
mqttWriter->writeRetained(sDataTopic.c_str(), j);
free(j);
json_decref(oValue);
return success;
}
//***************************************************************************
// MQTT Write (to Home Automation Systems)
//***************************************************************************
int Daemon::mqttHaWrite(json_t* obj, uint groupid)
{
std::string sDataTopic = mqttHaDataTopic;
// check/prepare connection
if (mqttCheckConnection() != success)
return fail;
char* message = json_dumps(obj, JSON_REAL_PRECISION(4));
if (mqttHaInterfaceStyle == misGroupedTopic)
sDataTopic = strReplace("<GROUP>", groups[groupid].name, sDataTopic);
int status = mqttWriter->write(sDataTopic.c_str(), message);
free(message);
return status;
}
//***************************************************************************
// Perform MQTT Requests
// - check 'mqttHassCommandReader' for commands of a home automation
// - check 'mqttReader' for data from the W1 service and the arduino, etc ...
// -> w1mqtt (W1 service) is running localy and provide data of the W1 sensors
// -> the arduino provide the values of his analog inputs
//***************************************************************************
int Daemon::performMqttRequests()
{
static time_t lastMqttRead {0};
static time_t lastMqttRecover {0};
if (isEmpty(mqttUrl))
return done;
if (!lastMqttRead)
lastMqttRead = time(0);
mqttCheckConnection();
if (!mqttReader->isConnected())
return done;
MemoryStruct message;
// tell(eloMqtt, "Try reading topic '%s'", mqttReader->getTopic());
while (mqttReader->read(&message, 10) == success)
{
if (isEmpty(message.memory))
continue;
lastMqttRead = time(0);
std::string tp = mqttReader->getLastReadTopic();
tell(eloMqtt, "<- (%s) [%s] retained %d", tp.c_str(), message.memory, mqttReader->isRetained());
if (strstr(tp.c_str(), "2mqtt/ping"))
;
else if (strstr(tp.c_str(), "2mqtt/w1"))
dispatchW1Msg(message.memory);
else if (strstr(tp.c_str(), "2mqtt/arduino/out"))
dispatchArduinoMsg(message.memory);
else if (strstr(tp.c_str(), "2mqtt/homematic/rpcresult"))
dispatchHomematicRpcResult(message.memory);
else if (strstr(tp.c_str(), "2mqtt/homematic/events"))
dispatchHomematicEvents(message.memory);
else if (strstr(tp.c_str(), "growatt/solar"))
dispatchGrowattEvents(message.memory);
else if (strstr(tp.c_str(), "rtl_433"))
dispatchRtl433(message.memory);
else if (strstr(tp.c_str(), "2mqtt/light/"))
{
json_t* jData = jsonLoad(message.memory);
if (jData)
{
dispatchMqttHaCommandRequest(jData, tp.c_str());
json_decref(jData);
}
}
else if (strstr(tp.c_str(), "2mqtt/command") || strstr(tp.c_str(), "2mqtt/nodered"))
{
json_t* jData = jsonLoad(message.memory);
if (jData)
{
dispatchNodeRedCommands(tp.c_str(), jData);
json_decref(jData);
}
}
else
{
dispatchOther(tp.c_str(), message.memory);
}
}
// last successful MQTT read at least in last 5 minutes?
if (lastMqttRead < time(0)-300 && lastMqttRecover < time(0)-60)
{
lastMqttRecover = time(0);
tell(eloAlways, "No update from MQTT since '%s', disconnect from MQTT to force recover", l2pTime(lastMqttRead).c_str());
mqttDisconnect();
}
return success;
}
//***************************************************************************
// Check MQTT Disconnect
//***************************************************************************
int Daemon::mqttDisconnect()
{
if (mqttReader) mqttReader->disconnect();
if (mqttWriter) mqttWriter->disconnect();
delete mqttReader; mqttReader = nullptr;
delete mqttWriter; mqttWriter = nullptr;
tell(eloMqtt, "Disconnected from MQTT");
return done;
}
//***************************************************************************
// Check MQTT Connection and Connect
//***************************************************************************
int Daemon::mqttCheckConnection()
{
const char* mqttPingTopic = TARGET "2mqtt/ping";
static time_t lastMqttPing {0};
if (isEmpty(mqttUrl))
return done;
if (!mqttReader)
mqttReader = new Mqtt();
if (!mqttWriter)
mqttWriter = new Mqtt();
if (mqttReader->isConnected() && mqttWriter->isConnected())
{
if (lastMqttPing < time(0)-30)
{
lastMqttPing = time(0);
mqttWriter->write(mqttPingTopic, "{\"ping\" : true, \"sender\" : \"" TARGET "\"}");
}
return success;
}
// retry connect all 20 seconds
if (lastMqttConnectAt >= time(0) - 20)
return fail;
if (lastMqttConnectAt)
tell(eloAlways, "Error: MQTT connection broken, trying reconnect");
lastMqttConnectAt = time(0);
// connect reader
if (!mqttWriter->isConnected())
{
// #TODO - we need a connect timeout (for all mqtt->connect calls)!
if (mqttWriter->connect(mqttUrl, mqttUser, mqttPassword) != success)
{
tell(eloAlways, "Error: MQTT: Connecting publisher to '%s' failed", mqttUrl);
return fail;
}
tell(eloMqtt, "MQTT: Connecting publisher to '%s' succeeded", mqttUrl);
}
// connect writer
if (!mqttReader->isConnected())
{
if (mqttReader->connect(mqttUrl, mqttUser, mqttPassword) != success)
{
tell(eloAlways, "Error: MQTT: Connecting subscriber to '%s' failed", mqttUrl);
return fail;
}
tell(eloMqtt, "MQTT: Connecting subscriber to '%s' succeeded", mqttUrl);
for (const auto& t : mqttSensorTopics)
{
mqttReader->subscribe(t.c_str());
tell(eloMqtt, "MQTT: Connecting subscriber to '%s' - '%s' succeeded", mqttUrl, t.c_str());
}
}
return success;
}
//***************************************************************************
// Publish to Node-Red (on change)
//***************************************************************************
int Daemon::mqttNodeRedPublishSensor(SensorData& sensor)
{
return mqttNodeRedPublishAction(sensor, sensor.value, true);
}
int Daemon::mqttNodeRedPublishAction(SensorData& sensor, double value, bool publishOnly)
{
if (!mqttWriter || !mqttWriter->isConnected())
return done;
json_t* oJson = json_object();
char* key {};
asprintf(&key, "%s:0x%02x", sensor.type.c_str(), sensor.address);
json_object_set_new(oJson, "id", json_string(key));
free(key);
json_object_set_new(oJson, "type", json_string(sensor.type.c_str()));
json_object_set_new(oJson, "name", json_string(sensor.title.c_str()));
json_object_set_new(oJson, "unit", json_string(sensor.unit.c_str()));
json_object_set_new(oJson, "state", json_string(sensor.state ? "on" : "off"));
json_object_set_new(oJson, "value", json_real(value));
if (!publishOnly)
{
// an action is to be triggered
if (sensor.type == "HMB")
{
json_object_set_new(oJson, "action", json_string(sensor.working ? "STOP" : "LEVEL"));
json_object_set_new(oJson, "uuid", json_string(homeMaticUuids[sensor.address].c_str()));
}
else
json_object_set_new(oJson, "action", json_string("ACTION"));
}
else
json_object_set_new(oJson, "action", json_string("CHANGE"));
char* message = json_dumps(oJson, JSON_REAL_PRECISION(4));
json_decref(oJson);
tell(eloNodeRed, "-> (node-red) (%s) [%s]", TARGET "2mqtt/changes", message);
int status = mqttWriter->write(TARGET "2mqtt/changes", message);
free(message);
return status;
}
//***************************************************************************
// Json Add Value
//***************************************************************************
int Daemon::jsonAddValue(json_t* obj, SensorData& sensor, bool forceConfig)
{
std::string sName = sensor.name;
bool newGroup {false};
json_t* oGroup {};
json_t* oSensor = json_object();
if (mqttHaInterfaceStyle == misSingleTopic)
{
oGroup = json_object_get(obj, groups[sensor.group].name.c_str());
if (!oGroup)
{
oGroup = json_object();
newGroup = true;
}
}
sName = strReplace("ß", "ss", sName);
sName = strReplace("ü", "ue", sName);
sName = strReplace("ö", "oe", sName);
sName = strReplace("ä", "ae", sName);
// create json
if (!isEmpty(mqttHaSendWithKeyPrefix))
{
std::string kType = mqttHaSendWithKeyPrefix + sensor.type;
json_object_set_new(obj, "type", json_string(kType.c_str()));
json_object_set_new(obj, "address", json_integer(sensor.address));
json_object_set_new(obj, "unit", json_string(sensor.unit.c_str()));
json_object_set_new(obj, "title", json_string(sensor.title.c_str()));
json_object_set_new(obj, "kind", json_string(sensor.kind.c_str()));
if (sensor.kind == "status")
{
json_object_set_new(obj, "state", json_boolean(sensor.state));
// json_object_set_new(obj, "brightness", json_integer(sensor.value));
}
else if (sensor.text.length())
json_object_set_new(obj, "text", json_string(sensor.text.c_str()));
else if (sensor.kind == "value")
json_object_set_new(obj, "value", json_real(sensor.value));
char* key {};
asprintf(&key, "%s:0x%02x", sensor.type.c_str(), sensor.address);
const char* image = getTextImage(key, sensor.text.c_str());
if (!isEmpty(image))
json_object_set_new(obj, "image", json_string(image));
free(key);
return success;
}
else if (forceConfig)
{
json_object_set_new(oSensor, "unit", json_string(sensor.unit.c_str()));
json_object_set_new(oSensor, "description", json_string(sensor.title.c_str()));
}
if (sensor.kind == "status")
{
json_object_set_new(oSensor, "state", json_string(sensor.state ? "ON" :"OFF"));
// json_object_set_new(oSensor, "brightness", json_integer(255));
}
else if (sensor.text.length())
json_object_set_new(oSensor, "value", json_string(sensor.text.c_str()));
else if (sensor.kind == "value")
json_object_set_new(oSensor, "value", json_real(sensor.value));
if (mqttHaInterfaceStyle == misSingleTopic)
{
json_object_set_new(oGroup, sName.c_str(), oSensor);
if (newGroup)
json_object_set_new(obj, groups[sensor.group].name.c_str(), oGroup);
}
else // misGroupedTopic
{
json_object_set_new(obj, sName.c_str(), oSensor);
}
return success;
}