Repository navigation
Expand file tree
/
Copy pathdaemon.c
More file actions
6648 lines (5102 loc) · 206 KB
/
Copy pathdaemon.c
File metadata and controls
6648 lines (5102 loc) · 206 KB
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//***************************************************************************
// Home Automation Control
// File daemon.c
// This code is distributed under the terms and conditions of the
// GNU GENERAL PUBLIC LICENSE. See the file LICENSE for details.
// Date 2010 - 2024 Jörg Wendel
//***************************************************************************
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#include <algorithm>
#include <cmath>
#include <libgen.h>
#include "lib/curl.h"
#include "lib/json.h"
#include "daemon.h"
#include "growatt.h"
bool HomeCtl::shutdown {false};
//***************************************************************************
// Widgets
//***************************************************************************
const char* HomeCtl::widgetTypes[] =
{
"Symbol",
"Chart",
"Text",
"Value",
"Gauge",
"Meter",
"MeterLevel",
"PlainText",
"Choice",
"SymbolValue",
"Spacer",
"Time",
"SymbolText",
"BarChart",
"SpecialSymbol",
"Level",
"Balance",
"Timer",
0
};
const char* HomeCtl::toName(WidgetType type)
{
if (type > wtUnknown && type < wtCount)
return widgetTypes[type];
return widgetTypes[wtText];
}
HomeCtl::WidgetType HomeCtl::toType(const char* name)
{
if (!name)
return wtUnknown;
for (int t = wtUnknown+1; t < wtCount; t++)
if (strcasecmp(name, widgetTypes[t]) == 0)
return (WidgetType)t;
return wtText;
}
//***************************************************************************
// Default Value Types
//***************************************************************************
HomeCtl::ValueTypes HomeCtl::defaultValueTypes[] =
{
// expression, title
{ "^VA$", "Messwerte" },
{ "^SD", "Status Laufzeiten" },
{ "^DO", "Digitale Ausgänge" },
{ "^MCPO", "Digitale Ausgänge" },
{ "^DI", "Digitale Eingänge" },
{ "^MCPI", "Digitale Eingänge" },
{ "^GPIO", "GPIO" },
{ "^W1", "One Wire Sensoren" },
{ "^SC", "Skripte" },
{ "^AO", "Analog Ausgänge" },
{ "^AI", "Analog Eingänge" },
{ "^ADS", "Analog Eingänge" },
{ "^Sp", "Weitere Sensoren" },
{ "^DZL", "DECONZ Lampen" },
{ "^DZLG", "DECONZ Lampen Gruppe" },
{ "^DZS", "DECONZ Sensoren" },
{ "^HM.*", "Home Matic" },
{ "^P4.*", "P4 Daemon" },
{ "^WEA", "Wetter" },
{ "^SUN", "Sonne" },
{ "^DHT", "Wetter" },
{ "^CV", "Calculated Values" },
{ "^PA", "Parameter" },
{ "^UD", "User Defined" },
{ "^VIC", "Victron" },
{ "^VOTRO", "Votronic" },
{ "^MOPEKA.*", "Mopeka" },
{ "", "" }
};
const char* HomeCtl::getTitleOfType(const char* type)
{
for (int i = 0; defaultValueTypes[i].typeExpression != ""; i++)
{
// tell(eloAlways, "check type '%s' against '%s'", type, defaultValueTypes[i].typeExpression.c_str());
if (rep(type, defaultValueTypes[i].typeExpression.c_str()) == success)
return defaultValueTypes[i].title.c_str();
}
return type;
}
//***************************************************************************
// Widgets - Default Properties
//***************************************************************************
HomeCtl::DefaultWidgetProperty HomeCtl::defaultWidgetProperties[] =
{
// #TODO - auf einen JSON string umstellen
// type, address, unit, widgetType, minScale, maxScale scaleStep, showPeak
{ "-", na, "*", wtMeter, 0, 45, 10, false },
{ "SPACER", na, "*", wtSpace, 0, 0, 0, false },
{ "TIME", na, "txt", wtPlainText, 0, 0, 0, true },
{ "DO", na, "*", wtSymbol, 0, 0, 0, false },
{ "DI", na, "*", wtSymbol, 0, 0, 0, false },
{ "GPIO", na, "*", wtSymbol, 0, 0, 0, false },
{ "AO", na, "*", wtMeter, 0, 45, 10, false },
{ "AI", na, "*", wtMeter, 0, 45, 10, false },
{ "SD", na, "*", wtChart, 0, 2000, 0, true },
{ "SC", na, "", wtText, 0, 0, 0, false },
{ "SC", na, "txt", wtText, 0, 0, 0, false },
{ "SC", na, "stxt",wtSymbolText, 0, 0, 0, false },
{ "SC", na, "zst", wtSymbol, 0, 0, 0, false },
{ "SC", na, "*", wtMeter, 0, 40, 10, true },
{ "UD", na, "txt", wtText, 0, 0, 0, false },
{ "UD", na, "zst", wtSymbolText, 0, 0, 0, false },
{ "UD", na, "*", wtText, 0, 0, 0, false },
{ "W1", na, "*", wtMeterLevel, 0, 40, 10, true },
{ "VA", na, "%", wtMeterLevel, 0, 100, 20, true },
{ "VA", na, "*", wtMeter, 0, 45, 10, true },
{ "HMB", na, "*",wtSymbolValue, 0, 0, 0, true },
{ "DZL", na, "*", wtSymbol, 0, 0, 0, true },
{ "DZLG", na, "*", wtSymbol, 0, 0, 0, true },
{ "DZS", na, "zst", wtSymbol, 0, 0, 0, true },
{ "DZS", na, "°C", wtMeterLevel, 0, 45, 10, true },
{ "DZS", na, "%", wtChart, 0, 0, 0, true },
{ "DZS", na, "hPa", wtChart, 0, 0, 0, true },
{ "DZS", na, "mov", wtSymbol, 0, 0, 0, true },
{ "DZS", na, "lx", wtChart, 0, 0, 0, true },
{ "DZS", na, "*", wtMeter, 0, 45, 12, true },
{ "WEA", na, "*", wtPlainText, 0, 0, 0, true },
{ "SUN", na, "*", wtPlainText, 0, 0, 0, false },
{ "N4000", na, "*", wtValue, 0, 0, 0, false },
{ "T2090", na, "*", wtValue, 0, 0, 0, true },
{ "CV", na, "txt", wtText, 0, 0, 0, true },
{ "CV", na, "°C", wtMeterLevel, 0, 0, 0, true },
{ "CV", na, "*", wtSymbol, 0, 0, 0, true },
{ "" }
};
HomeCtl::DefaultWidgetProperty* HomeCtl::getDefalutProperty(const char* type, const char* unit, int address)
{
for (int i = 0; defaultWidgetProperties[i].type != ""; i++)
{
if (defaultWidgetProperties[i].type == type)
{
bool addressMatch = defaultWidgetProperties[i].address == na || defaultWidgetProperties[i].address == address;
bool unitMatch = defaultWidgetProperties[i].unit == "*" || defaultWidgetProperties[i].unit == unit;
if (unitMatch && addressMatch)
return &defaultWidgetProperties[i];
}
}
return &defaultWidgetProperties[0]; // the default of the defaluts
}
//***************************************************************************
// Widget Defaults 2 Json
//***************************************************************************
int HomeCtl::widgetDefaults2Json(json_t* jDefaults, std::string type, std::string unit, const char* usrTitle, int address)
{
DefaultWidgetProperty* defProperty {getDefalutProperty(type.c_str(), unit.c_str(), address)};
// #TODO move to a json config
// like /etc/homectld/widget-defaults.json
// and a user config like /etc/homectld/widget-defaults-usr.json
const char* color {type != "HMB" ? "rgb(255, 255, 255)" : "rgb(0, 99, 162)"};
const char* colorOn {type != "HMB" ? "rgb(235, 197, 5)" : "rgb(255, 255, 255)"};
WidgetType widgetType {defProperty->widgetType};
if (defProperty->widgetType == wtUnknown)
{
if (unit == "°C")
widgetType = wtMeterLevel;
else if (unit == "V" || unit == "A")
widgetType = wtMeter;
else if (unit == "txt" || unit == "")
widgetType = wtText;
else if (unit == "stxt")
widgetType = wtSymbolText;
else if (unit == "sym")
widgetType = wtSymbol;
}
json_object_set_new(jDefaults, "widgettype", json_integer(widgetType));
json_object_set_new(jDefaults, "unit", json_string(unit.c_str()));
json_object_set_new(jDefaults, "scalemax", json_integer(defProperty->maxScale));
json_object_set_new(jDefaults, "scalemin", json_integer(defProperty->minScale));
json_object_set_new(jDefaults, "scalestep", json_integer(defProperty->scaleStep));
json_object_set_new(jDefaults, "showpeak", json_boolean(defProperty->showPeak));
json_object_set_new(jDefaults, "color", json_string(color));
json_object_set_new(jDefaults, "colorOn", json_string(colorOn));
const char* on {getImageFor(type, usrTitle, unit, true)};
const char* off {getImageFor(type, usrTitle, unit, false)};
if (strstr(off, "mdi:") == off)
json_object_set_new(jDefaults, "symbol", json_string(off));
else
json_object_set_new(jDefaults, "imgoff", json_string(off));
if (strstr(on, "mdi:") == on)
json_object_set_new(jDefaults, "symbolOn", json_string(on));
else
json_object_set_new(jDefaults, "imgon", json_string(on));
return done;
}
//***************************************************************************
// Get Image For
//***************************************************************************
const char* HomeCtl::getImageFor(std::string type, const char* usrTitle, std::string unit, int value)
{
// #TODO move symbol/image to getDefalutProperty() ?!!
const char* imagePath {};
if (strcasestr(usrTitle, "Pump"))
imagePath = value ? "img/icon/pump-on.gif" : "img/icon/pump-off.png";
else if (strcasestr(usrTitle, "Steckdose") || strcasestr(usrTitle, "Plug") )
imagePath = value ? "img/icon/plug-on.png" : "img/icon/plug-off.png";
else if (strcasestr(usrTitle, "UV-C") || strcasestr(usrTitle, "UVC"))
imagePath = value ? "img/icon/uvc-on.png" : "img/icon/uvc-off.png";
else if (strcasestr(usrTitle, "Shower") || strcasestr(usrTitle, "Dusche"))
imagePath = value ? "img/icon/shower-on.png" : "img/icon/shower-off.png";
else if (strcasestr(usrTitle, "VDR"))
imagePath = value ? "img/icon/vdr-on.png" : "img/icon/vdr-off.png";
else if (strcasestr(usrTitle, "VPN"))
imagePath = value ? "img/icon/vpn-on.png" : "img/icon/vpn-off.png";
else if (strcasestr(usrTitle, "SATIP"))
imagePath = value ? "img/icon/satip-on.png" : "img/icon/satip-off.png";
else if (strcasestr(usrTitle, "Music") || strcasestr(usrTitle, "Musik"))
imagePath = value ? "img/icon/note-on.png" : "img/icon/note-off.png";
else if (strcasestr(usrTitle, "Fan") || strcasestr(usrTitle, "Lüfter"))
imagePath = value ? "img/icon/fan-on.png" : "img/icon/fan-off.png";
else if (strcasestr(usrTitle, "Desktop"))
imagePath = value ? "img/icon/desktop-on.png" : "img/icon/desktop-off.png";
else if (type == "DZL" || strcasestr(usrTitle, "Licht") || strcasestr(usrTitle, "Bulb") || strcasestr(usrTitle, "Light"))
imagePath = value ? "mdi:mdi-lightbulb" : "mdi:mdi-lightbulb";
else if (type == "DI" || type == "DO" || type == "GPIO")
imagePath = value ? "mdi:mdi-toggle-switch-outline" : "mdi:mdi-toggle-switch-off-outline";
else if (unit == "mov")
imagePath = "mdi:mdi-walk";
else if (type == "HMB")
imagePath = value ? "mdi:mdi-blinds-open" : "mdi:mdi-blinds";
else if (type == "DZL")
imagePath = value ? "mdi:mdi-lightbulb-variant" : "mdi:mdi-lightbulb-variant-outline";
else if (type == "DZLG")
imagePath = value ? "mdi:mdi-lightbulb-group" : "mdi:mdi-lightbulb-group-outline";
else
imagePath = value ? "mdi:mdi-toggle-switch-outline" : "mdi:mdi-toggle-switch-off-outline";
tell(eloDebug, "Debug: Found special image for '%s/%s/%s/%d' [%s]", type.c_str(), usrTitle, unit.c_str(), value, imagePath);
return imagePath;
}
//***************************************************************************
// Object
//***************************************************************************
HomeCtl::HomeCtl()
{
nextRefreshAt = time(0) + 5;
startedAt = time(0);
cDbConnection::init();
cDbConnection::setEncoding("utf8");
cDbConnection::setHost(dbHost);
cDbConnection::setPort(dbPort);
cDbConnection::setName(dbName);
cDbConnection::setUser(dbUser);
cDbConnection::setPass(dbPass);
cCurl::create(); // create global cCurl instance
webSock = new cWebSock(this, httpPath);
}
HomeCtl::~HomeCtl()
{
exit();
delete webSock;
cCurl::destroy();
cDbConnection::exit();
free(mqttUrlPlain);
}
//***************************************************************************
// Push In Message (from WS to daemon)
//***************************************************************************
int HomeCtl::pushInMessage(const char* data)
{
cMyMutexLock lock(&messagesInMutex);
messagesIn.push(data);
return success;
}
//***************************************************************************
// Push Out Message (from daemon to WS)
//***************************************************************************
// realPrecision: significant digits of the reals; 4 fits the (float) sensor values,
// coordinates need more (4 digits round 51.0579 to 51.06 - a grid of about 1 km)
int HomeCtl::pushOutMessage(json_t* oContents, const char* event, long client, bool keepJson, int realPrecision)
{
json_t* obj {json_object()};
addToJson(obj, "event", event);
json_object_set_new(obj, "object", oContents);
char* p {json_dumps(obj, JSON_REAL_PRECISION(realPrecision))};
if (!keepJson)
json_decref(obj);
if (!p)
{
tell(eloAlways, "Error: Dumping json message for event '%s' failed", event);
return fail;
}
webSock->pushOutMessage(p, (lws*)client);
free(p);
webSock->performData(cWebSock::mtData);
return done;
}
int HomeCtl::pushDataUpdate(const char* event, long client)
{
// push all in the jsonSensorList to the 'interested' clients
if (client)
{
auto cl {wsClients[(void*)client]};
json_t* oJson {json_object()};
for (auto& sj : jsonSensorList)
json_object_set(oJson, sj.first.c_str(), sj.second);
pushOutMessage(oJson, event, client);
}
else
{
for (const auto& cl : wsClients)
{
json_t* oJson {json_object()};
for (auto& sj : jsonSensorList)
json_object_set(oJson, sj.first.c_str(), sj.second);
pushOutMessage(oJson, event, (long)cl.first);
}
}
// cleanup
// since we use the references more than once we have to do it
// by calling json_object_set instead of json_object_set_new
// therefore we have to free it by json_decref()
for (auto sj : jsonSensorList)
json_decref(sj.second);
jsonSensorList.clear();
return success;
}
//***************************************************************************
// Init / Exit
//***************************************************************************
int HomeCtl::init()
{
int status {success};
initLocale();
// initialize the dictionary
char* dictPath {};
asprintf(&dictPath, "%s/database.dat", confDir);
if (dbDict.in(dictPath) != success)
{
tell(eloAlways, "Fatal: Dictionary not loaded, aborting!");
return 1;
}
tell(eloAlways, "Dictionary '%s' loaded", dictPath);
free(dictPath);
while ((status = initDb()) != success && !doShutDown())
{
exitDb();
tell(eloAlways, "Retrying in %d seconds", 10);
doSleep(10);
}
deconz.init(this, connection);
// ---------------------------------
// check users - add default user if empty
int userCount {0};
tableUsers->countWhere("", userCount);
if (userCount <= 0)
{
tell(eloAlways, "Initially adding default user (" NAME "/" NAME ")");
md5Buf defaultPwd;
createMd5(NAME, defaultPwd);
tableUsers->clear();
tableUsers->setValue("USER", NAME);
tableUsers->setValue("PASSWD", defaultPwd);
tableUsers->setValue("TOKEN", "dein&&secret12login34token");
tableUsers->setValue("RIGHTS", 0xff); // all rights
tableUsers->store();
}
// ---------------------------------
// update the config table by the configuration definition
initConfigTable();
readConfiguration(true);
mqttCheckConnection();
gpsReceiverPublishConfig(); // the GPS script may run already
// ---------------------------------
// setup GPIO
gpio = new Gpio(myName(), confDir);
gpio->init();
// -------------------
// init values
tableValueFacts->clear();
for (bool f = selectActiveValueFacts->find(); f; f = selectActiveValueFacts->fetch())
initSensorByFact(tableValueFacts->getStrValue("TYPE"), tableValueFacts->getIntValue("ADDRESS"));
selectActiveValueFacts->freeResult();
// ---------------------------------
// apply configuration specials
applyConfigurationSpecials();
// resume a GPS tour which was active at the last shutdown
gpsTourInit();
// homeMaticInterface
if (homeMaticInterface && !homeMaticViaService()) // the service hmmqtt publishes its devices retained
{
if (mqttCheckConnection() == success && !mqttUrl.empty())
{
const char* request {"{ \"method\" : \"listDevices\" }"};
mqttWriter->write(INSTANCE "2mqtt/homematic/rpccall", request);
tell(eloHomeMatic, "-> (home-matic) '%s' to '%s'", INSTANCE "2mqtt/homematic/rpccall", request);
}
else
{
tell(eloAlways, "Error: Can't request home-matic data, MQTT connection failed");
}
}
publishVictronInit("VIC");
requestSensorInit("ALPICOOL");
requestSensorInit("KENWOOD");
// init web socket ...
while (webSock->init(webPort, webSocketPingTime, confDir, webSsl) != success)
{
tell(eloAlways, "Retrying in 2 seconds");
sleep(2);
}
initArduino();
performMqttRequests();
initScripts();
loadIoStates(); // load states of outputs on last exit
lmcInit(true);
if (!isEmpty(deconz.getHttpUrl()) && !isEmpty(deconz.getApiKey()))
deconz.initWsClient();
// deconz.initDevices();
if (!isEmpty(deconz.getHttpUrl()) && isEmpty(deconz.getApiKey()))
{
tell(eloAlways, "DECONZ: No API key for '%s' jet, try to query", deconz.getHttpUrl());
std::string result;
int status {deconz.queryApiKey(result)};
if (status != success)
{
tell(eloAlways, "DECONZ: Key result was '%s' (%d)", result.c_str(), status);
tell(eloAlways, "ACHTUNG: Initiale Registrierung bei deconz '%s' fehlgeschlagen! " \
"Unlock the deCONZ gateway and restart homectrld within the 60 seconds", deconz.getHttpUrl());
}
else
{
setConfigItem("deconzApiKey", result.c_str());
deconz.setApiKey(result.c_str());
deconz.initDevices();
}
}
addValueFact(1, "CV", 1, "Calc Sensor 1", "", "");
addValueFact(2, "WEA", 1, "Windy App by Spot ID", "", "");
addValueFact(3, "WEA", 1, "Windy App Map", "", "");
addValueFact(4, "WEA", 1, "Windy App by GPS", "", "");
lua.configure([this](sol::state& s) {
s.new_usertype<SensorData>("SensorData",
"value", sol::readonly(&SensorData::value),
"state", sol::readonly(&SensorData::state),
"text", sol::readonly(&SensorData::text),
"last", sol::property(&SensorData::last), // getters -> read-only properties
"changedAt", sol::property(&SensorData::changedAt),
"kind", sol::readonly(&SensorData::kind),
"name", sol::readonly(&SensorData::name),
"title", sol::readonly(&SensorData::title),
"unit", sol::readonly(&SensorData::unit),
"valid", sol::property(&SensorData::valid));
s.set_function("watch", [this](const std::string& wType, int wAddr) {
luaDeps[luaCurrentKey].insert({wType, wAddr});
});
s.set_function("every", [this](int seconds) { // periodic run in the own interval of the script
luaEvery[luaCurrentKey] = std::max(seconds, 1);
});
s.set_function("tell", [](int level, const std::string& msg) {
tell(static_cast<Eloquence>(level), "%s", msg.c_str());
});
s["eloAlways"] = (int)eloAlways;
s["eloInfo"] = (int)eloInfo;
s["eloDebug"] = (int)eloDebug;
s["eloLua"] = (int)eloLua;
// share config options
sol::table configTable {s.create_table()};
sol::table configMetatable {s.create_table()};
// Hook für den Zugriff: config["optionFooBar"]
configMetatable[sol::meta_function::index] = [this](sol::table t, const std::string& key) -> sol::object {
sol::state_view luaState = t.lua_state();
// Suche das Config-Item in der config Tabelle
ConfigItemType type {ctString};
// key existiert nicht in der Konfiguration
if (!this->configItemExists(key.c_str(), &type))
return sol::nil;
// Type abhängiges Auslesen über die exakte Überladung
switch (type)
{
case ConfigItemType::ctInteger:
{
int intVal {0};
this->getConfigItem(key.c_str(), intVal);
return sol::make_object(luaState, intVal);
}
case ConfigItemType::ctBitSelect:
{
long longVal {0};
this->getConfigItem(key.c_str(), longVal);
return sol::make_object(luaState, longVal);
}
case ConfigItemType::ctNum:
{
double doubleVal {0.0};
this->getConfigItem(key.c_str(), doubleVal);
return sol::make_object(luaState, doubleVal);
}
case ConfigItemType::ctBool:
{
bool boolVal {false};
this->getConfigItem(key.c_str(), boolVal);
return sol::make_object(luaState, boolVal);
}
// Alle textbasierten und restlichen Auswahllisten nutzen std::string
case ConfigItemType::ctString:
case ConfigItemType::ctText:
case ConfigItemType::ctChoice:
case ConfigItemType::ctComboChoice:
case ConfigItemType::ctMultiSelect:
case ConfigItemType::ctRange:
default:
{
std::string strVal;
this->getConfigItem(key.c_str(), strVal);
return sol::make_object(luaState, strVal);
}
}
};
configTable[sol::metatable_key] = configMetatable;
s["config"] = configTable;
});
lua.push([&](sol::state& s) {
s["sensors"] = &sensors;
});
initialized = true;
triggerProcess = true; // first evaluation of the LUA scripts (collects their watch() / every())
return success;
}
int HomeCtl::initLocale()
{
// setenv("TZ", "CET", 1);
// Locale initialisieren (Liest die Umgebungsvariablen des Systems wie LANG oder LC_ALL)
const char* locale {setlocale(LC_ALL, "")};
if (!locale)
{
tell(eloDebug, "Debug: Detecting locale setting for LC_ALL failed");
return fail;
}
tell(eloInfo, "Current locale is %s", locale);
// Zeitzone des Systems einlesen - tzset() nach setlocale
tzset();
if ((strcasestr(locale, "UTF-8") != 0) || (strcasestr(locale, "UTF8") != 0))
tell(eloInfo, "Detected UTF-8");
time_t nun {time(nullptr)};
struct tm* tmTime {localtime(&nun)};
char strTime[64] {};
strftime(strTime, sizeof(strTime), "%c", tmTime);
tell(eloAlways, "Daylight (glob: %d, akt: %d); Timezone offset is (%ld) now it's %ld [%s]",
daylight, tmTime->tm_isdst, timezone, nun, strTime);
return done;
}
int HomeCtl::exit()
{
for (auto it = sensors["DO"].begin(); it != sensors["DO"].end(); ++it)
{
if (!sensors["DO"][it->first].impulse)
gpioWrite(it->first, false, false);
}
for (auto& sensor : sensors["GPIO"])
{
if (sensor.second.fct == "out" && !sensor.second.impulse)
gpioWrite(sensor.first, false, false);
}
lmcExit();
deconz.exit();
mqttDisconnect();
exitDb();
return success;
}
//***************************************************************************
// Init Sensor
//***************************************************************************
int HomeCtl::applyConfigurationSpecials()
{
std::map<int,PinInfo> pinList;
gpio->getPinList(pinList);
for (const auto& [phys, pinInfo] : pinList)
{
if (!pinInfo.usable) // is GPIO pin and not blocked by other process
continue;
initGpioLine(phys, pinInfo);
}
return done;
}
//***************************************************************************
// Init Sensor
//***************************************************************************
int HomeCtl::initSensorByFact(myString type, uint address)
{
cDbRow* fact {valueFactRowOf(type.c_str(), address)};
if (!fact)
{
tell(eloAlways, "Warning: valuefact for %s:0x%02x not found!", type.c_str(), address);
return fail;
}
sensors[type][address].type = type;
sensors[type][address].address = address;
sensors[type][address].record = fact->hasValue("RECORD", "A");
sensors[type][address].name = fact->getStrValue("NAME");
sensors[type][address].unit = fact->getStrValue("UNIT");
sensors[type][address].factor = fact->getIntValue("FACTOR");
sensors[type][address].group = fact->getIntValue("GROUPID");
sensors[type][address].active = fact->hasValue("STATE", "A");
sensors[type][address].choices = fact->getStrValue("CHOICES");
if (!fact->getValue("PARAMETER")->isEmpty())
sensors[type][address].parameter = fact->getStrValue("PARAMETER");
if (type == "GPIO" || type == "DO" || type == "DI" || type == "DZL" || type == "DZLG")
sensors[type][address].kind = "status";
if (sensors[type][address].unit == "txt")
sensors[type][address].kind = "text";
if (!fact->getValue("USRTITLE")->isEmpty())
sensors[type][address].title = fact->getStrValue("USRTITLE");
else if (!fact->getValue("TITLE")->isEmpty())
sensors[type][address].title = fact->getStrValue("TITLE");
else
sensors[type][address].title = fact->getStrValue("NAME");
if (type != "CV" && !fact->getValue("SETTINGS")->isEmpty())
{
json_t* jCal {jsonLoad(fact->getStrValue("SETTINGS"), 0, true)};
if (!jCal)
tell(eloAlways, "Ignoring invalid JSON in settings config of '%s:0x%x'", type.c_str(), address);
if (jCal)
{
if (type == "GPIO")
sensors[type][address].fct = getStringFromJson(jCal, "fct", "off");
if (type == "AI" || type.starts_with("ADS"))
{
aiSensorConfig[type][address].calPointA = getDoubleFromJson(jCal, "pointA");
aiSensorConfig[type][address].calPointB = getDoubleFromJson(jCal, "pointB");
aiSensorConfig[type][address].calPointValueA = getDoubleFromJson(jCal, "valueA");
aiSensorConfig[type][address].calPointValueB = getDoubleFromJson(jCal, "valueB");
aiSensorConfig[type][address].round = getDoubleFromJson(jCal, "round");
aiSensorConfig[type][address].cutBelow = getDoubleFromJson(jCal, "cutBelow", -10000.0);
}
else if (type == "DO" || type.starts_with("MCPO") || (type == "GPIO" && sensors[type][address].fct == "out"))
{
sensors[type][address].outputModes = getIntFromJson(jCal, "outputModes", 1);
sensors[type][address].invert = getBoolFromJson(jCal, "invert", true);
sensors[type][address].impulse = getBoolFromJson(jCal, "impulse");
sensors[type][address].feedbackInType = getStringFromJson(jCal, "feedbackInType", "");
sensors[type][address].feedbackInAddress = getIntFromJson(jCal, "feedbackInAddress");
sensors[type][address].script = getStringFromJson(jCal, "script", "");
cfgOutput(type, address, jCal);
}
else if (type == "DI" || type.starts_with("MCPI") || (type == "GPIO" && sensors[type][address].fct == "in"))
{
sensors[type][address].invert = getBoolFromJson(jCal, "invert", true);
sensors[type][address].pull = (Gpio::PullUpDown)getIntFromJson(jCal, "pull", 0);
cfgInput(type, address, jCal);
}
else if (type == "SC")
{
sensors[type][address].script = fact->getStrValue("SETTINGS");
}
json_decref(jCal);
}
}
tell(eloDebug, "Debug: Init sensor %s/0x%02x - '%s' %s", type.c_str(), address,
sensors[type][address].title.c_str(), sensors[type][address].active ? "active" : "not active");
return success;
}
//***************************************************************************
// Init GPIO Line
//***************************************************************************
int HomeCtl::initGpioLine(uint physPin, const PinInfo& pinInfo)
{
std::string name {std::to_string(physPin) + " - " + pinInfo.name + "\n" + pinInfo.description};
addValueFact(physPin, "GPIO", 1, name.c_str(), "", "", urControl);
if (sensors["GPIO"][physPin].active)
{
if (sensors["GPIO"][physPin].fct == "out")
{
gpio->pinMode(physPin, Gpio::dirOut);
cfgOutput("GPIO", physPin);
if (!sensors["GPIO"][physPin].impulse)
gpioWrite(physPin, false, false);
}
else if (sensors["GPIO"][physPin].fct == "in")
{
gpio->pinMode(physPin, Gpio::dirIn);
cfgInput("GPIO", physPin);
gpioRead(physPin);
}
}
return done;
}
//***************************************************************************
// Init digital Output
//***************************************************************************
int HomeCtl::initOutput(uint pin, int outputModes, OutputMode mode, const char* name, uint rights)
{
std::string n {std::string(name) + " " + std::to_string(pin) + "\n" + gpio->pinToName(pin)};
addValueFact(pin, "DO", 1, n.c_str(), "", "", rights);
// tell(eloDetail, "Info: initOutput 'DO:0x%x' to mode (%d)", pin, mode);
sensors["DO"][pin].outputModes = outputModes;
sensors["DO"][pin].mode = mode;
gpio->pinMode(pin, Gpio::dirOut);
cfgOutput("DO", pin);
if (!sensors["DO"][pin].impulse)
gpioWrite(pin, false, false);
return done;
}
int HomeCtl::cfgOutput(myString type, uint pin, json_t* jCal)
{
if (type.starts_with("MCPO"))
{
publishI2CSensorConfig(type.c_str(), pin, jCal);
}
else if (type == "DO" || type == "GPIO")
{
if (sensors[type][pin].impulse)
{
sensors[type][pin].markValid();
sensors[type][pin].state = sensors[type][pin].invert ? true : false;
}
}
return done;
}
//***************************************************************************
// Init digital Input
//***************************************************************************
int HomeCtl::initInput(uint pin, const char* name)
{
std::string n = std::string(name) + " " + std::to_string(pin) + "\n" + gpio->pinToName(pin);
addValueFact(pin, "DI", 1, n.c_str());
gpio->pinMode(pin, Gpio::dirIn);
cfgInput("DI", pin);
gpioRead(pin);
return done;
}
int HomeCtl::cfgInput(myString type, uint pin, json_t* jCal)
{
if (type.starts_with("MCPI"))
publishI2CSensorConfig(type.c_str(), pin, jCal);
else if (type == "DI" || (type == "GPIO" && sensors[type][pin].fct == "in"))
{
if (sensors[type][pin].pull != Gpio::pudOff)
gpio->pullUpDnControl(pin, sensors[type][pin].pull);
if (sensors[type][pin].active) //
{
tell(eloDebugGpio, "Debug: GPIO: ISR(%d) (%s)", pin, gpio->pinToName(pin).c_str());
if (!sensors[type][pin].interruptSet)
{
if (gpio->setIsr(pin, Gpio::edgeBoth, std::bind(&HomeCtl::onGpioChange, this, std::placeholders::_1, std::placeholders::_2)) != success)
tell(eloAlways, "Error: Unable to setup ISR to pin %d (%s)", pin, gpio->pinToName(pin).c_str());
else
sensors[type][pin].interruptSet = true;
}
}
}
return done;
}
//***************************************************************************
// Init Scripts
//***************************************************************************
int HomeCtl::initScripts()
{
// LogDuration ld("initScripts");
int count {0};
tableValueFacts->clear();
tableValueFacts->setValue("TYPE", "SC");
// cleanup valuefacts (delete all 'SC' sensors which not exist)
for (bool f = selectValueFactsByType->find(); f; f = selectValueFactsByType->fetch())
{
char* path {};
asprintf(&path, "%s/scripts.d/%s", confDir, tableValueFacts->getStrValue("NAME"));
if (!fileExists(path))
{
char* stmt {};
asprintf(&stmt, "%s = %ld and %s = 'SC'",
tableValueFacts->getField("ADDRESS")->getDbName(), tableValueFacts->getIntValue("ADDRESS"),
tableValueFacts->getField("TYPE")->getDbName());
tell(eloScript, "Script: Removing value fact for script '%s'", path);
tableValueFacts->deleteWhere("%s", stmt);
free(stmt);
}
free(path);
}
tableValueFacts->reset();
// check for new scripts
FileList scripts;
char* path {};
asprintf(&path, "%s/scripts.d", confDir);
int status = getFileList(path, DT_REG, "sh", false, &scripts, count);
if (status != success)
{