-
Notifications
You must be signed in to change notification settings - Fork 22
/
daemon.c
4344 lines (3346 loc) · 130 KB
/
daemon.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
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
//***************************************************************************
// 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 - 2023 Jörg Wendel
//***************************************************************************
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#include <algorithm>
#include <cmath>
#include <libgen.h>
#ifndef _NO_RASPBERRY_PI_
# include <wiringPi.h>
#else
# include "gpio.h"
#endif
#include "lib/curl.h"
#include "lib/json.h"
#include "lib/lua.h"
#include "daemon.h"
#include "growatt.h"
bool Daemon::shutdown {false};
//***************************************************************************
// Widgets
//***************************************************************************
const char* Daemon::widgetTypes[] =
{
"Symbol",
"Chart",
"Text",
"Value",
"Gauge",
"Meter",
"MeterLevel",
"PlainText",
"Choice",
"SymbolValue",
"Spacer",
"Time",
"SymbolText",
"BarChart",
0
};
const char* Daemon::toName(WidgetType type)
{
if (type > wtUnknown && type < wtCount)
return widgetTypes[type];
return widgetTypes[wtText];
}
Daemon::WidgetType Daemon::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
//***************************************************************************
Daemon::ValueTypes Daemon::defaultValueTypes[] =
{
// expression, title
{ "^VA", "Messwerte" },
{ "^SD", "Status Laufzeiten" },
{ "^DO", "Digitale Ausgänge" },
{ "^DI", "Digitale Eingänge" },
{ "^W1", "One Wire Sensoren" },
{ "^SC", "Skripte" },
{ "^AO", "Analog Ausgänge" },
{ "^AI", "Analog Eingänge" },
{ "^Sp", "Weitere Sensoren" },
{ "^DZL", "DECONZ Lampen" },
{ "^DZS", "DECONZ Sensoren" },
{ "^HM.*", "Home Matic" },
{ "^P4.*", "P4 Daemon" },
{ "^WEA", "Wetter" },
{ "^CV", "Calculated Values" },
{ "^PA", "Parameter" },
{ "^UD", "UD" },
{ "", "" }
};
const char* Daemon::getTitleOfType(const char* type)
{
for (int i = 0; defaultValueTypes[i].typeExpression != ""; i++)
{
if (rep(type, defaultValueTypes[i].typeExpression.c_str()) == success)
return defaultValueTypes[i].title.c_str();
}
return type;
}
//***************************************************************************
// Widgets - Default Properties
//***************************************************************************
Daemon::DefaultWidgetProperty Daemon::defaultWidgetProperties[] =
{
// 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 },
{ "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, "zst", wtSymbol, 0, 0, 0, false },
{ "SC", na, "*", wtMeter, 0, 40, 10, true },
{ "SP", na, "", wtText, 0, 0, 0, false },
{ "SP", na, "%", wtMeterLevel, 0, 100, 20, false },
{ "SP", na, "kWh", wtChart, 0, 50, 0, true },
{ "SP", na, "W", wtMeter, 0, 3000, 0, true },
{ "SP", na, "txt", wtPlainText, 0, 0, 0, true },
{ "SP", na, "*", wtMeter, 0, 100, 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 },
{ "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 },
{ "" }
};
Daemon::DefaultWidgetProperty* Daemon::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 Daemon::widgetDefaults2Json(json_t* jDefaults, const char* type, const char* unit, const char* name, int address)
{
std::string result;
DefaultWidgetProperty* defProperty = getDefalutProperty(type, unit, address);
const char* color {"rgb(255, 255, 255)"};
const char* colorOn {"rgb(235, 197, 5)"};
const char* symbol {""};
const char* symbolOn {""};
if (defProperty->unit == "mov")
{
symbol = "mdi:mdi-walk";
}
else if (strcmp(type, "HMB") == 0)
{
symbol = "mdi:mdi-blinds";
symbolOn = "mdi:mdi-blinds-open";
color = "rgb(0, 99, 162)";
colorOn = "rgb(255, 255, 255)";
}
else if (strcmp(type, "DZL") == 0)
{
symbol = "mdi:mdi-lightbulb-variant-outline";
symbolOn = "mdi:mdi-lightbulb-variant";
color = "rgb(255, 255, 255)";
colorOn = "rgb(235, 197, 5)";
}
json_object_set_new(jDefaults, "widgettype", json_integer(defProperty->widgetType));
json_object_set_new(jDefaults, "unit", json_string(unit));
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, "imgon", json_string(getImageFor(type, name, unit, true)));
json_object_set_new(jDefaults, "imgoff", json_string(getImageFor(type, name, unit, false)));
json_object_set_new(jDefaults, "symbol", json_string(symbol));
json_object_set_new(jDefaults, "symbolOn", json_string(symbolOn));
json_object_set_new(jDefaults, "color", json_string(color));
json_object_set_new(jDefaults, "colorOn", json_string(colorOn));
return done;
}
//***************************************************************************
// Get Image For
//***************************************************************************
const char* Daemon::getImageFor(const char* type, const char* title, const char* unit, int value)
{
const char* imagePath = "img/icon/unknown.png";
if (strcmp(type, "DZL") == 0 || strcasestr(title, "Licht") || strcasestr(title, "Light"))
imagePath = value ? "img/icon/light-on.png" : "img/icon/light-off.png";
else if (strcasestr(title, "Pump"))
imagePath = value ? "img/icon/pump-on.gif" : "img/icon/pump-off.png";
else if (strcasestr(title, "Steckdose") || strcasestr(title, "Plug") )
imagePath = value ? "img/icon/plug-on.png" : "img/icon/plug-off.png";
else if (strcasestr(title, "UV-C"))
imagePath = value ? "img/icon/uvc-on.png" : "img/icon/uvc-off.png";
else if (strcasestr(title, "Shower") || strcasestr(title, "Dusche"))
imagePath = value ? "img/icon/shower-on.png" : "img/icon/shower-off.png";
else if (strcasestr(title, "VDR"))
imagePath = value ? "img/icon/vdr-on.png" : "img/icon/vdr-off.png";
else if (strcasestr(title, "VPN"))
imagePath = value ? "img/icon/vpn-on.png" : "img/icon/vpn-off.png";
else if (strcasestr(title, "SATIP"))
imagePath = value ? "img/icon/satip-on.png" : "img/icon/satip-off.png";
else if (strcasestr(title, "Music") || strcasestr(title, "Musik"))
imagePath = value ? "img/icon/note-on.png" : "img/icon/note-off.png";
else if (strcasestr(title, "Fan") || strcasestr(title, "Lüfter"))
imagePath = value ? "img/icon/fan-on.png" : "img/icon/fan-off.png";
else if (strcasestr(title, "Desktop"))
imagePath = value ? "img/icon/desktop-on.png" : "img/icon/desktop-off.png";
else
imagePath = value ? "img/icon/boolean-on.png" : "img/icon/boolean-off.png";
return imagePath;
}
//***************************************************************************
// Object
//***************************************************************************
int isDST()
{
struct tm tm;
time_t t = time(0);
localtime_r(&t, &tm);
tm.tm_isdst = -1; // force DST auto detect
mktime(&tm);
return tm.tm_isdst;
}
Daemon::Daemon()
{
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);
webSock = new cWebSock(this, httpPath);
}
Daemon::~Daemon()
{
exit();
delete webSock;
free(mailScript);
free(stateMailTo);
free(errorMailTo);
cDbConnection::exit();
}
//***************************************************************************
// Push In Message (from WS to daemon)
//***************************************************************************
int Daemon::pushInMessage(const char* data)
{
cMyMutexLock lock(&messagesInMutex);
messagesIn.push(data);
return success;
}
//***************************************************************************
// Push Out Message (from daemon to WS)
//***************************************************************************
int Daemon::pushOutMessage(json_t* oContents, const char* event, long client)
{
json_t* obj = json_object();
addToJson(obj, "event", event);
json_object_set_new(obj, "object", oContents);
char* p = json_dumps(obj, JSON_REAL_PRECISION(4));
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 Daemon::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 Daemon::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/Read configuration from config table
for (const auto& it : *getConfiguration())
{
tableConfig->clear();
tableConfig->setValue("OWNER", myName());
tableConfig->setValue("NAME", it.name.c_str());
if (!tableConfig->find())
{
tableConfig->setValue("VALUE", it.def);
tableConfig->store();
}
}
readConfiguration(true);
// ---------------------------------
// setup GPIO
wiringPiSetupPhys(); // we use the 'physical' PIN numbers
// wiringPiSetup(); // to use the 'special' wiringPi PIN numbers
// wiringPiSetupGpio(); // to use the 'GPIO' PIN numbers
// ---------------------------------
// apply configuration specials
applyConfigurationSpecials();
// homeMaticInterface
if (homeMaticInterface)
{
mqttSensorTopics.push_back(TARGET "2mqtt/homematic/rpcresult");
mqttSensorTopics.push_back(TARGET "2mqtt/homematic/events");
if (mqttCheckConnection() == success && !isEmpty(mqttUrl))
{
const char* request = "{ \"method\" : \"listDevices\" }";
mqttWriter->write(TARGET "2mqtt/homematic/rpccall", request);
tell(eloHomeMatic, "-> (home-matic) '%s' to '%s'", TARGET "2mqtt/homematic/rpccall", request);
}
else
{
tell(eloAlways, "Error: Can't request home-matic data, MQTT connection failed");
}
}
// init web socket ...
while (webSock->init(webPort, webSocketPingTime, confDir, webSsl) != success)
{
tell(eloAlways, "Retrying in 2 seconds");
sleep(2);
}
initArduino();
performMqttRequests();
initScripts();
loadStates(); // load states of outputs on last exit
lmcInit();
if (!isEmpty(deconz.getHttpUrl()) && !isEmpty(deconz.getApiKey()))
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", "", "");
initialized = true;
return success;
}
int Daemon::initLocale()
{
setenv("TZ", "CET", 1);
tzset(); // init timezone environment
tell(eloAlways, "Daylight (%d); Timezone is (%ld) now it's %ld", isDST(), timezone, time(0));
// set a locale to "" means 'reset it to the environment'
// as defined by the ISO-C standard the locales after start are C
const char* locale {};
setlocale(LC_ALL, "");
locale = setlocale(LC_ALL, 0); // 0 for query the setting
if (!locale)
{
tell(eloAlways, "Info: Detecting locale setting for LC_ALL failed");
return fail;
}
tell(eloInfo, "Current locale is %s", locale);
if ((strcasestr(locale, "UTF-8") != 0) || (strcasestr(locale, "UTF8") != 0))
tell(eloInfo, "Detected UTF-8");
return done;
}
int Daemon::exit()
{
for (auto it = sensors["DO"].begin(); it != sensors["DO"].end(); ++it)
gpioWrite(it->first, false, false);
lmcExit();
deconz.exit();
mqttDisconnect();
exitDb();
return success;
}
//***************************************************************************
// Init Sensor
//***************************************************************************
int Daemon::initSensorByFact(std::string 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].invertDO = !fact->hasValue("INVERT", "N");
if (type == "DO" || type == "DI" || type == "DZL")
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 == "AI" && !fact->getValue("CALIBRATION")->isEmpty())
{
json_t* jCal = jsonLoad(fact->getStrValue("CALIBRATION"));
if (jCal)
{
aiSensors[address].calPointA = getDoubleFromJson(jCal, "pointA");
aiSensors[address].calPointB = getDoubleFromJson(jCal, "pointB");
aiSensors[address].calPointValueA = getDoubleFromJson(jCal, "valueA");
aiSensors[address].calPointValueB = getDoubleFromJson(jCal, "valueB");
aiSensors[address].round = getDoubleFromJson(jCal, "round");
aiSensors[address].calCutBelow = getDoubleFromJson(jCal, "calCutBelow", -10000.0);
json_decref(jCal);
}
}
tell(eloDebug, "Debug: Init sensor %s/0x%02x - '%s'", type.c_str(), address, sensors[type][address].title.c_str());
return success;
}
//***************************************************************************
// Init digital Output
//***************************************************************************
int Daemon::initOutput(uint pin, int opt, OutputMode mode, const char* name, uint rights)
{
addValueFact(pin, "DO", 1, name, "", "", rights);
sensors["DO"][pin].opt = opt;
sensors["DO"][pin].mode = mode;
pinMode(pin, OUTPUT);
gpioWrite(pin, false, false);
return done;
}
//***************************************************************************
// Init digital Input
//***************************************************************************
int Daemon::initInput(uint pin, const char* name)
{
pinMode(pin, INPUT);
if (!isEmpty(name))
{
addValueFact(pin, "DI", 1, name);
sensors["DI"][pin].state = gpioRead(pin);
}
return done;
}
//***************************************************************************
// Init Scripts
//***************************************************************************
int Daemon::initScripts()
{
char* path {};
int count {0};
// clear removed scripts ...
tableScripts->clear();
for (int f = selectScripts->find(); f; f = selectScripts->fetch())
{
if (!fileExists(tableScripts->getStrValue("PATH")))
{
char* stmt {};
asprintf(&stmt, "%s = '%s'", tableScripts->getField("PATH")->getDbName(), tableScripts->getStrValue("PATH"));
tableScripts->deleteWhere("%s", stmt);
free(stmt);
tell(eloAlways, "Removed script '%s'", tableScripts->getStrValue("PATH"));
}
}
tableValueFacts->clear();
tableValueFacts->setValue("TYPE", "SC");
for (int f = selectValueFactsByType->find(); f; f = selectValueFactsByType->fetch())
{
tableScripts->setValue("ID", tableValueFacts->getIntValue("ADDRESS"));
if (!tableScripts->find())
{
char* stmt {};
asprintf(&stmt, "%s = %ld and %s = 'SC'",
tableValueFacts->getField("ADDRESS")->getDbName(), tableValueFacts->getIntValue("ADDRESS"),
tableValueFacts->getField("TYPE")->getDbName());
tableValueFacts->deleteWhere("%s", stmt);
free(stmt);
tell(eloAlways, "Removed valuefact 'SC/%ld'", tableValueFacts->getIntValue("ADDRESS"));
}
}
tableValueFacts->reset();
// check for new scripts
FileList scripts;
asprintf(&path, "%s/scripts.d", confDir);
int status = getFileList(path, DT_REG, "sh", false, &scripts, count);
if (status != success)
{
free(path);
return status;
}
for (const auto& script : scripts)
{
char* scriptPath {};
uint addr {0};
char* cmd {};
std::string result;
asprintf(&scriptPath, "%s/%s", path, script.name.c_str());
// get address
tableScripts->clear();
tableScripts->setValue("PATH", scriptPath);
if (!selectScriptByPath->find())
{
tableScripts->store();
addr = tableScripts->getLastInsertId();
}
else
addr = tableScripts->getIntValue("ID");
selectScriptByPath->freeResult();
cDbRow* factRow = valueFactRowOf("SC", addr);
if (factRow && !factRow->hasValue("STATE", "A"))
{
tell(eloDebug, "Skipping deactivated script '%s'", scriptPath);
free(scriptPath);
continue;
}
// execute script
const char* url = strrchr(mqttUrl, '/');
if (url)
url++;
else
url = mqttUrl;
asprintf(&cmd, "%s %s %d 'mqtt://%s/%s'", scriptPath, "init", addr, url, TARGET "2mqtt/scripts");
tell(eloDetail, "Calling '%s'", cmd);
result = executeCommand(cmd);
free(cmd);
json_t* oData = jsonLoad(result.c_str());
if (!oData)
{
free(scriptPath);
continue;
}
std::string kind = getStringFromJson(oData, "kind", "status");
const char* title = getStringFromJson(oData, "title");
const char* unit = getStringFromJson(oData, "unit");
const char* choices = getStringFromJson(oData, "choices");
double value = getDoubleFromJson(oData, "value");
const char* text = getStringFromJson(oData, "text");
bool valid = getBoolFromJson(oData, "valid", true);
if (kind == "text")
unit = "";
else if (kind == "status")
unit = "zst";
auto tuple = split(script.name, '.');
addValueFact(addr, "SC", 1, !isEmpty(title) ? title : script.name.c_str(), unit, tuple[0].c_str(), urControl, choices);
tell(eloAlways, "Init script value of 'SC:%d' to %.2f", addr, value);
sensors["SC"][addr].kind = kind;
sensors["SC"][addr].last = time(0);
sensors["SC"][addr].valid = valid;
if (kind == "status")
sensors["SC"][addr].state = (bool)value;
else if (kind == "trigger")
sensors["SC"][addr].state = (bool)value;
else if (kind == "text")
sensors["SC"][addr].text = text;
else if (kind == "value")
sensors["SC"][addr].value = value;
tell(eloDetail, "Info: Found script '%s' addr (%d), unit '%s'; result was [%s]", scriptPath, addr, unit, result.c_str());
free(scriptPath);
json_decref(oData);
}
free(path);
return success;
}
//***************************************************************************
// Call Script
//***************************************************************************
int Daemon::callScript(int addr, const char* command)
{
if (commandThreads.find(addr) != commandThreads.end())
{
if (commandThreads[addr].active)
{
tell(eloAlways, "Info: Skipping call of script 'SC:0x%02x', already running", addr);
return done;
}
}
tableScripts->clear();
tableScripts->setValue("ID", addr);
if (!tableScripts->find())
{
tell(eloAlways, "Fatal: Script for 'SC:0x%02x' not found", addr);
return fail;
}
char* cmd {};
const char* url = strrchr(mqttUrl, '/');
if (url)
url++;
else
url = mqttUrl;
asprintf(&cmd, "%s %s %d 'mqtt://%s/%s'", tableScripts->getStrValue("PATH"), command, addr, url, TARGET "2mqtt/scripts");
tell(eloDetail, "Info: Calling '%s' ..", cmd);
int result = executeCommandAsync(addr, cmd);
tell(eloDetail, ".. done");
tableScripts->reset();
if (result == success && strstr("start|stop|toggle", command))
{
sensors["SC"][addr].working = true;
json_t* ojData = json_object();
sensor2Json(ojData, "SC", addr);
char* tuple {};
asprintf(&tuple, "%s:0x%02x", "SC", addr);
jsonSensorList[tuple] = ojData;
free(tuple);
pushDataUpdate("update", 0L);
}
return result;
}
//***************************************************************************
// Value Fact Of
//***************************************************************************
cDbRow* Daemon::valueFactRowOf(const char* type, uint addr)
{
tableValueFacts->clear();
tableValueFacts->setValue("ADDRESS", (long)addr);
tableValueFacts->setValue("TYPE", type);
if (!tableValueFacts->find())
return nullptr;
return tableValueFacts->getRow();
}
//***************************************************************************
// Get Sensor
//***************************************************************************
Daemon::SensorData* Daemon::getSensor(const char* type, int addr)
{
if (isEmpty(type))
return nullptr;
auto itType = sensors.find(type);
if (itType == sensors.end())
return nullptr;
auto itSensor = itType->second.find(addr);
if (itSensor == itType->second.end())
return nullptr;
return &itSensor->second;
}
//***************************************************************************
// Set Special Value
//***************************************************************************
void Daemon::setSpecialValue(uint addr, double value, const std::string& text)
{
sensors["SP"][addr].last = time(0);
sensors["SP"][addr].value = value;
sensors["SP"][addr].text = text;
sensors["SP"][addr].kind = text == "" ? "value" : "text";
sensors["SP"][addr].valid = sensors["SP"][addr].kind == "text" ? true : !isNan(value);
}
//***************************************************************************
// Init/Exit Database
//***************************************************************************
cDbFieldDef xmlTimeDef("XML_TIME", "xmltime", cDBS::ffAscii, 20, cDBS::ftData);
cDbFieldDef rangeFromDef("RANGE_FROM", "rfrom", cDBS::ffDateTime, 0, cDBS::ftData);
cDbFieldDef rangeToDef("RANGE_TO", "rto", cDBS::ffDateTime, 0, cDBS::ftData);
cDbFieldDef avgValueDef("AVG_VALUE", "avalue", cDBS::ffFloat, 122, cDBS::ftData);
cDbFieldDef maxValueDef("MAX_VALUE", "mvalue", cDBS::ffFloat, 122, cDBS::ftData);
cDbFieldDef rangeEndDef("time", "time", cDBS::ffDateTime, 0, cDBS::ftData);
int Daemon::initDb()
{
static int initial {yes};
int status {success};
if (connection)
exitDb();
tell(eloAlways, "Try conneting to database");
connection = new cDbConnection();
if (initial)
{
// ------------------------------------------
// initially create/alter tables and indices
// ------------------------------------------
tell(eloDb, "Checking database connection ...");
if (connection->attachConnection() != success)
{
tell(eloAlways, "Error: Initial database connect failed");
return fail;
}
tell(eloDb, "Checking table structure and indices ...");
for (auto t = dbDict.getFirstTableIterator(); t != dbDict.getTableEndIterator(); t++)
{
cDbTable* table = new cDbTable(connection, t->first.c_str());
if (strstr(table->TableName(), "information_schema"))
{
tell(eloAlways, "Skipping check of table '%s'", t->first.c_str());
delete table;
continue;
}
tell(eloDb, "Checking table '%s'", t->first.c_str());
if (!table->exist())
{
if ((status += table->createTable()) != success)
{
continue;
delete table;
}
}
else
{
status += table->validateStructure();
}
status += table->createIndices();
delete table;
}
connection->detachConnection();