Repository navigation
Expand file tree
/
Copy pathemModbus2influx.cpp
More file actions
1561 lines (1352 loc) · 49.1 KB
/
Copy pathemModbus2influx.cpp
File metadata and controls
1561 lines (1352 loc) · 49.1 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
/******************************************************************************
emModbus2influx
Read from modbus energy meters (currently DRT428M-3
and send the data to influxdb (1.x or 2.x API) and/or via mqtt
******************************************************************************/
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <getopt.h>
#include <ctype.h>
#include <errno.h>
#include <termios.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include "argparse.h"
#include <math.h>
#include <sys/ioctl.h>
#include <signal.h>
#include <time.h>
#include "log.h"
#ifndef DISABLE_MQTT
#include "mqtt_publish.h"
#endif
#include "influxdb-post/influxdb-post.h"
#include "meterDef.h"
#include "modbusread.h"
#include "global.h"
#include "parser.h"
#include <modbus.h>
#include "global.h"
#include <endian.h>
#include "cron.h"
#include <inttypes.h>
#ifdef CURL_STATIC
#include "curl/curl.h"
#else
#include <curl/curl.h>
#endif
#ifndef DISABLE_FORMULAS
#include "muParser.h"
#endif
#ifndef DISABLE_MQTT
#include "MQTTClient.h"
#endif
#define VER "1.44 Armin Diehl <ad@ardiehl.de> Jun 10,2026 compiled " __DATE__ " " __TIME__ " "
#define ME "emModbus2influx"
#define CONFFILE "emModbus2influx.conf"
#define MQTT_CLIENT_ID ME
#define NUM_RECS_TO_BUFFER_ON_FAILURE 1000
// this is for grafana live (via MQTT and telegraf), if we only send data when changed
// grafana will, after some time, show "NO DATA"
#define MQTT_SEND_UNCHANGED
#ifndef DISABLE_FORMULAS
extern double formulaNumPolls;
#endif
char *configFileName;
char * serDevice;
char * serBaudrate;
char *serParity;
char *serStopbits;
char * ser_rs485;
int dumpRegisters;
int dryrun;
int queryIntervalSecs = 5; // seconds
char *formulaValMeterName;
int formulaTry;
int scanRTU;
int scanRTUReg;
int modbusDebug;
influx_client_t *iClient;
int showModbusRetries;
int ModbusRTU_exitErrorCount = 5;
int testConfigFile;
int noinitialwrite;
#ifndef DISABLE_MQTT
mqtt_pubT *mClient;
#endif
#define MQTT_PREFIX_DEF "ad/house/energy/"
int doTry = false;
#define INFLUX_DEFAULT_MEASUREMENT "energyMeter"
#define INFLUX_DEFAULT_TAGNAME "Meter"
char * influxMeasurement;
char * influxTagName;
int influxWriteMult; // write to influx only on x th query (>=2)
int iVerifyPeer = 1;
int mqttQOS;
int mqttRetain;
int mqttFormat;
int mqttDelayMs;
char * mqttprefix;
char * mqttstatprefix;
char * cronExpression;
int scan;
int scanStart;
int scanEnd = 0xffff;
char * scanHost;
char * scanPort = strdup("502");
int scanAddr;
int scanInput;
int scanHolding;
// Grafana Live
char *ghost;
int gport = 3000;
char *gtoken;
char *gpushid;
char *gpushStatId;
int gUseInfluxMeasurement;
int gVerifyPeer = 1;
influx_client_t *gClient;
void scanAddresses() {
modbus_t *ctx;
int reg;
uint16_t value;
int res;
int isSerial = 0;
int numFound;
if (!scanInput && !scanHolding) {
scanInput++; scanHolding++;
}
if (scanHost) {
ctx = modbus_new_tcp_pi(scanHost, scanPort);
} else {
ctx = *modbusRTU_getmh(0,"scanAddresses");
isSerial++;
}
modbus_set_debug(ctx,modbusDebug);
if (!isSerial && scanAddr == 0) scanAddr = 0xff;
if (!scanAddr) {
fprintf(stderr, "no slave address specified\n");
return;
}
res = modbus_connect(ctx);
if (res != 0) {
if (scanHost) {
fprintf(stderr,"unable to connect to %s:%s (%s)\n",scanHost,scanPort,modbus_strerror(errno));
} else
fprintf(stderr,"unable to connect to Serial0 (%s)\n",modbus_strerror(errno));
return;
}
res = modbus_set_slave(ctx, scanAddr);
if (res == -1) {
fprintf(stderr, "Invalid slave address\n");
modbus_free(ctx);
return;
}
fprintf(stderr,"connected to %s, slave address %d\n",scanHost ? scanHost : "Serial0", scanAddr);
if (scanEnd < scanStart) scanEnd = scanStart+1;
printf("Scanning from %d to %d\n",scanStart,scanEnd);
if (scanHolding) {
printf("Scanning Holding registers (function 3):\n");
numFound = 0;
for (reg=scanStart; reg<=scanEnd; reg++) {
res = modbus_read_registers(ctx, reg,1,&value);
if (res == ETIMEDOUT) {
msleep(50);
res = modbus_read_registers(ctx, reg,1,&value);
}
if (reg % 10 == 0) { printf("\r%d ",reg); fflush(stdout); }
if (res >= 0) {
printf("\r%d (0x%04x): 0x%04x (%d)\n",reg,reg,value,value);
numFound++;
}
if (verbose && (res <= 0)) printf("\r%d Res:%d (%s)\n",reg,errno,modbus_strerror(errno));
if (isSerial) {
modbusRTU_SilentDelay(modbusRTU_getBaudrate(0));
modbusRTU_SilentDelay(modbusRTU_getBaudrate(0));
}
//msleep(250);
}
printf("\rfound %d holding registers\n\n",numFound);
}
if (scanInput) {
printf("\nInput registers (function 4):\n");
numFound = 0;
for (reg=scanStart; reg<=scanEnd; reg++) {
res = modbus_read_input_registers(ctx, reg, 1,&value);
if (res == ETIMEDOUT) {
msleep(50);
res = modbus_read_input_registers(ctx, reg,1,&value);
}
if (reg % 10 == 0) { printf("\r%d ",reg); fflush(stdout); }
if (res >= 0) {
printf("\r%d (0x%04x): 0x%04x (%d)\n",reg,reg,value,value);
numFound++;
}
if (verbose && (res <= 0)) printf("\r%d Res:%d (%s)\n",reg,errno,modbus_strerror(errno));
if (isSerial) modbusRTU_SilentDelay(modbusRTU_getBaudrate(0));
}
printf("\rfound %d input registers\n\n",numFound);
}
}
int syslogTestCallback(argParse_handleT *a, char * arg) {
VPRINTF(0,"%s : sending testtext via syslog\n\n",ME);
log_setSyslogTarget(ME);
VPRINTF(0,"testtext via syslog by %s",ME);
exit(0);
}
int showVersionCallback(argParse_handleT *a, char * arg) {
#ifndef DISABLE_MQTT
MQTTClient_nameValue* MQTTVersionInfo;
char *MQTTVersion = NULL;
int i;
#endif
printf("%s %s\n",ME,VER);
printf(" libmodbus: %d.%d.%d - ",LIBMODBUS_VERSION_MAJOR,LIBMODBUS_VERSION_MINOR,LIBMODBUS_VERSION_MICRO);
#ifdef MODBUS_STATIC
printf("static\n");
#else
printf("dynamic\n");
#endif
#ifndef DISABLE_FORMULAS
printf(" muparser: %s - ",mu::ParserVersion.c_str());
#ifdef MUPARSER_STATIC
printf("static\n");
#else
printf("dynamic\n");
#endif
#else
printf(" muparser: disabled at compile time\n");
#endif
#ifndef DISABLE_MQTT
MQTTVersionInfo = MQTTClient_getVersionInfo();
i = 0;
while (MQTTVersionInfo[i].name && MQTTVersion == NULL) {
if (strcasecmp(MQTTVersionInfo[i].name,"Version") == 0) {
MQTTVersion = (char *)MQTTVersionInfo[i].value;
break;
}
i++;
}
if (MQTTVersion) {
printf("paho mqtt-c: %s - ",MQTTVersion);
#ifdef PAHO_STATIC
printf("static\n");
#else
printf("dynamic\n");
#endif
}
#else
printf("paho mqtt-c: disabled at compile time\n");
#endif
curl_version_info_data *ver = curl_version_info(CURLVERSION_NOW);
printf(" libcurl: %u.%u.%u - ", (ver->version_num >> 16) & 0xff, (ver->version_num >> 8) & 0xff, ver->version_num & 0xff);
#ifdef CURL_STATIC
printf("static\n");
#else
printf("dynamic\n");
#endif
#ifdef __GNUC__
printf(" gcc: " __VERSION__ "\n");
#endif
exit(2);
}
// to avoid unused error message for --configfile
int dummyCallback(argParse_handleT *a, char * arg) {
return 0;
}
#define CONFFILEARG "--configfile="
int parseArgs (int argc, char **argv) {
int res = 0;
int i;
char * dbName = NULL;
char * serverName = NULL;
char * userName = NULL;
char * password = NULL;
char * bucket = NULL;
char * org = NULL;
char * token = NULL;
char * influxApiStr = NULL;
int syslog = 0;
int port = 8086;
int numQueueEntries = NUM_RECS_TO_BUFFER_ON_FAILURE;
int influxapi=1;
argParse_handleT *a;
influxMeasurement = strdup(INFLUX_DEFAULT_MEASUREMENT);
influxTagName = strdup(INFLUX_DEFAULT_TAGNAME);
serBaudrate = strdup("9600");
serStopbits = strdup("1");
AP_START(argopt)
AP_HELP
AP_OPT_STRVAL_CB (0,0,"configfile" ,NULL ,"config file name",&dummyCallback)
AP_OPT_STRVAL (0,'d',"device" ,&serDevice ,"specify serial device names separated by ,")
AP_OPT_STRVAL (1,0 ,"baud" ,&serBaudrate ,"baudrates separated by ,")
AP_OPT_STRVAL (1,'a',"parity" ,&serParity ,"N (default), E or O")
AP_OPT_STRVAL (1,'S' ,"stopbits" ,&serStopbits ,"1 or 2 stopbits")
AP_OPT_STRVAL (1,'4',"rs485" ,&ser_rs485 ,"set rs485 mode")
//AP_REQ_STRVAL_CB (1,'a',"tags" ,NULL ,"specify influxdb tags for each meter separated by ,", &parseTagCallback)
AP_OPT_STRVAL (1,'m',"measurement" ,&influxMeasurement ,"Influxdb measurement")
AP_OPT_STRVAL (1,'g',"tagname" ,&influxTagName ,"Influxdb tag name")
AP_OPT_STRVAL (1,'s',"server" ,&serverName ,"influxdb server name or ip")
AP_OPT_INTVAL (1,'o',"port" ,&port ,"influxdb port")
AP_OPT_STRVAL (1,'b',"db" ,&dbName ,"Influxdb v1 database name")
AP_OPT_STRVAL (1,'u',"user" ,&userName ,"Influxdb v1 user name")
AP_OPT_STRVAL (1,'p',"password" ,&password ,"Influxdb v1 password")
AP_OPT_STRVAL (1,'B',"bucket" ,&bucket ,"Influxdb v2 bucket")
AP_OPT_STRVAL (1,'O',"org" ,&org ,"Influxdb v2 org")
AP_OPT_STRVAL (0,'T',"token" ,&token ,"Influxdb v2 auth api token")
AP_OPT_INTVAL (0, 0 ,"influxwritemult",&influxWriteMult ,"Influx write multiplicator")
AP_OPT_INTVAL (1,0 ,"isslverifypeer" ,&iVerifyPeer ,"Influx SSL certificate verification (0=off)")
AP_OPT_STRVAL (0,'A',"influxapi" ,&influxApiStr ,"Influxdb api string, if specified db..token will not be used")
AP_OPT_INTVAL (1,'c',"cache" ,&numQueueEntries ,"#entries for influxdb cache")
#ifndef DISABLE_MQTT
AP_OPT_STRVAL (1,'M',"mqttserver" ,&mClient->hostname ,"mqtt server name or ip")
AP_OPT_STRVAL (1,'C',"mqttprefix" ,&mqttprefix ,"prefix for mqtt publish")
AP_OPT_STRVAL (1,0 ,"mqttstatprefix" ,&mqttstatprefix ,"prefix for mqtt statistics publish")
AP_OPT_INTVAL (1,'R',"mqttport" ,&mClient->port ,"ip port for mqtt server")
AP_OPT_INTVAL (1,'Q',"mqttqos" ,&mqttQOS ,"default mqtt QOS, can be changed for meter")
AP_OPT_INTVAL (1,'l',"mqttdelay" ,&mqttDelayMs ,"delay milliseconds after mqtt publish")
AP_OPT_INTVAL (1,'r',"mqttretain" ,&mqttRetain ,"default mqtt retain, can be changed for meter")
AP_OPT_STRVAL (1,'i',"mqttclientid" ,&mClient->clientId ,"mqtt client id")
AP_OPT_INTVAL (1,0 ,"mqttformat" ,&mqttFormat ,"json format, 0=std,1=Logo array")
#endif
AP_OPT_STRVAL (1,0 ,"ghost" ,&ghost ,"grafana server url w/o port, e.g. ws://localost or https://localhost")
AP_OPT_INTVAL (1,0 ,"gport" ,&gport ,"grafana port")
AP_OPT_STRVAL (1,0 ,"gtoken" ,>oken ,"authorisation api token for Grafana")
AP_OPT_STRVAL (1,0 ,"gpushid" ,&gpushid ,"push id for Grafana")
AP_OPT_STRVAL (1,0 ,"gpushstatid" ,&gpushStatId ,"statistics push id for Grafana")
AP_OPT_INTVAL (1,0 ,"ginfluxmeas" ,&gUseInfluxMeasurement,"use influx measurement names for grafana as well")
AP_OPT_INTVAL (1,0 ,"gsslverifypeer" ,&gVerifyPeer ,"grafana SSL certificate verification (0=off)")
AP_OPT_INTVALFO (0,'v',"verbose" ,&log_verbosity ,"increase or set verbose level")
AP_OPT_INTVALF (0,'G',"modbusdebug" ,&modbusDebug ,"set debug for libmodbus")
AP_OPT_INTVALF (0,0,"modbusshowretries",&showModbusRetries ,"show retries on failed modbus reads")
AP_OPT_INTVAL (0,'P',"poll" ,&queryIntervalSecs ,"poll intervall in seconds")
AP_OPT_STRVAL (0, 'H',"cron" ,&cronExpression ,"Crontab style expression like Sec Min Hour Day Mon Wday")
AP_OPT_INTVALF (0, 0 ,"no-threads" ,&disableThreadedQuery ,"enable threaded query (one thread for each serial port and one for tcp)")
AP_OPT_INTVAL (1,0 ,"maxrtuerrs" ,&ModbusRTU_exitErrorCount,"exit if all meters on a serial port failed n times")
AP_OPT_INTVALF (0,'y',"syslog" ,&syslog ,"log to syslog insead of stderr")
AP_OPT_INTVALF_CB (0,'Y',"syslogtest" ,NULL ,"send a testtext to syslog and exit",&syslogTestCallback)
AP_OPT_INTVALF_CB (0,'e',"version" ,NULL ,"show version and exit",&showVersionCallback)
AP_OPT_INTVALF (0,'D',"dumpregisters" ,&dumpRegisters ,"Show registers read from all meters and exit, twice to show received data")
AP_OPT_INTVALFO (0,'U',"dryrun" ,&dryrun ,"Show what would be written to MQTT/Influx for one query and exit")
AP_OPT_INTVALF (0,'t',"try" ,&doTry ,"try to connect returns 0 on success")
AP_OPT_STRVAL (0, 0 ,"formtryt" ,&formulaValMeterName ,"interactive try out formula for register values for a given meter name")
AP_OPT_INTVALF (0, 0 ,"formtry" ,&formulaTry ,"interactive try out formula (global for formulas in meter definition)")
AP_OPT_INTVALF (1, 0 ,"scanrtu" ,&scanRTU ,"scan for modbus rtu devices")
AP_OPT_INTVAL (1, 0 ,"scanreg" ,&scanRTUReg ,"register to be used for scanrtu")
AP_OPT_INTVALF (1, 0 ,"scan" ,&scan ,"scan a device for available registers")
AP_OPT_INTVAL (1, 0 ,"scanstart" ,&scanStart ,"register to start scan with")
AP_OPT_INTVAL (1, 0 ,"scanend" ,&scanEnd ,"register to end scan with")
AP_OPT_STRVAL (0, 0 ,"scanhost" ,&scanHost ,"TCP hostname, if not specified Modbus RTU will be used for scan")
AP_OPT_STRVAL (0, 0 ,"scanport" ,&scanPort ,"TCP port number or name")
AP_OPT_INTVAL (1, 0 ,"scanaddr" ,&scanAddr ,"Modbus address to scan")
AP_OPT_INTVALF (1, 0 ,"scaninput" ,&scanInput ,"scan input registers (default=both)")
AP_OPT_INTVALF (1, 0 ,"scanholding" ,&scanHolding ,"scan holding registers (default=both)")
AP_OPT_INTVALF (1, 0 ,"test" ,&testConfigFile ,"test config file")
AP_OPT_INTVALF (1, 0 ,"noinitialwrite" ,&noinitialwrite ,"do not perform a write after initial query of all meters")
AP_END;
// check if we have a configfile argument
int len = strlen(CONFFILEARG);
for (i=1;i<argc;i++) {
if (strncmp(CONFFILEARG,argv[i],len) == 0) {
configFileName = strdup(argv[i]+len);
int fh = open(configFileName,O_RDONLY);
if (fh < 0) {
EPRINTFN("unable to open config file '%s'",configFileName);
exit(1);
}
close(fh);
LOGN(1,"using configfile \"%s\"",configFileName);
break;
}
}
if (configFileName == NULL) configFileName = strdup(CONFFILE);
a = argParse_init(argopt, configFileName, NULL,
"The cache will be used in case the influxdb server is down. In\n" \
"that case data will be send when the server is reachable again.\n");
res = argParse (a, argc, argv, 0);
if (res != 0) {
argParse_free (a);
return res;
}
//mClient->topicPrefix = mqttprefix;
if (doTry==0 && serverName != NULL) {
if (!influxApiStr) {
if (org || token || bucket) influxapi++;
//if (serverName == NULL) { EPRINTF("influx server name not specified\n"); exit(1); }
if (influxapi == 1) {
if (!dbName) { EPRINTF("influxdb database name not specified\n"); exit(1); }
} else {
if (!org) { EPRINTF("influxdb org not specified\n"); exit(1); }
if (!bucket) { EPRINTF("influxdb bucket not specified\n"); exit(1); }
if (!token) { EPRINTF("influxdb token not specified\n"); exit(1); }
if (dbName) EPRINTF("Warning: database name ignored for influxdb v2 api\n");
if (userName) EPRINTF("Warning: user name ignored for influxdb v2 api\n");
if (password) EPRINTF("Warning: password ignored for influxdb v2 api\n");
}
}
}
#ifndef DISABLE_MQTT
if (mClient->hostname) {
if (!mqttprefix) {
EPRINTF("mqttprefix required\n"); exit(1);
}
}
#endif
if (syslog) log_setSyslogTarget(ME);
if (doTry == 0) {
if (serverName) {
LOG(1,"Influx init: serverName: %s, port %d, dbName: %s, userName: %s, password: %s, org: %s, bucket:%s, numQueueEntries %d, influxApiStr: %s\n",serverName, port, dbName, userName, password, org, bucket, numQueueEntries, influxApiStr);
iClient = influxdb_post_init (serverName, port, dbName, userName, password, org, bucket, token, numQueueEntries, influxApiStr, iVerifyPeer);
}
}
free(dbName);
free(serverName);
free(userName);
free(password);
free(bucket);
free(org);
free(token);
free(influxApiStr);
argParse_free (a);
return 0;
}
int terminated;
void sigterm_handler(int signum) {
LOGN(0,"sigterm_handler called, terminating");
signal(SIGINT, NULL);
terminated++;
}
void sigusr1_handler(int signum) {
log_verbosity++;
LOGN(0,"verbose: %d",log_verbosity);
}
void sigusr2_handler(int signum) {
if (log_verbosity) log_verbosity--;
LOGN(0,"verbose: %d",log_verbosity);
}
#define INITIAL_BUFFER_LEN 256
void appendToStr (const char *src, char **dest, int *len, int *bufsize) {
int srclen;
if (src == NULL) return;
if (*src == 0) return;
srclen = strlen(src);
while (*len + srclen + 1 > *bufsize) {
*bufsize *= 2;
//printf("Realloc to %d, len=%d, srclen: %d %x %x %s\n",*bufsize,*len,srclen,dest,*dest,*dest);
*dest = (char *)realloc(*dest,*bufsize);
if (*dest == NULL) { EPRINTF("Out of memory in appendToStr"); exit(1); };
}
strcat(*dest,src);
*len += srclen;
}
#define VALBUFLEN 64
void appendValue (int includeName, meterRegisterRead_t *rr, char **dest, int *len, int *bufsize) {
char valbuf[VALBUFLEN];
char format[30];
char *nameBuf;
int nameBufSize;
char *p = &valbuf[0];
if (rr->isInt) {
//snprintf(valbuf,VALBUFLEN,"%lld",(int64_t) rr->fvalue);
snprintf(valbuf,VALBUFLEN,"%" PRId64,(int64_t) rr->fvalue);
} else {
snprintf(format,sizeof(format),"%%%d.%df",10+rr->registerDef->decimals,rr->registerDef->decimals);
snprintf(valbuf,VALBUFLEN,format,rr->fvalue);
while (*p && *p<=32) p++;
}
if (includeName) {
nameBufSize = strlen(rr->registerDef->name)+10;
nameBuf = (char *)malloc(nameBufSize);
snprintf(nameBuf,nameBufSize,"\"%s\":",rr->registerDef->name);
appendToStr(nameBuf,dest,len,bufsize);
free(nameBuf);
}
appendToStr(p,dest,len,bufsize);
}
void appendFormulaValue (int includeName, meterFormula_t *mf, char **dest, int *len, int *bufsize) {
char valbuf[VALBUFLEN];
char format[30];
char *nameBuf;
int nameBufSize;
char *p = &valbuf[0];
if (mf->forceType == force_int) {
snprintf(valbuf,VALBUFLEN,"%" PRId64,(int64_t) mf->fvalue);
} else {
snprintf(format,sizeof(format),"%%%d.%df",10+mf->decimals,mf->decimals);
snprintf(valbuf,VALBUFLEN,format,mf->fvalue);
while (*p && *p<=32) p++;
}
if (includeName) {
nameBufSize = strlen(mf->name)+10;
nameBuf = (char *)malloc(nameBufSize);
snprintf(nameBuf,nameBufSize,"\"%s\":",mf->name);
appendToStr(nameBuf,dest,len,bufsize);
free(nameBuf);
}
appendToStr(p,dest,len,bufsize);
}
#define APPEND(SRC) appendToStr(SRC,&buf,&buflen,&bufsize)
#ifndef DISABLE_MQTT
int mqttSendData (meter_t * meter,int dryrun) {
int bufsize = INITIAL_BUFFER_LEN;
char *buf;
int buflen = 0;
int first = 1;
meterRegisterRead_t *rr = meter->registerRead;
meterFormula_t *mf = meter->meterFormula;
char *arrayName;
char emptyStr = 0;
int rc = 0;
char *measurement;
char valBuf[VALBUFLEN];
double timeSecs;
int numRegs = 0;
// check if we have something to write
if (meter->disabled) return 0;
if (! meter->numEnabledRegisters_mqtt) return 0;
buf = (char *)malloc(bufsize);
if (buf == NULL) return -1;
*buf=0;
switch (meter->mqttFormat) {
case mqttFormatStd:
arrayName = &emptyStr;
APPEND("{\"name\":\"");
measurement = meter->influxMeasurement;
if (! measurement) measurement = influxMeasurement;
if (measurement) {
APPEND(measurement); APPEND(".");
}
APPEND(meter->name);
APPEND("\", ");
// registers from meter type
while (rr) {
if (rr->registerDef->enableMqttWrite) {
numRegs++;
if (rr->registerDef->arrayName) {
if (strcmp(arrayName,rr->registerDef->arrayName) != 0) { // start new array
if (strlen(arrayName)) APPEND("]"); // close previous array
arrayName = rr->registerDef->arrayName;
if (!first) APPEND(", ");
first = 0;
APPEND("\""); APPEND(arrayName); APPEND("\":["); // start new array
appendValue(0,rr,&buf,&buflen,&bufsize);
} else { // add to array as long as we are in the same array
APPEND(", ");
appendValue(0,rr,&buf,&buflen,&bufsize);
}
} else { // register not as array
if (strlen(arrayName)) { APPEND("]"); arrayName = &emptyStr; } // close previous array
if (!first) APPEND(", ");
first = 0;
appendValue(1,rr,&buf,&buflen,&bufsize);
}
}
rr = rr->next;
}
// registers from meter specific formulas
while (mf) {
if (mf->enableMqttWrite) {
numRegs++;
if (mf->arrayName) {
if (strcmp(arrayName,mf->arrayName) != 0) { // start new array
if (strlen(arrayName)) APPEND("]"); // close previous array
arrayName = mf->arrayName;
if (!first) APPEND(", ");
first = 0;
APPEND("\""); APPEND(arrayName); APPEND("\":["); // start new array
appendFormulaValue(0,mf,&buf,&buflen,&bufsize);
} else { // add to array as long as we are in the same array
APPEND(", ");
appendFormulaValue(0,mf,&buf,&buflen,&bufsize);
}
} else { // register not an array
if (strlen(arrayName)) { APPEND("]"); arrayName = &emptyStr; } // close previous array
if (!first) APPEND(", ");
first = 0;
appendFormulaValue(1,mf,&buf,&buflen,&bufsize);
}
}
mf = mf->next;
}
if (strlen(arrayName)) APPEND("]");
APPEND("}");
break;
case mqttFormatLogoArr:
// {"state":{"var1":{"value":[0,0]},"var2":{"value":[0]}}}
APPEND("{\"state\":{");
// registers from meter type
while (rr) {
if (rr->registerDef->enableMqttWrite) {
numRegs++;
if (!first) APPEND(",");
first = 0;
APPEND("\"");
APPEND(rr->registerDef->name);
APPEND("\":{\"value\":[");
appendValue(0,rr,&buf,&buflen,&bufsize);
APPEND("]}");
}
rr = rr->next;
}
// registers from meter specific formulas
while (mf) {
if (mf->enableMqttWrite) {
numRegs++;
if (!first) APPEND(",");
first = 0;
first = 0;
APPEND("\"");
APPEND(mf->name);
APPEND("\":{\"value\":[");
appendFormulaValue(0,mf,&buf,&buflen,&bufsize);
APPEND("]}");
}
mf = mf->next;
}
APPEND("}}");
break;
default:
EPRINTFN("Unsupported mqtt format (%d)",(int)meter->mqttFormat);
exit(1);
}
int doWrite = 1; // if mqtt retain is send, only write if data has been changed
#ifndef MQTT_SEND_UNCHANGED
if (meter->mqttLastSend && meter->mqttRetain) {
if (strcmp(buf,meter->mqttLastSend) == 0) doWrite--;
}
#endif
if (!dryrun) VPRINTFN(3,"%s: retain: %d, qos: %d, mqttLastSend: '%s', buf: '%s', doWrite: %d",meter->name,meter->mqttRetain,meter->mqttQOS,meter->mqttLastSend,buf,doWrite);
if (dryrun) {
printf("%s%s %s %s\n",meter->mqttprefix,meter->name,buf,doWrite ? "" : "- no change, will not be written");
} else {
if (doWrite) {
mClient->topicPrefix = meter->mqttprefix;
rc = mqtt_pub_strF (mClient,meter->name, 0, meter->mqttQOS,meter->mqttRetain, buf);
// message not needeed, we already has the disconnect message
//if (rc != MQTTCLIENT_SUCCESS && rc != MQTT_RECONNECTED) LOGN(0,"mqtt publish failed with rc: %d (connected=%d)",rc,MQTTClient_isConnected(mClient->client));
mClient->topicPrefix = NULL;
}
}
#ifndef MQTT_SEND_UNCHANGED
free(meter->mqttLastSend);
meter->mqttLastSend = buf;
#else
free(buf);
#endif
if (numRegs && mqttstatprefix) { //mqttstatprefix && meter->registerRead && !meter->meterType->isFormulaOnly) {
buf = (char *)malloc(bufsize);
if (buf == NULL) return -1;
*buf=0; buflen=0;
APPEND("{\"name\":\"stat.");
measurement = meter->influxMeasurement;
if (! measurement) measurement = influxMeasurement;
if (measurement) {
APPEND(measurement); APPEND(".");
}
APPEND(meter->name);
APPEND("\"");
if (!meter->isFormulaOnly) {
APPEND(", \"last\":");
timeSecs = meter->queryTimeNano / NANO_PER_SEC;
snprintf(valBuf,VALBUFLEN,"%06.4f",timeSecs);
APPEND(valBuf);
APPEND(", \"avg\":");
timeSecs = meter->queryTimeNanoAvg / NANO_PER_SEC;
snprintf(valBuf,VALBUFLEN,"%06.4f",timeSecs);
APPEND(valBuf);
APPEND(", \"min\":");
timeSecs = meter->queryTimeNanoMin / NANO_PER_SEC;
snprintf(valBuf,VALBUFLEN,"%06.4f",timeSecs);
APPEND(valBuf);
APPEND(", \"max\":");
timeSecs = meter->queryTimeNanoMax / NANO_PER_SEC;
snprintf(valBuf,VALBUFLEN,"%06.4f",timeSecs);
APPEND(valBuf);
APPEND(", \"initial\":");
timeSecs = meter->queryTimeNanoInitial / NANO_PER_SEC;
snprintf(valBuf,VALBUFLEN,"%06.4f",timeSecs);
APPEND(valBuf);
APPEND(", \"numQueries\":");
snprintf(valBuf,VALBUFLEN,"%d",meter->numQueries);
APPEND(valBuf);
}
APPEND(", \"numInfluxWrites\":");
snprintf(valBuf,VALBUFLEN,"%d",meter->numInfluxWrites);
APPEND(valBuf);
APPEND(", \"influxWriteCountdown\":");
snprintf(valBuf,VALBUFLEN,"%d",meter->influxWriteCountdown);
APPEND(valBuf);
APPEND(", \"numErrs\":");
snprintf(valBuf,VALBUFLEN,"%d",meter->numErrs);
APPEND(valBuf);
APPEND("}");
if (dryrun) {
printf("%s%s %s\n",meter->mqttprefix,meter->name,buf);
free(buf);
} else {
mClient->topicPrefix = mqttstatprefix;
mqtt_pub_strF (mClient,meter->name, 0, 0, 1, buf);
free(buf);
mClient->topicPrefix = NULL;
}
}
if (meter->mqttDelayMs) msleep(meter->mqttDelayMs);
return rc;
}
#endif
int influxAppendData (influx_client_t* c, meter_t *meter, uint64_t timestamp) {
meterRegisterRead_t *rr;
meterFormula_t *mf;
int regCount = 0;
int rc;
// use the global measurement or the one from the meter (if defined)
char * measurement = influxMeasurement;
if (meter->influxMeasurement) measurement = meter->influxMeasurement;
char * tagname = influxTagName;
if (meter->influxTagName) tagname = meter->influxTagName;
// check if we have something to write
if (meter->disabled) {
VPRINTFN(2,"%s; influx: meter is disabled");
return 0;
}
if (! meter->numEnabledRegisters_influx) {
VPRINTFN(2,"%s; influx: no enabled registers",meter->name);
return 0;
}
//VPRINTFN(2,"%s: InfluxAppendData\n",meter->name);
rc = influxdb_format_line(c, INFLUX_MEAS(measurement), INFLUX_TAG(tagname, meter->iname ? meter->iname : meter->name),INFLUX_END);
if (rc < 0) { EPRINTFN("influxdb_format_line failed, INFLUX_MEAS"); exit(1); }
rr = meter->registerRead;
while (rr) {
if (rr->registerDef->enableInfluxWrite) {
if (rr->isInt || rr->registerDef->forceType == force_int) {
rc = influxdb_format_line(c, INFLUX_F_INT(rr->registerDef->name, (int)rr->fvalueInflux), INFLUX_END);
if (rc< 0) { EPRINTFN("influxdb_format_line failed, INFLUX_F_INT"); exit(1); }
} else {
rc = influxdb_format_line(c, INFLUX_F_FLT(rr->registerDef->name, rr->fvalueInflux, rr->registerDef->decimals), INFLUX_END);
if (rc < 0) { EPRINTFN("influxdb_format_line failed, INFLUX_F_FLT"); exit(1); }
}
}
regCount++;
rr = rr->next;
}
// meter specific register formulas
mf = meter->meterFormula;
while (mf) {
if (mf->enableInfluxWrite) {
if (mf->forceType == force_int) {
rc = influxdb_format_line(c, INFLUX_F_INT(mf->name, (int)mf->fvalueInflux) ,INFLUX_END);
if (rc < 0) { EPRINTFN("influxdb_format_line failed, INFLUX_F_INT"); exit(1); }
regCount++;
} else {
rc = influxdb_format_line(c, INFLUX_F_FLT(mf->name, mf->fvalueInflux, mf->decimals), INFLUX_END);
if (rc < 0) { EPRINTFN("influxdb_format_line failed, INFLUX_F_FLT"); exit(1); }
regCount++;
}
}
mf = mf->next;
}
//printf("InfluxLine: '%s'\n",c->influxBuf);
rc = influxdb_format_line(c, INFLUX_TS(timestamp), INFLUX_END);
if (rc < 0) { EPRINTFN("influxdb_format_line failed, INFLUX_TS"); exit(1); }
if (regCount) meter->numInfluxWrites++;
return regCount;
}
#define CHANNEL_MAX_LEN 140
int grafanaAppendData (influx_client_t* c, meter_t *meter, uint64_t timestamp) {
meterRegisterRead_t *rr;
meterFormula_t *mf;
int regCount = 0;
int rc;
char channelName[255];
// check if we have something to write
if (meter->disabled) {
VPRINTFN(2,"%s; grafana: meter is disabled");
return 0;
}
if (! meter->numEnabledRegisters_grafana) {
VPRINTFN(2,"%s; grafana: no enabled registers",meter->name);
return 0;
}
VPRINTFN(2,"%s: grafanaAppendData",meter->name);
memset(channelName,0,sizeof(channelName));
if (gUseInfluxMeasurement) {
if (meter->influxMeasurement) strncpy(channelName,meter->influxMeasurement,CHANNEL_MAX_LEN);
else strncpy(channelName,influxMeasurement,CHANNEL_MAX_LEN);
if (strlen(channelName)) strncat(channelName,"/",CHANNEL_MAX_LEN);
}
strncat(channelName,meter->gname?meter->gname:meter->name,CHANNEL_MAX_LEN);
rc = influxdb_format_line(c, INFLUX_MEAS(channelName), INFLUX_END);
if (rc < 0) { EPRINTFN("influxdb_format_line failed, INFLUX_MEAS (grafana)"); exit(1); }
rr = meter->registerRead;
while (rr) {
if (rr->registerDef->enableGrafanaWrite) {
if (rr->isInt || rr->registerDef->forceType == force_int) {
rc = influxdb_format_line(c, INFLUX_F_INT(rr->registerDef->name, (int)rr->fvalue), INFLUX_END);
if (rc< 0) { EPRINTFN("influxdb_format_line failed, INFLUX_F_INT"); exit(1); }
} else {
rc = influxdb_format_line(c, INFLUX_F_FLT(rr->registerDef->name, rr->fvalue, rr->registerDef->decimals), INFLUX_END);
if (rc < 0) { EPRINTFN("influxdb_format_line failed, INFLUX_F_FLT"); exit(1); }
}
} //else printf("%s %s: disabled for Grafana\n",meter->name,rr->registerDef->name);
regCount++;
rr = rr->next;
}
// meter specific register formulas
mf = meter->meterFormula;
while (mf) {
if (mf->enableGrafanaWrite) {
if (mf->forceType == force_int) {
rc = influxdb_format_line(c, INFLUX_F_INT(mf->name, (int)mf->fvalueInflux) ,INFLUX_END);
if (rc < 0) { EPRINTFN("influxdb_format_line failed, INFLUX_F_INT"); exit(1); }
regCount++;
} else {
rc = influxdb_format_line(c, INFLUX_F_FLT(mf->name, mf->fvalueInflux, mf->decimals), INFLUX_END);
if (rc < 0) { EPRINTFN("influxdb_format_line failed, INFLUX_F_FLT"); exit(1); }
regCount++;
}
} //else printf("%s, meter formula field %s disabled for Grafana\n",meter->name,mf->name);
mf = mf->next;
}
//printf("GrafanaLine: '%s'\n",c->influxBuf);
rc = influxdb_format_line(c, INFLUX_TS(timestamp), INFLUX_END);
if (rc < 0) { EPRINTFN("influxdb_format_line failed, INFLUX_TS (grafana)"); exit(1); }
if (regCount) meter->numGrafanaWrites++;
return regCount;
}
int test;
int grafanaAppendStat (influx_client_t* c, uint64_t timestamp, double totalQueryTime) {
char channelName[255];
char fieldName[255];
int rc;
meter_t * meter = meters;
int meterCount = 0;
int len;
double timeSecs;
int statCount = 0;
// check if we have something to write
//TODO
test++;
memset(channelName,0,sizeof(channelName));
if (gpushStatId) {
strncpy(channelName,gpushStatId,CHANNEL_MAX_LEN);
if (strlen(channelName)) strncat(channelName,"/",CHANNEL_MAX_LEN);
} else {
if (gUseInfluxMeasurement) {
strncpy(channelName,influxMeasurement,CHANNEL_MAX_LEN);
if (strlen(channelName)) strncat(channelName,"/",CHANNEL_MAX_LEN);
strncat(channelName,"_STATISTICS",CHANNEL_MAX_LEN);
} else
strncat(channelName,"_STATISTICS",CHANNEL_MAX_LEN);
}
while (meter) {
if (!meter->disabled && !meter->isFormulaOnly) {
if (meter->isTCP || meter->isSerial) {
if (statCount == 0)
influxdb_format_line(c, INFLUX_MEAS(channelName), INFLUX_END);
statCount++;
len = snprintf(fieldName,sizeof(fieldName),"%s.%s",meter->name,"last");
if (len >= (int)(sizeof(fieldName)-1)) {
EPRINTF("Buffer overflow in grafanaAppendStat, meter: %s",meter->name);
exit(1);
}
timeSecs = meter->queryTimeNano / NANO_PER_SEC;
rc = influxdb_format_line(c, INFLUX_F_FLT(fieldName, timeSecs, 3), INFLUX_END);
if (rc < 0) { EPRINTFN("influxdb_format_line failed, rc:%d, INFLUX_F_FLT",rc); exit(1); }
len = snprintf(fieldName,sizeof(fieldName),"%s.%s",meter->name,"min");
if (len >= (int)(sizeof(fieldName)-1)) {
EPRINTF("Buffer overflow in grafanaAppendStat, meter: %s",meter->name);