-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRscpMain.cpp
3145 lines (2931 loc) · 152 KB
/
RscpMain.cpp
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
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdarg.h>
#include "RscpProtocol.h"
#include "RscpTags.h"
#include "RscpTagsOverview.h"
#include "RscpMapping.h"
#include "RscpConfig.h"
#include "SocketConnection.h"
#include "AES.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <signal.h>
#include <thread>
#include <regex>
#include <mutex>
#include <fcntl.h>
#define RSCP2P "1.3"
#define RSCP2P_LONG "1.3.3.31"
#define AES_KEY_SIZE 32
#define AES_BLOCK_SIZE 32
#define E3DC_FOUNDED 2010
#define CONFIG_FILE ".config"
#define DEFAULT_INTERVAL_MIN 1
#define DEFAULT_INTERVAL_MAX 300
#define IDLE_PERIOD_CACHE_SIZE 14
#define RECURSION_MAX_LEVEL 7
#define CHARGE_LOCK_TRUE "today:charge:true:00:00-23:59"
#define CHARGE_LOCK_FALSE "today:charge:false:00:00-23:59"
#define DISCHARGE_LOCK_TRUE "today:discharge:true:00:00-23:59"
#define DISCHARGE_LOCK_FALSE "today:discharge:false:00:00-23:59"
#define PV_SOLAR_MIN 200
#define MAX_DAYS_PER_ITERATION 12
#define DELAY_BEFORE_RECONNECT 10
static int iSocket = -1;
static int iAuthenticated = 0;
static AES aesEncrypter;
static AES aesDecrypter;
static uint8_t ucEncryptionIV[AES_BLOCK_SIZE];
static uint8_t ucDecryptionIV[AES_BLOCK_SIZE];
static time_t e3dc_ts = 0;
static time_t e3dc_diff = 0;
static int gmt_diff = 0;
static config_t cfg;
static wb_t wb_stat;
static int day, leap_day, year, curr_day, curr_year, battery_nr, pm_nr, wb_nr;
static uint8_t period_change_nr = 0;
static bool period_trigger = false;
static bool day_end = false;
static bool new_day = false;
std::mutex mtx;
static bool mqttRcvd = false;
static bool go = true;
static bool tags_added = false;
static int fd = -1;
char *wfifo = (char *)"/tmp/rscp2p.fifo.data";
char *rfifo = (char *)"/tmp/rscp2p.fifo.cmd";
void logMessage(char *file, char *srcfile, int line, char *format, ...);
void logMessageCache(char *file, bool clear);
void signal_handler(int sig) {
if (sig == SIGINT) {
logMessage(cfg.logfile, (char *)__FILE__, __LINE__, (char *)"Program exits by signal SIGINT\n");
go = false;
} else if (sig == SIGTERM) {
logMessage(cfg.logfile, (char *)__FILE__, __LINE__, (char *)"Program exits by signal SIGTERM\n");
go = false;
} else if (sig == SIGPIPE) {
logMessage(cfg.logfile, (char *)__FILE__, __LINE__, (char *)"Program gets signal SIGPIPE\n");
fd = -1;
}
}
void wsleep(double seconds) {
while (seconds > 0.0) {
mtx.lock();
if (mqttRcvd || !go) {
mtx.unlock();
return;
}
mtx.unlock();
if (seconds >= 1.0) {
sleep(1);
} else {
useconds_t usec = (useconds_t)(seconds * 1e6);
if (usec > 0) usleep(usec);
}
seconds = seconds - 1.0;
}
return;
}
bool hasSpaces(char *s) {
for (size_t i = 0; i < strlen(s); i++) {
if (isspace(s[i])) return(true);
}
return(false);
}
char *tagName(std::vector<RSCP_TAGS::tag_overview_t> & v, uint32_t tag) {
for (std::vector<RSCP_TAGS::tag_overview_t>::iterator it = v.begin(); it != v.end(); ++it) {
if (it->tag == tag) {
return(it->name);
}
}
return(NULL);
}
uint32_t tagID(std::vector<RSCP_TAGS::tag_overview_t> & v, char *name) {
for (std::vector<RSCP_TAGS::tag_overview_t>::iterator it = v.begin(); it != v.end(); ++it) {
if (!strcmp(it->name, name)) {
return(it->tag);
}
}
return(0);
}
bool isTag(std::vector<RSCP_TAGS::tag_overview_t> & v, char *name, bool must_be_request_tag) {
for (std::vector<RSCP_TAGS::tag_overview_t>::iterator it = v.begin(); it != v.end(); ++it) {
if (!strcmp(it->name, name) && (!must_be_request_tag || (must_be_request_tag && it->request))) {
return(true);
}
}
return(false);
}
char *typeName(std::vector<RSCP_TAGS::rscp_types_t> & v, uint8_t code) {
for (std::vector<RSCP_TAGS::rscp_types_t>::iterator it = v.begin(); it != v.end(); ++it) {
if (it->code == code) {
return(it->type);
}
}
return(NULL);
}
uint8_t typeID(std::vector<RSCP_TAGS::rscp_types_t> & v, char *type) {
for (std::vector<RSCP_TAGS::rscp_types_t>::iterator it = v.begin(); it != v.end(); ++it) {
if (!strcmp(it->type, type)) {
return(it->code);
}
}
return(0);
}
char *errName(std::vector<RSCP_TAGS::rscp_err_codes_t> & v, uint32_t code) {
char *unknown = NULL;
for (std::vector<RSCP_TAGS::rscp_err_codes_t>::iterator it = v.begin(); it != v.end(); ++it) {
if (!it->code) unknown = it->error;
if (it->code == code) {
return(it->error);
}
}
return(unknown);
}
int storeMQTTReceivedValue(std::vector<RSCP_MQTT::rec_cache_t> & c, char *topic_in, char *payload) {
char topic[TOPIC_SIZE];
mtx.lock();
mqttRcvd = true;
for (std::vector<RSCP_MQTT::rec_cache_t>::iterator it = c.begin(); it != c.end(); ++it) {
if (cfg.prefix) snprintf(topic, TOPIC_SIZE, "%s_%s", cfg.prefix, it->topic);
else strcpy(topic, it->topic);
if (!strcmp(topic, topic_in) && it->done) {
if (std::regex_match(payload, std::regex(it->regex_true))) {
if (strcmp(it->value_true, "")) strncpy(it->payload, it->value_true, PAYLOAD_SIZE);
else strncpy(it->payload, payload, PAYLOAD_SIZE);
if (it->queue) {
if (!strcmp(it->topic, "request_day")) {
int year, month, day;
if (sscanf(it->payload, "%d-%d-%d", &year, &month, &day)) {
RSCP_MQTT::requestQ.push({day, month, year});
}
}
} else it->done = false;
break;
} else if (std::regex_match(payload, std::regex(it->regex_false))) {
if (strcmp(it->value_false, "")) strncpy(it->payload, it->value_false, PAYLOAD_SIZE);
else strncpy(it->payload, payload, PAYLOAD_SIZE);
it->done = false;
break;
} else {
it->done = true;
break;
}
}
}
mtx.unlock();
return(0);
}
void fifoListener() {
char fifo[1024];
char key[128];
char value[128];
int fd = -1;
logMessage(cfg.logfile, (char *)__FILE__, __LINE__, (char *)"fifoListener: starting listener loop\n");
while (go) {
memset(fifo, 0, sizeof(fifo));
if (fd < 0) fd = open(rfifo, O_RDONLY);
read(fd, fifo, 1024);
if (strlen(fifo)) {
if (sscanf(fifo, "%127[^=]=%127[^\n]", key, value) == 2) {
if (!cfg.prefix || (strstr(key, cfg.prefix))) {
storeMQTTReceivedValue(RSCP_MQTT::RscpMqttReceiveCache, key, value);
if (cfg.verbose) logMessage(cfg.logfile, (char *)__FILE__, __LINE__, (char *)"fifoListener: >%s< >%s< received\n", key, value);
}
}
}
}
close(fd);
fd = -1;
logMessage(cfg.logfile, (char *)__FILE__, __LINE__, (char *)"fifoListener: stopped\n");
return;
}
// topic: <prefix>/set/power_mode payload: auto / idle:60 (cycles) / discharge:2000:60 (Watt:cycles) / charge:2000:60 (Watt:cycles) / grid_charge:2000:60 (Watt:cycles)
int handleSetPower(std::vector<RSCP_MQTT::rec_cache_t> & c, uint32_t container, char *payload) {
char cycles[12];
char cmd[12];
char power[12];
char modus[2];
time_t now;
time(&now);
if (!strcmp(payload, "auto")) {
strcpy(cycles, "0");
strcpy(modus, "0");
strcpy(power, "0");
} else if ((sscanf(payload, "%12[^:]:%12[^:]", cmd, cycles) == 2) && (!strcmp(cmd, "idle"))) {
strcpy(modus, "1");
strcpy(power, "0");
} else if (sscanf(payload, "%12[^:]:%12[^:]:%12[^:]", cmd, power, cycles) == 3) {
if (!strcmp(cmd, "discharge")) strcpy(modus, "2");
else if (!strcmp(cmd, "charge")) strcpy(modus, "3");
else strcpy(modus, "4");
} else return(0);
for (std::vector<RSCP_MQTT::rec_cache_t>::iterator it = c.begin(); it != c.end(); ++it) {
if (it->container == container) {
switch (it->tag) {
case TAG_EMS_REQ_SET_POWER_MODE: {
strcpy(it->payload, modus);
it->refresh_until = abs(atoi(cycles)) * cfg.interval + now;
break;
}
case TAG_EMS_REQ_SET_POWER_VALUE: {
strcpy(it->payload, power);
it->refresh_until = abs(atoi(cycles)) * cfg.interval + now;
break;
}
}
}
}
return(0);
}
int handleSetIdlePeriod(RscpProtocol *protocol, SRscpValue *rootContainer, char *payload) {
int day, starthour, startminute, endhour, endminute;
char daystring[12];
char typestring[12];
char activestring[12];
memset(daystring, 0, sizeof(daystring));
memset(typestring, 0, sizeof(typestring));
memset(activestring, 0, sizeof(activestring));
if (sscanf(payload, "%12[^:]:%12[^:]:%12[^:]:%d:%d-%d:%d", daystring, typestring, activestring, &starthour, &startminute, &endhour, &endminute) != 7) {
logMessage(cfg.logfile, (char *)__FILE__, __LINE__, (char *)"handleSetIdlePeriod: payload=>%s< not enough attributes.\n", payload);
return(1);
}
for (day = 0; day < 8; day++) {
if (!strcmp(RSCP_MQTT::days[day].c_str(), daystring)) break;
}
if (day == 7) { // today
time_t rawtime;
time(&rawtime);
struct tm *l = localtime(&rawtime);
day = l->tm_wday?(l->tm_wday-1):6;
}
if (starthour*60+startminute >= endhour*60+endminute) {
logMessage(cfg.logfile, (char *)__FILE__, __LINE__, (char *)"handleSetIdlePeriod: payload=>%s< time range %02d:%02d-%02d:%02d not allowed.\n", payload, starthour, startminute, endhour, endminute);
return(1);
}
SRscpValue setTimeContainer;
protocol->createContainerValue(&setTimeContainer, TAG_EMS_REQ_SET_IDLE_PERIODS);
SRscpValue setDayContainer;
protocol->createContainerValue(&setDayContainer, TAG_EMS_IDLE_PERIOD);
protocol->appendValue(&setDayContainer, TAG_EMS_IDLE_PERIOD_TYPE, (uint8_t)strcmp(typestring, "discharge")?0:1); // 0 = charge 1 = discharge
protocol->appendValue(&setDayContainer, TAG_EMS_IDLE_PERIOD_DAY, (uint8_t)day); // 0 = Monday -> 6 = Sunday
protocol->appendValue(&setDayContainer, TAG_EMS_IDLE_PERIOD_ACTIVE, strcmp(activestring, "true")?false:true);
SRscpValue setStartContainer;
protocol->createContainerValue(&setStartContainer, TAG_EMS_IDLE_PERIOD_START);
protocol->appendValue(&setStartContainer, TAG_EMS_IDLE_PERIOD_HOUR, (uint8_t)starthour);
protocol->appendValue(&setStartContainer, TAG_EMS_IDLE_PERIOD_MINUTE, (uint8_t)startminute);
protocol->appendValue(&setDayContainer, setStartContainer);
protocol->destroyValueData(setStartContainer);
SRscpValue setStopContainer;
protocol->createContainerValue(&setStopContainer, TAG_EMS_IDLE_PERIOD_END);
protocol->appendValue(&setStopContainer, TAG_EMS_IDLE_PERIOD_HOUR, (uint8_t)endhour);
protocol->appendValue(&setStopContainer, TAG_EMS_IDLE_PERIOD_MINUTE, (uint8_t)endminute);
protocol->appendValue(&setDayContainer, setStopContainer);
protocol->destroyValueData(setStopContainer);
protocol->appendValue(&setTimeContainer, setDayContainer);
protocol->destroyValueData(setDayContainer);
protocol->appendValue(rootContainer, setTimeContainer);
protocol->destroyValueData(setTimeContainer);
return(0);
}
void setTopicAttr() {
for (std::vector<RSCP_MQTT::topic_store_t>::iterator i = RSCP_MQTT::TopicStore.begin(); i != RSCP_MQTT::TopicStore.end(); ++i) {
switch (i->type) {
case FORCED_TOPIC: {
for (std::vector<RSCP_MQTT::cache_t>::iterator it = RSCP_MQTT::RscpMqttCache.begin(); it != RSCP_MQTT::RscpMqttCache.end(); ++it) {
if (std::regex_match(it->topic, std::regex(i->topic))) it->forced = true;
}
break;
}
case LOG_TOPIC: {
for (std::vector<RSCP_MQTT::cache_t>::iterator it = RSCP_MQTT::RscpMqttCache.begin(); it != RSCP_MQTT::RscpMqttCache.end(); ++it) {
if (std::regex_match(it->topic, std::regex(i->topic))) it->history_log = true;
}
break;
}
}
}
return;
}
void addTemplTopicsIdx(int index, char *seg, int start, int n, int inc, bool finalize) {
for (int c = start; c < n; c++) {
for (std::vector<RSCP_MQTT::cache_t>::iterator it = RSCP_MQTT::RscpMqttCacheTempl.begin(); it != RSCP_MQTT::RscpMqttCacheTempl.end(); ++it) {
if (it->index == index) {
RSCP_MQTT::cache_t cache = { it->container, it->tag, index + c, "", "", it->format, "", it->divisor, it->bit_to_bool, it->history_log, it->changed, it->influx, it->forced };
if (n == 1) {
snprintf(cache.topic, TOPIC_SIZE, it->topic, seg);
} else if (seg == NULL) {
snprintf(cache.topic, TOPIC_SIZE, it->topic, c + inc);
} else {
char buffer[TOPIC_SIZE];
snprintf(buffer, TOPIC_SIZE, "%s/%d", seg, c + inc);
snprintf(cache.topic, TOPIC_SIZE, it->topic, buffer);
}
strcpy(cache.unit, it->unit);
RSCP_MQTT::RscpMqttCache.push_back(cache);
}
}
}
if (finalize) {
sort(RSCP_MQTT::RscpMqttCache.begin(), RSCP_MQTT::RscpMqttCache.end(), RSCP_MQTT::compareCache);
setTopicAttr();
}
return;
}
void addTemplTopics(uint32_t container, int index, char *seg, int start, int n, int inc, bool finalize) {
for (int c = start; c < n; c++) {
for (std::vector<RSCP_MQTT::cache_t>::iterator it = RSCP_MQTT::RscpMqttCacheTempl.begin(); it != RSCP_MQTT::RscpMqttCacheTempl.end(); ++it) {
if (it->container == container) {
RSCP_MQTT::cache_t cache = { it->container, it->tag, c, "", "", it->format, "", it->divisor, it->bit_to_bool, it->history_log, it->changed, it->influx, it->forced };
if (it->index > 1) cache.index = it->index + c * 10;
if ((seg == NULL) && (index == 0)) { // no args
cache.index = it->index;
strcpy(cache.topic, it->topic);
} else if ((seg == NULL) && (index == 1)) { // "%d"
snprintf(cache.topic, TOPIC_SIZE, it->topic, c + inc);
} else if ((seg != NULL) && (index == 0)) { // "%s"
snprintf(cache.topic, TOPIC_SIZE, it->topic, seg);
} else { // "%s" with "%s/%d"
char buffer[TOPIC_SIZE];
snprintf(buffer, TOPIC_SIZE, "%s/%d", seg, c + inc);
snprintf(cache.topic, TOPIC_SIZE, it->topic, buffer);
}
strcpy(cache.unit, it->unit);
RSCP_MQTT::RscpMqttCache.push_back(cache);
}
}
}
if (finalize) {
sort(RSCP_MQTT::RscpMqttCache.begin(), RSCP_MQTT::RscpMqttCache.end(), RSCP_MQTT::compareCache);
setTopicAttr();
}
return;
}
void addTopic(uint32_t container, uint32_t tag, char *topic, char *unit, int format, int divisor, int bit_to_bool, bool finalize) {
RSCP_MQTT::cache_t cache = { container, tag, 0, "", "", format, "", divisor, bit_to_bool, false, false, false, false };
strcpy(cache.topic, topic);
strcpy(cache.unit, unit);
RSCP_MQTT::RscpMqttCache.push_back(cache);
if (finalize) {
sort(RSCP_MQTT::RscpMqttCache.begin(), RSCP_MQTT::RscpMqttCache.end(), RSCP_MQTT::compareCache);
setTopicAttr();
}
return;
}
void addSetTopic(uint32_t container, uint32_t tag, int index, char *topic, char *regex_true, char *value_true, char *regex_false, char *value_false, int type, bool finalize) {
RSCP_MQTT::rec_cache_t cache = { container, tag, index, "", "", "1", "", "0", "", UNIT_NONE, type, -1, false, true };
strcpy(cache.topic, topic);
strcpy(cache.regex_true, regex_true);
strcpy(cache.value_true, value_true);
strcpy(cache.regex_false, regex_false);
strcpy(cache.value_false, value_false);
RSCP_MQTT::RscpMqttReceiveCache.push_back(cache);
if (finalize) sort(RSCP_MQTT::RscpMqttReceiveCache.begin(), RSCP_MQTT::RscpMqttReceiveCache.end(), RSCP_MQTT::compareRecCache);
return;
}
void writeFifo(char *fifo, bool single) {
int i, g = 0;
if (fd < 0) fd = open(wfifo, O_WRONLY);
do {
i = write(fd, fifo+g, strlen(fifo)-g);
g+= i;
} while (g < strlen(fifo));
if (single) {
close(fd);
fd = -1;
}
}
void publishImmediately(char *t, char *p) {
char fifo[1024];
sprintf(fifo, "$=%s=%s=%s=$\n", t, p, "");
writeFifo(fifo, false);
return;
}
int handleMQTT(std::vector<RSCP_MQTT::cache_t> & v) {
char fifo[1024];
int rc = 0;
for (std::vector<RSCP_MQTT::cache_t>::iterator it = v.begin(); it != v.end(); ++it) {
if ((it->changed || it->forced) && strcmp(it->topic, "") && strcmp(it->payload, "")) {
if (it->history_log) logMessage(cfg.historyfile, (char *)__FILE__, __LINE__, (char *)"topic >%s< payload >%s< unit >%s<\n", it->topic, it->payload, it->unit);
sprintf(fifo, "$=%s=%s=%s=$\n", it->topic, it->payload, it->unit);
writeFifo(fifo, false);
it->changed = false;
}
}
return(rc);
}
int handleMQTTIdlePeriods(std::vector<RSCP_MQTT::idle_period_t> & v) {
int rc = 0;
char fifo[1024];
char topic[TOPIC_SIZE];
char payload[PAYLOAD_SIZE];
RSCP_MQTT::idle_period_t e;
while (!v.empty()) {
e = v.back();
if (cfg.prefix) {
snprintf(topic, TOPIC_SIZE, "%s/idle_period/%s/%s", cfg.prefix, RSCP_MQTT::days[e.day].c_str(), e.type?"discharge":"charge");
} else {
snprintf(topic, TOPIC_SIZE, "idle_period/%s/%s", RSCP_MQTT::days[e.day].c_str(), e.type?"discharge":"charge");
}
snprintf(payload, PAYLOAD_SIZE, "%s:%02d:%02d-%02d:%02d", e.active?"true":"false", e.starthour, e.startminute, e.endhour, e.endminute);
sprintf(fifo, "$=%s=%s=%s=$\n", topic, payload, "");
writeFifo(fifo, false);
v.pop_back();
}
return(rc);
}
int handleMQTTErrorMessages(std::vector<RSCP_MQTT::error_t> & v) {
int rc = 0;
int i = 0;
char fifo[1024];
char topic[TOPIC_SIZE];
char payload[PAYLOAD_SIZE];
RSCP_MQTT::error_t e;
while (!v.empty()) {
e = v.back();
if (cfg.prefix) {
snprintf(topic, TOPIC_SIZE, "%s/error_message/%d/meta", cfg.prefix, ++i);
} else {
snprintf(topic, TOPIC_SIZE, "error_message/%d/meta", ++i);
}
snprintf(payload, PAYLOAD_SIZE, "type %d code %d source %s", e.type, e.code, e.source);
sprintf(fifo, "$=%s=%s=%s=$\n", topic, payload, "");
writeFifo(fifo, false);
if (cfg.prefix) {
snprintf(topic, TOPIC_SIZE, "%s/error_message/%d", cfg.prefix, i);
} else {
snprintf(topic, TOPIC_SIZE, "error_message/%d", i);
}
sprintf(fifo, "$=%s=%s=%s=$\n", topic, e.message, "");
writeFifo(fifo, false);
v.pop_back();
}
return(rc);
}
void logCache(std::vector<RSCP_MQTT::cache_t> & v, char *file) {
if (file) {
FILE *fp;
fp = fopen(file, "a");
if (!fp) return;
for (std::vector<RSCP_MQTT::cache_t>::iterator it = v.begin(); it != v.end(); ++it) {
fprintf(fp, "container >%s< tag >%s< index >%d< topic >%s< payload >%s< unit >%s<%s\n", tagName(RSCP_TAGS::RscpTagsOverview, it->container), tagName(RSCP_TAGS::RscpTagsOverview, it->tag), it->index, it->topic, it->payload, it->unit, (it->forced?" forced":""));
}
fflush(fp);
fclose(fp);
} else {
for (std::vector<RSCP_MQTT::cache_t>::iterator it = v.begin(); it != v.end(); ++it) {
printf("container >%s< tag >%s< index >%d< topic >%s< payload >%s< unit >%s<%s\n", tagName(RSCP_TAGS::RscpTagsOverview, it->container), tagName(RSCP_TAGS::RscpTagsOverview, it->tag), it->index, it->topic, it->payload, it->unit, (it->forced?" forced":""));
}
fflush(NULL);
}
return;
}
void logRecCache(std::vector<RSCP_MQTT::rec_cache_t> & v, char *file) {
if (file) {
FILE *fp;
fp = fopen(file, "a");
if (!fp) return;
for (std::vector<RSCP_MQTT::rec_cache_t>::iterator it = v.begin(); it != v.end(); ++it) {
fprintf(fp, "container >%s< tag >%s< index >%d< topic >%s< regex_true >%s< value_true >%s< regex_false >%s< value_false >%s< unit >%s< type >%s<\n", tagName(RSCP_TAGS::RscpTagsOverview, it->container), tagName(RSCP_TAGS::RscpTagsOverview, it->tag), it->index, it->topic, it->regex_true, it->value_true, it->regex_false, it->value_false, it->unit, typeName(RSCP_TAGS::RscpTypeNames, it->type));
}
fflush(fp);
fclose(fp);
} else {
for (std::vector<RSCP_MQTT::rec_cache_t>::iterator it = v.begin(); it != v.end(); ++it) {
printf("container >%s< tag >%s< index >%d< topic >%s< regex_true >%s< value_true >%s< regex_false >%s< value_false >%s< unit >%s< type >%s<\n", tagName(RSCP_TAGS::RscpTagsOverview, it->container), tagName(RSCP_TAGS::RscpTagsOverview, it->tag), it->index, it->topic, it->regex_true, it->value_true, it->regex_false, it->value_false, it->unit, typeName(RSCP_TAGS::RscpTypeNames, it->type));
}
fflush(NULL);
}
return;
}
void logTopics(std::vector<RSCP_MQTT::cache_t> & v, char *file, bool check_payload) {
int total = 0;
int forced = 0;
int influx = 0;
int history_log = 0;
for (std::vector<RSCP_MQTT::cache_t>::iterator it = v.begin(); it != v.end(); ++it) {
if (it->forced) { logMessage(file, (char *)__FILE__, __LINE__, (char *)"Topic >%s< forced\n", it->topic); forced++; }
if (it->history_log) { logMessage(file, (char *)__FILE__, __LINE__, (char *)"Topic >%s< marked for logging\n", it->topic); history_log++; }
if (check_payload && (!strcmp(it->payload, ""))) logMessage(file, (char *)__FILE__, __LINE__, (char *)"Topic >%s< unused? Payload is empty\n", it->topic);
total++;
}
logMessage(file, (char *)__FILE__, __LINE__, (char *)"Number of topics >%d<\n", total);
logMessage(file, (char *)__FILE__, __LINE__, (char *)"Number of topics with flag \"forced\" >%d<\n", forced);
logMessage(file, (char *)__FILE__, __LINE__, (char *)"Number of topics with flag \"history_log\" >%d<\n", history_log);
return;
}
bool checkTopicOrder(std::vector<RSCP_MQTT::cache_t> & v) {
uint32_t container = 0;
uint32_t tag = 0;
int index = 0;
bool sorted = true;
for (std::vector<RSCP_MQTT::cache_t>::iterator it = v.begin(); it != v.end(); ++it) {
if ((it->container < container) && (it->tag < tag) && (it->index < index)) {
sorted = false;
break;
}
container = it->container;
tag = it->tag;
index = it->index;
}
return(sorted);
}
bool checkTopicUniqueness(std::vector<RSCP_MQTT::cache_t> & v) {
int j;
for (std::vector<RSCP_MQTT::cache_t>::iterator i = v.begin(); i != v.end(); ++i) {
j = 0;
for (std::vector<RSCP_MQTT::cache_t>::iterator it = v.begin(); it != v.end(); ++it) {
if ((i->container == it->container) && (i->tag == it->tag) && (i->index == it->index) && (i->bit_to_bool == it->bit_to_bool)) j++;
}
if (j > 1) return(false);
}
return(true);
}
void logHealth(char *file) {
logMessage(file, (char *)__FILE__, __LINE__, (char *)"[%s] PVI %s | PM %s | DCB %s (%d) | Wallbox %s | Autorefresh %s | Raw data %s | Interval %d\n", RSCP2P, cfg.pvi_requests?"✓":"✗", cfg.pm_requests?"✓":"✗", cfg.dcb_requests?"✓":"✗", cfg.battery_strings, cfg.wallbox?"✓":"✗", cfg.auto_refresh?"✓":"✗", cfg.raw_mode?"✓":"✗", cfg.interval);
for (uint8_t i = 0; i < cfg.pm_number; i++) {
logMessage(file, (char *)__FILE__, __LINE__, (char *)"PM_INDEX >%d<\n", cfg.pm_indexes[i]);
}
for (uint8_t i = 0; i < cfg.wb_number; i++) {
logMessage(file, (char *)__FILE__, __LINE__, (char *)"WB_INDEX >%d<\n", cfg.wb_indexes[i]);
}
logTopics(RSCP_MQTT::RscpMqttCache, file, true);
for (std::vector<RSCP_MQTT::additional_tags_t>::iterator it = RSCP_MQTT::AdditionalTags.begin(); it != RSCP_MQTT::AdditionalTags.end(); ++it) {
logMessage(file, (char *)__FILE__, __LINE__, (char *)"Container >%s< Tag >%s< added (one shot: %s).\n", tagName(RSCP_TAGS::RscpTagsOverview, it->req_container), tagName(RSCP_TAGS::RscpTagsOverview, it->req_tag), it->one_shot?"true":"false");
}
logMessage(file, (char *)__FILE__, __LINE__, (char *)"Topics sorted >%s<\n", checkTopicOrder(RSCP_MQTT::RscpMqttCache)?"true":"false");
logMessage(file, (char *)__FILE__, __LINE__, (char *)"Topics unique >%s<\n", checkTopicUniqueness(RSCP_MQTT::RscpMqttCache)?"true":"false");
for (std::vector<RSCP_MQTT::not_supported_tags_t>::iterator it = RSCP_MQTT::NotSupportedTags.begin(); it != RSCP_MQTT::NotSupportedTags.end(); ++it) {
logMessage(file, (char *)__FILE__, __LINE__, (char *)"Container >%s< Tag >%s< not supported.\n", tagName(RSCP_TAGS::RscpTagsOverview, it->container), tagName(RSCP_TAGS::RscpTagsOverview, it->tag));
}
for (std::vector<RSCP_MQTT::cache_t>::iterator it = RSCP_MQTT::RscpMqttCacheTempl.begin(); it != RSCP_MQTT::RscpMqttCacheTempl.end(); ++it) {
logMessage(file, (char *)__FILE__, __LINE__, (char *)"Container >%s< Tag >%s< in temporary cache.\n", tagName(RSCP_TAGS::RscpTagsOverview, it->container), tagName(RSCP_TAGS::RscpTagsOverview, it->tag));
}
logMessageCache(file, false);
return;
}
void logMessage(char *file, char *srcfile, int line, char *format, ...) {
FILE * fp;
if (file) {
fp = fopen(file, "a");
if (!fp) return;
}
pid_t pid, ppid;
va_list args;
char timestamp[64];
time_t rawtime;
time(&rawtime);
struct tm *l = localtime(&rawtime);
strftime(timestamp, 26, "%Y-%m-%d %H:%M:%S", l);
pid = getpid();
ppid = getppid();
va_start(args, format);
if (file) {
fprintf(fp, "[%s] pid=%d ppid=%d %s(%d) ", timestamp, pid, ppid, srcfile, line);
vfprintf(fp, format, args);
fflush(fp);
fclose(fp);
} else {
printf("[%s] pid=%d ppid=%d %s(%d) ", timestamp, pid, ppid, srcfile, line);
vprintf(format, args);
fflush(NULL);
}
va_end(args);
return;
}
void copyCache(std::vector<RSCP_MQTT::cache_t> & to, std::vector<RSCP_MQTT::cache_t> & from, uint32_t container) {
for (std::vector<RSCP_MQTT::cache_t>::iterator it = from.begin(); it != from.end(); ++it) {
if (it->container == container) {
RSCP_MQTT::cache_t cache = { it->container, it->tag, it->index, "", "", it->format, "", it->divisor, it->bit_to_bool, it->history_log, it->changed, it->influx, it->forced };
strcpy(cache.topic, it->topic);
strcpy(cache.payload, it->payload);
strcpy(cache.unit, it->unit);
to.push_back(cache);
}
}
return;
}
void cleanupCache(std::vector<RSCP_MQTT::cache_t> & v) {
std::vector<RSCP_MQTT::cache_t> TempCache({});
copyCache(TempCache, v, TAG_DB_HISTORY_DATA_YEAR);
copyCache(TempCache, v, TAG_DB_HISTORY_DATA_DAY);
RSCP_MQTT::RscpMqttCacheTempl.clear();
copyCache(v, TempCache, TAG_DB_HISTORY_DATA_DAY);
copyCache(v, TempCache, TAG_DB_HISTORY_DATA_YEAR);
return;
}
bool updMessageByTag(uint32_t container, uint32_t tag, int error, int type) {
for (std::vector<RSCP_MQTT::message_cache_t>::iterator it = RSCP_MQTT::MessageCache.begin(); it != RSCP_MQTT::MessageCache.end(); ++it) {
if ((it->container == container) && (it->tag == tag) && (it->type == type) && (it->error == error)) {
it->count += 1;
return(true);
}
}
return(false);
}
void logMessageByTag(uint32_t container, uint32_t tag, int error, int type, char *message) {
if (!cfg.log_level) return;
if (updMessageByTag(container, tag, error, type)) return;
RSCP_MQTT::message_cache_t v;
v.container = container;
v.tag = tag;
v.type = type;
v.error = error;
v.count = 1;
strcpy(v.message, message);
RSCP_MQTT::MessageCache.push_back(v);
if (cfg.log_level == 1) logMessageCache(cfg.logfile, true);
return;
}
void logMessageCache(char *file, bool clear) {
for (std::vector<RSCP_MQTT::message_cache_t>::iterator it = RSCP_MQTT::MessageCache.begin(); it != RSCP_MQTT::MessageCache.end(); ++it) {
if (it->count) {
if (it->container && it->tag && it->error) logMessage(file, (char *)__FILE__, it->type, it->message, tagName(RSCP_TAGS::RscpTagsOverview, it->container), tagName(RSCP_TAGS::RscpTagsOverview, it->tag), errName(RSCP_TAGS::RscpErrorOverview, it->error), it->count);
else if (!it->container && it->tag && it->error) logMessage(file, (char *)__FILE__, it->type, it->message, tagName(RSCP_TAGS::RscpTagsOverview, it->tag), errName(RSCP_TAGS::RscpErrorOverview, it->error), it->count);
else if (it->container && it->tag && !it->error) logMessage(file, (char *)__FILE__, it->type, it->message, tagName(RSCP_TAGS::RscpTagsOverview, it->container), tagName(RSCP_TAGS::RscpTagsOverview, it->tag), it->count);
else logMessage(file, (char *)__FILE__, it->type, it->message, it->count);
if (clear) it->count = 0;
}
}
return;
}
bool existsNotSupportedTag(uint32_t container, uint32_t tag) {
for (std::vector<RSCP_MQTT::not_supported_tags_t>::iterator it = RSCP_MQTT::NotSupportedTags.begin(); it != RSCP_MQTT::NotSupportedTags.end(); ++it) {
if ((it->container == container) && (it->tag == tag)) return(true);
}
return(false);
}
void pushNotSupportedTag(uint32_t container, uint32_t tag) {
if (existsNotSupportedTag(container, tag)) return;
RSCP_MQTT::not_supported_tags_t v;
v.container = container;
v.tag = tag;
RSCP_MQTT::NotSupportedTags.push_back(v);
return;
}
bool existsAdditionalTag(uint32_t container, uint32_t tag, int index) {
for (std::vector<RSCP_MQTT::additional_tags_t>::iterator it = RSCP_MQTT::AdditionalTags.begin(); it != RSCP_MQTT::AdditionalTags.end(); ++it) {
if ((it->req_container == container) && (it->req_tag == tag) && (it->req_index == index)) return(true);
}
return(false);
}
void pushAdditionalTag(uint32_t req_container, uint32_t req_tag, int req_index, int order, bool one_shot) {
if (existsAdditionalTag(req_container, req_tag, req_index)) return;
RSCP_MQTT::additional_tags_t v;
v.req_container = req_container;
v.req_tag = req_tag;
v.req_index = req_index;
v.order = order;
v.one_shot = one_shot;
RSCP_MQTT::AdditionalTags.push_back(v);
tags_added = true;
return;
}
bool updateRawData(char *topic, char *payload) {
if (topic && payload) {
for (std::vector<RSCP_MQTT::mqtt_data_t>::iterator it = RSCP_MQTT::rawData.begin(); it != RSCP_MQTT::rawData.end(); ++it) {
if (!strcmp(it->topic, topic)) {
if (strcmp(it->payload, payload)) {
if (strlen(it->payload) != strlen(payload)) it->payload = (char *)realloc(it->payload, strlen(payload) + 1);
strcpy(it->payload, payload);
}
return(true);
}
}
}
return(false);
}
void insertRawData(char *topic, char *payload) {
if (topic && payload) {
RSCP_MQTT::mqtt_data_t v;
v.topic = strdup(topic);
v.payload = strdup(payload);
RSCP_MQTT::rawData.push_back(v);
}
return;
}
char *readRawData(char *topic) {
for (std::vector<RSCP_MQTT::mqtt_data_t>::iterator it = RSCP_MQTT::rawData.begin(); it != RSCP_MQTT::rawData.end(); ++it) {
if (!strcmp(it->topic, topic)) {
return(it->payload);
}
}
return(NULL);
}
void refreshCache(std::vector<RSCP_MQTT::cache_t> & v, char *payload) {
for (std::vector<RSCP_MQTT::cache_t>::iterator it = v.begin(); it != v.end(); ++it) {
if ((it->changed == false) && strcmp(it->payload, "") && (std::regex_match(it->topic, std::regex(payload)) || std::regex_match(payload, std::regex("^true|on|1$")))) it->changed = true;
}
if (std::regex_match(payload, std::regex("^true|on|1$")) || std::regex_match(payload, std::regex(".*(idle|period).*"))) period_trigger = true;
return;
}
void addPrefix(std::vector<RSCP_MQTT::cache_t> & v, char *prefix) {
char topic[TOPIC_SIZE];
if (prefix) {
for (std::vector<RSCP_MQTT::cache_t>::iterator it = v.begin(); it != v.end(); ++it) {
snprintf(topic, TOPIC_SIZE, "%s/%s", cfg.prefix, it->topic);
strcpy(it->topic, topic);
}
}
return;
}
int handleImmediately(RscpProtocol *protocol, SRscpValue *response, uint32_t container, int year, int month, int day) {
char topic[TOPIC_SIZE];
char payload[PAYLOAD_SIZE];
char fifo[1024];
int rc = 0;
for (std::vector<RSCP_MQTT::cache_t>::iterator it = RSCP_MQTT::RscpMqttCacheTempl.begin(); it != RSCP_MQTT::RscpMqttCacheTempl.end(); ++it) {
if ((it->container == container) && (it->tag == response->tag)) {
snprintf(topic, TOPIC_SIZE, it->topic, year, month, day);
// only float is handled
switch (it->format) {
case F_FLOAT_0 : {
snprintf(payload, PAYLOAD_SIZE, "%.0f", protocol->getValueAsFloat32(response) / it->divisor);
break;
}
case F_FLOAT_1 : {
snprintf(payload, PAYLOAD_SIZE, "%0.1f", protocol->getValueAsFloat32(response) / it->divisor);
break;
}
case F_AUTO :
case F_FLOAT_2 : {
snprintf(payload, PAYLOAD_SIZE, "%0.2f", protocol->getValueAsFloat32(response) / it->divisor);
break;
}
}
sprintf(fifo, "$=%s=%s=%s=$\n", topic, payload, it->unit);
writeFifo(fifo, false);
}
}
return(rc);
}
int storeIntegerValue(std::vector<RSCP_MQTT::cache_t> & c, uint32_t container, uint32_t tag, int value, int index, bool dobreak) {
char buf[PAYLOAD_SIZE];
for (std::vector<RSCP_MQTT::cache_t>::iterator it = c.begin(); it != c.end(); ++it) {
if ((it->container == container) && (it->tag == tag) && (it->index == index)) {
if (it->bit_to_bool) {
if (value & it->bit_to_bool) strcpy(buf, cfg.true_value);
else strcpy(buf, cfg.false_value);
} else {
snprintf(buf, PAYLOAD_SIZE, "%d", value);
}
if (strcmp(it->payload, buf)) {
strcpy(it->payload, buf);
it->changed = true;
}
if (dobreak) break;
}
}
return(value);
}
float storeFloatValue(std::vector<RSCP_MQTT::cache_t> & c, uint32_t container, uint32_t tag, float value, int index, bool dobreak) {
char buf[PAYLOAD_SIZE];
for (std::vector<RSCP_MQTT::cache_t>::iterator it = c.begin(); it != c.end(); ++it) {
if ((it->container == container) && (it->tag == tag) && (it->index == index)) {
switch (it->format) {
case F_FLOAT_0 : {
snprintf(buf, PAYLOAD_SIZE, "%.0f", value / it->divisor);
break;
}
case F_FLOAT_1 : {
snprintf(buf, PAYLOAD_SIZE, "%0.1f", value / it->divisor);
break;
}
case F_AUTO :
case F_FLOAT_2 : {
snprintf(buf, PAYLOAD_SIZE, "%0.2f", value / it->divisor);
break;
}
}
if (strcmp(it->payload, buf)) {
strcpy(it->payload, buf);
it->changed = true;
}
if (dobreak) break;
}
}
return(value);
}
void storeStringValue(std::vector<RSCP_MQTT::cache_t> & c, uint32_t container, uint32_t tag, char *value, int index) {
char buf[PAYLOAD_SIZE];
for (std::vector<RSCP_MQTT::cache_t>::iterator it = c.begin(); it != c.end(); ++it) {
if ((it->container == container) && (it->tag == tag) && (it->index == index)) {
snprintf(buf, PAYLOAD_SIZE, "%s", value);
if (strcmp(it->payload, buf)) {
strcpy(it->payload, buf);
it->changed = true;
}
break;
}
}
return;
}
int getIntegerValue(std::vector<RSCP_MQTT::cache_t> & c, uint32_t container, uint32_t tag, int index) {
int value = 0;
for (std::vector<RSCP_MQTT::cache_t>::iterator it = c.begin(); it != c.end(); ++it) {
if ((it->container == container) && (it->tag == tag) && (it->index == index) && (it->bit_to_bool == 0)) {
value = atoi(it->payload);
break;
}
}
return(value);
}
float getFloatValue(std::vector<RSCP_MQTT::cache_t> & c, uint32_t container, uint32_t tag, int index) {
float value = 0.0;
for (std::vector<RSCP_MQTT::cache_t>::iterator it = c.begin(); it != c.end(); ++it) {
if ((it->container == container) && (it->tag == tag) && (it->index == index)) {
value = atof(it->payload);
break;
}
}
return(value);
}
void preparePayload(RscpProtocol *protocol, SRscpValue *response, char **buf) {
switch (response->dataType) {
case RSCP::eTypeBool: {
if (protocol->getValueAsBool(response)) strcpy(*buf, cfg.true_value);
else strcpy(*buf, cfg.false_value);
break;
}
case RSCP::eTypeInt16: {
snprintf(*buf, PAYLOAD_SIZE, "%i", protocol->getValueAsInt16(response));
break;
}
case RSCP::eTypeTimestamp:
case RSCP::eTypeInt32: {
snprintf(*buf, PAYLOAD_SIZE, "%i", protocol->getValueAsInt32(response));
break;
}
case RSCP::eTypeUInt16: {
snprintf(*buf, PAYLOAD_SIZE, "%u", protocol->getValueAsUInt16(response));
break;
}
case RSCP::eTypeUInt32: {
snprintf(*buf, PAYLOAD_SIZE, "%u", protocol->getValueAsUInt32(response));
break;
}
case RSCP::eTypeChar8: {
snprintf(*buf, PAYLOAD_SIZE, "%i", protocol->getValueAsChar8(response));
break;
}
case RSCP::eTypeUChar8: {
snprintf(*buf, PAYLOAD_SIZE, "%u", protocol->getValueAsUChar8(response));
break;
}
case RSCP::eTypeFloat32: {
snprintf(*buf, PAYLOAD_SIZE, "%0.2f", protocol->getValueAsFloat32(response));
break;
}
case RSCP::eTypeDouble64: {
snprintf(*buf, PAYLOAD_SIZE, "%0.2f", protocol->getValueAsDouble64(response));
break;
}
case RSCP::eTypeString: {
snprintf(*buf, PAYLOAD_SIZE, "%s", protocol->getValueAsString(response).c_str());
break;
}
default: {
strcpy(*buf, "");
break;
}
}
return;
}
int storeResponseValue(std::vector<RSCP_MQTT::cache_t> & c, RscpProtocol *protocol, SRscpValue *response, uint32_t container, int index) {
char buf[PAYLOAD_SIZE];
static int battery_soc = -1;
int rc = -1;
for (std::vector<RSCP_MQTT::cache_t>::iterator it = c.begin(); it != c.end(); ++it) {
if ((it->container > container) && (it->tag > response->tag)) break;
if ((!it->container || (it->container == container)) && (it->tag == response->tag) && (it->index == index)) {
switch (response->dataType) {
case RSCP::eTypeBool: {
if (protocol->getValueAsBool(response)) strcpy(buf, "true");
else strcpy(buf, "false");
if (strcmp(it->payload, buf)) {
strcpy(it->payload, buf);
it->changed = true;