-
Notifications
You must be signed in to change notification settings - Fork 2
/
obinsectd.c
2106 lines (1802 loc) · 55.8 KB
/
obinsectd.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
/*
* SPDX-License-Identifier: GPL-2.0
*
* A simple OBIS COSEM to MQTT proxy
*
* Copyright 2019 Bjørn Mork <[email protected]>
*
* crc16 and hdlc parts were taken from modemmanager, having:
* Copyright (C) 2010 Red Hat, Inc.
*
* Parsing struct:
* https://github.com/roarfred/AmsToMqttBridge/tree/master/Code/Arduino/HanReader/src
*
* Data samples and important findings (differences in parity and use of OBIS codes):
* https://github.com/roarfred/AmsToMqttBridge/tree/master/Samples
*
* HAN data packets are sent inside an HDLC frame. The following COSEM classes are used:
* - Data (class_id 1)
* - Register (class_id 3)
* - Clock (class_id 9)
*/
#include <endian.h>
#include <errno.h>
#include <getopt.h>
#include <fcntl.h>
#include <inttypes.h>
#include <json.h>
#include <limits.h>
#include <mosquitto.h>
#include <poll.h>
#include <signal.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>
#ifndef VERSION
#define VERSION "unknown"
#endif
#define CONFIG_FILE "/etc/obinsect.conf"
#define MQTT_BROKER "localhost"
#define MQTT_PORT 1883
#define MQTTS_PORT 8883
#define MQTT_KEEPALIVE 60
/* support config refresh */
static bool reread_cfg = false;
static char *cfgfile = CONFIG_FILE;
/* static metadata */
static char *progname = NULL;
static char hostname[64];
static char *serialport = NULL;
/* parsed configuration */
static json_object *cfg = NULL;
/* current OBIS list */
static json_object *current_list = NULL;
/* OBIS code lookup table - ListId must be first entry, and is fixed */
#define MAX_LIST_LENGTH 32
static const char *obiscode[MAX_LIST_LENGTH] = { "1-1:0.2.129.255" , NULL };
/* a few global settings - OK, this is a mess :-) */
static bool unscaled = false;
static bool units = false;
/* defines size of both the read buffer and the print buffer.- because I'm lazy... */
#define BUFSIZE (1024 * 2)
/* shared buffers */
static unsigned char *buf = NULL;
static char *printbuffer = NULL;
/* mosquitto client */
struct mosquitto *mosq = NULL;
/* logging stuff */
static bool debug = false;
#define _logit_nomqtt(lvl, format, arg...) \
do { \
switch (lvl) { \
case LOG_DEBUG: \
if (debug) \
fprintf(stderr, "DEBUG: " format, arg); \
break; \
case LOG_INFO: \
fprintf(stderr, "INFO: " format, arg); \
break; \
case LOG_ERROR: \
fprintf(stderr, "ERROR: " format, arg); \
} \
} while (0)
#define _logit(lvl, format, arg...) \
do { \
if (!printbuffer) { \
_logit_nomqtt(lvl, format, arg); \
} else { \
size_t __len; \
__len = snprintf(printbuffer, BUFSIZE, format, arg); \
if (__len >= BUFSIZE) \
__len = BUFSIZE - 1; \
_logit_nomqtt(lvl, "%s", printbuffer); \
while (__len > 1 && printbuffer[__len - 1] == '\n') \
__len--; \
log2mqtt(lvl, printbuffer, __len); \
} \
} while (0)
#define debug(format, arg...) _logit(LOG_DEBUG, format, arg)
#define err(format, arg...) _logit(LOG_ERROR, format, arg)
#define info(format, arg...) _logit(LOG_INFO, format, arg)
#define debug_nomqtt(format, arg...) _logit_nomqtt(LOG_DEBUG, format, arg)
#define err_nomqtt(format, arg...) _logit_nomqtt(LOG_ERROR, format, arg)
#define info_nomqtt(format, arg...) _logit_nomqtt(LOG_INFO, format, arg)
enum log_levels {
LOG_DEBUG = 0,
LOG_INFO,
LOG_ERROR,
_MAX_LOG_LEVELS
};
#define MAX_LOG_TOPICS 4
static const char *log_topic[_MAX_LOG_LEVELS][MAX_LOG_TOPICS] = {};
static void mqtt_publish(const char *topic, const char *msg, size_t msglen)
{
static int reconnect = 1;
static int mid = 1;
if (mosquitto_publish(mosq, &mid, topic, msglen, msg, 0, false)) { /* QoS = 0 */
info_nomqtt("mqtt broker went away -reconnecting (%d)\n", reconnect++);
mosquitto_reconnect(mosq);
}
}
static int log2mqtt(int lvl, const char *msg, size_t msglen)
{
int i;
for (i = 0; i < MAX_LOG_TOPICS && log_topic[lvl][i]; i++)
mqtt_publish(log_topic[lvl][i], msg, msglen);
return i;
}
static void libmosquitto_log_callback(struct mosquitto *mosq, void *userdata, int level, const char *str)
{
switch (level) {
case MOSQ_LOG_ERR:
err_nomqtt("mqtt: %s\n", str);
break;
case MOSQ_LOG_DEBUG:
debug_nomqtt("mqtt: %s\n", str);
break;
default:
info_nomqtt("mqtt: %s\n", str);
}
}
/*
* crc16 and HDLC escape code borrowed from modemmanager/libqcdm
* Copyright (C) 2010 Red Hat, Inc.
*/
/* Table of CRCs for each possible byte, with a generator polynomial of 0x8408 */
static const uint16_t crc_table[256] = {
0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7,
0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e,
0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876,
0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd,
0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5,
0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c,
0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974,
0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb,
0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3,
0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a,
0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72,
0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9,
0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1,
0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738,
0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70,
0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7,
0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff,
0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036,
0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e,
0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5,
0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd,
0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134,
0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c,
0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3,
0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb,
0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232,
0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a,
0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1,
0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9,
0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330,
0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78
};
/* Calculate the CRC for a buffer using a seed of 0xffff */
static uint16_t crc16(const char *buffer, size_t len)
{
uint16_t crc = 0xffff;
while (len--)
crc = crc_table[(crc ^ *buffer++) & 0xff] ^ (crc >> 8);
return ~crc;
}
#define CONTROL 0x7e
static int serial_open(const char *dev)
{
struct termios terminal_data;
int fd;
fd = open(dev, O_RDONLY | O_NOCTTY);
if (fd > 0) {
tcgetattr(fd, &terminal_data);
cfmakeraw(&terminal_data);
cfsetspeed(&terminal_data, B2400); // 2400 8N1
tcsetattr(fd, TCSANOW, &terminal_data);
}
/* MQTT session is not yet ready */
debug_nomqtt("opened %s\n", dev);
return fd;
}
/*
* See /usr/local/src/git/AmsToMqttBridge/Samples/Kaifa/readme.md for docs!
*
* http://www.fit.vutbr.cz/units/UIFS/pubs/tr.php?file=%2Fpub%2F11616%2FTR-DLMS.pdf&id=11616
* (TR-DLMS.pdf) has a Table 3 contains data types usable for attributes of COSEM objects
*
* Better reference:
* https://www.dlms.com/files/Blue-Book-Ed-122-Excerpt.pdf,
* section 4.1.5 "Common data types"
Important types:
1 struct
2 array
6 double-long-unsigned
9 octet-string
10 visible-string
15 integer (8bit)
16 long (16bit)
18 long-unsigned (16bit)
22 enum (0..255)
both array and struct are followed by an element count. Structs can be nested
Ref aidon sample:
7e a0d2 41 0883 13 82d6 e6e700
0f 40000000 00
0109 // array of 9 elements
0202 // struct of 2 elements
0906 0101000281ff // octet-string of 6 bytes (OBIS code)
0a0b 4149444f4e5f5630303031 // visible-string of 11 bytes (AIDON_V0001)
0202 // struct of 2 elements
0906 0000600100ff // octet-string of 6 bytes (OBIS code)
0a10 37333539393932383930393431373432 // visible-string of 16 bytes (7359992890941742)
0202
0906 0000600107ff
0a04 36353135
0203 // struct of 3 elements
0906 0100010700ff // octet-string of 6 bytes (OBIS code)
06 00000552 // double-long-unsigned
0202 // struct of 2 elements (inner struct!)
0f00 // 8bit int (0)
161b // enum (27)
0203
0906 0100020700ff
06 00000000
0202
0f00
161b
0203
0906 0100030700ff
06 000003e4
0202
0f00
161d
0203
0906 0100040700ff
06 00000000
0202
0f00
161d
0203
0906 01001f0700ff
10 005d
0202
0fff
1621
0203
0906 0100200700ff
12 09c4
0202
0fff
1623
e0c4 7e
ref Kamstrup sample:
7E A0E2 2B 21 13 239A E6E700
0F 00000000 0C07D0010106162100FF800001
0219 // struct of 25 elements
0A0E 4B616D73747275705F5630303031
0906 0101000005FF
0A10 35373036353637303030303030303030
0906 0101600101FF
0A12 303030303030303030303030303030303030
0906 0101010700FF
0600000000 // double-long-unsigned (0)
0906 0101020700FF
0600000000
0906 0101030700FF
0600000000
0906 0101040700FF
0600000000
0906 01011F0700FF
0600000000
0906 0101330700FF
0600000000
0906 0101470700FF
0600000000
0906 0101200700FF
120000 // long-unsigned (0)
0906 0101340700FF
120000 // long-unsigned (0)
0906 0101480700FF
120000
5BE5 7E
* HDLC:
* no segmentation
* 1 byte addressing
* src: 16
* dst(client): 21
* frame-type: UI
* tx window: 1
* max tx len: 1010
* example:
7E A0E2 2B 21 13 239A E6E700
0F 00000000 0C07D0010106162100FF800001
0219
0A0E 4B616D73747275705F5630303031
0906 0101000005FF 0A10 35373036353637303030303030303030
0906 0101600101FF 0A12 303030303030303030303030303030303030
0906 0101010700FF 0600000000
0906 0101020700FF 0600000000
0906 0101030700FF 0600000000
0906 0101040700FF 0600000000
0906 01011F0700FF 0600000000
0906 0101330700FF 0600000000
0906 0101470700FF 0600000000
0906 0101200700FF 120000
0906 0101340700FF 120000
0906 0101480700FF 120000
5BE57E
Also observed for Kamstrup: L2 and L3 codes and values can be replaced
by 00 records, maintaining list integrity:
7E A0BA 2B 21 13 EDAA E6E700
0F 00000000 0C07E60205060D000AFF800000
0219
0A0E 4B616D73747275705F5630303031
0906 0101000005FF 0A10 35373036353637323731353333323037
0906 0101600101FF 0A12 36383631313131424E323432313031303430
0906 0101010700FF 0600000268
0906 0101020700FF 0600000000
0906 0101030700FF 0600000053
0906 0101040700FF 0600000000
0906 01011F0700FF 0600000122
00 00
00 00
0906 0101200700FF 1200E2
00 00
00 00
05D8 7E
*/
/* read states:
- framelen < 0: look for CONTROL
- framelen = 0: look for first two bytes different from CONTROL
- framelen > 0: wait for complete frame
- repeat
*/
static int hdlc_length(unsigned char *buf)
{
if ((buf[1] & 0xf8) != 0xa0) { // HDLC type 3 without segmentation
debug("unsupported frame type/len: %02x%02x\n", buf[1], buf[2]);
return -1;
}
return (buf[1] << 8 | buf[2]) & 0x7ff;
}
static unsigned char *hdlc_start(unsigned char *buf, size_t buflen)
{
unsigned char *p = memchr(buf, CONTROL, buflen);
/* skip remaining CONTROL chars */
while (p && p - buf + 1 < buflen && p[1] == CONTROL)
p++;
return p;
}
/* verifies the HDLC header and checksums, and returns the offset to the payload
side-effect on success:
creates a new top level json object to hold the parsed frame, adding a hdlc
struct with format, segmentation, length, src, dst, control, hcs and fcs fields
*/
static unsigned char *hdlc_verify(unsigned char *buf, size_t buflen, json_object *json)
{
int dstlen, format, segmentation, length, src, dst, control, hcs, fcs, check;
json_object *tmp;
/* already failed length check */
if (buflen < 2)
return NULL;
/* check start and stop markers */
if (buf[0] != CONTROL || buf[buflen -1] != CONTROL) {
err("HDLC frame is missing start or stop markers (%#04x)\n", CONTROL);
return NULL;
}
/* verify header */
format = buf[1] >> 4;
if (format != 0xa) {
err("DLMS/COSEM requires HDLC frame format \"type 3\" - %#04x is invalid\n", format);
return NULL;
}
segmentation = !!(buf[1] & 0x08);
if (segmentation) {
err("HDLC segmentation is unsupported (%02x%02x)\n", buf[1], buf[2]);
return NULL;
}
length = hdlc_length(buf);
if (length != buflen - 2) {
err("Invalid HDLC frame length: %d != %zd\n", length, buflen - 2);
return NULL;
}
/* src address is always 1 byte */
src = buf[3];
/* dst address is 1, 2 or 4 bytes */
dst = 0;
for (dstlen = 0; dstlen < 4; dstlen++) {
dst <<= 8;
dst |= buf[4 + dstlen];
if (dst & 1)
break;
}
if (dstlen == 3) {
err("Bogus HDLC destination address - 3 bytes?: %02x %02x %02x\n", buf[4], buf[5], buf[6]);
return NULL;
}
control = buf[5 + dstlen];
hcs = buf[7 + dstlen] << 8 | buf[6 + dstlen];
check = crc16((char *)(buf + 1), 5 + dstlen);
if (hcs != check) {
err("HDLC header checksum: %#06x != %#06x\n", hcs, check);
return NULL;
}
/* This will be the HCS, and therefore redundant, in case of an empty payload */
fcs = buf[buflen-2] << 8 | buf[buflen-3];
check = crc16((char *)(buf + 1), buflen - 4);
if (fcs != check) {
err("HDLC frame checksum: %#06x != %#06x\n", fcs, check);
return NULL;
}
/* create JSON frame object with HDLC data */
tmp = json_object_new_object();
json_object_object_add(tmp, "format", json_object_new_int(format));
json_object_object_add(tmp, "segmentation", json_object_new_boolean(segmentation));
json_object_object_add(tmp, "length", json_object_new_int(length));
json_object_object_add(tmp, "src", json_object_new_int(src));
json_object_object_add(tmp, "dst", json_object_new_int(dst));
json_object_object_add(tmp, "control", json_object_new_int(control));
json_object_object_add(tmp, "hcs", json_object_new_int(hcs));
json_object_object_add(tmp, "fcs", json_object_new_int(fcs));
json_object_object_add(json, "hdlc", tmp);
/* return offset to payload */
return &buf[8 + dstlen];
}
/*
* ref DLMS Blue-Book-Ed-122-Excerpt.pdf section 4.1.6.1 "Date and time formats"
* Ignoring hundredths, deviation and status which are unspecified in all samples I've seen
*/
static time_t decode_datetime(unsigned char *buf)
{
struct tm t = {};
t.tm_year = (buf[0] << 8 | buf[1]) - 1900; /* POSIX is year - 1900 */
t.tm_mon = buf[2] - 1; /* COSEM is 1...12, POSIX is 0..11 */
t.tm_mday = buf[3];
t.tm_wday = !buf[4] ? 7 : buf[4]; /* COSEM is 1...7, 1 is Monday, POSIX is 0..6, 0 is Sunday */
t.tm_hour = buf[5];
t.tm_min = buf[6];
t.tm_sec = buf[7];
if (buf[8] != 0xff)
debug("hundredths are valid: %02x\n", buf[8]);
if (buf[9] != 0x80 || buf[10])
debug("deviation is valid: %02x %02x\n", buf[9], buf[10]);
if (buf[11] && buf[11] != 0xff)
debug("staus is valid and set: %02x\n", buf[12]);
return mktime(&t);
}
/*
* Ref BS EN 62056-6-2:2013, page 30, "Table 3 - Enumerated values for physical units".
* according to "Hårek"
*/
static char *cosem_unit_enum(unsigned char e)
{
static char ret[17]; /* "unknown-unit-255" is 16 bytes */
switch (e) {
case 27: return "W";
case 28: return "VA";
case 29: return "VAr";
case 30: return "Wh"; // guessed based on received values
case 32: return "VArh"; // guessed based on received values
case 33: return "A";
case 35: return "V";
default:
sprintf(ret, "unknown-unit-%u", e);
return ret;
}
}
static char *cosem_typestr(unsigned char type)
{
/* ref DLMS Blue-Book-Ed-122-Excerpt.pdf section 4.1.5 "Common data types" */
switch (type) {
case 0: return "null-data";
case 1: return "array";
case 2: return "structure";
case 3: return "boolean";
case 4: return "bit-string";
case 5: return "double-long";
case 6: return "double-long-unsigned";
/* case 7: return “floating-point”; // not usable in DLMS/COSEM. */
case 9: return "octet-string";
case 10: return "visible-string";
/* case 11: return “time”; // not usable in DLMS/COSEM. */
case 12: return "utf8-string";
case 13: return "bcd";
case 15: return "integer";
case 16: return "long";
case 17: return "unsigned";
case 18: return "long-unsigned";
case 20: return "long64";
case 21: return "long64-unsigned";
case 22: return "enum";
case 23: return "float32";
case 24: return "float64";
case 25: return "date-time";
case 26: return "date";
case 27: return "time";
default: return "unknown";
}
}
// guessing OBIS code if length is 6 and value is a.b.x.x.x.255 where a and b are 0 or 1
static bool is_obis(unsigned char *code)
{
if (code[0] != 9 || code[1] != 6 || code[2] > 1 || code[3] > 1 || code[7] != 255)
return false;
return true;
}
static json_object *cosem_object_new_int(unsigned char *raw, size_t intlen, bool sign)
{
uint32_t hi, lo;
switch (intlen) {
case 1:
if (sign)
lo = (char)raw[1];
else
lo = raw[1];
break;
case 2:
if (sign)
lo = (int16_t)(raw[1] << 8 | raw[2]);
else
lo = raw[1] << 8 | raw[2];
break;
case 4:
if (sign)
lo = (int32_t)(raw[1] << 24 | raw[2] << 16 | raw[3] << 8 | raw[4]);
else
lo = raw[1] << 24 | raw[2] << 16 | raw[3] << 8 | raw[4];
break;
case 8:
hi = raw[1] << 24 | raw[2] << 16 | raw[3] << 8 | raw[4];
lo = raw[5] << 24 | raw[6] << 16 | raw[7] << 8 | raw[8];
return json_object_new_int64(sign ? (int64_t)hi << 32 | lo : (uint64_t)hi << 32 | lo);
}
return json_object_new_int(lo);
}
/*
* parse_cosem() returns the number of eaten bytes, as well as a JSON
* object in ret.
*
* type defs: DLMS Blue-Book-Ed-122-Excerpt.pdf section 4.1.5 "Common data types"
*/
static int parse_cosem(unsigned char *buf, size_t buflen, int lvl, json_object **ret)
{
int i, n, len = 0;
json_object *myobj;
char fieldname[32]; /* "double-long-unsigned" is 20 bytes */
*ret = NULL;
switch (buf[0]) {
case 0: // null-data
len = 1;
*ret = NULL;
break;
case 1: // array
*ret = json_object_new_array();
len = 2;
for (i = 0; i < buf[1]; i++) {
n = parse_cosem(&buf[len], buflen - len, lvl + 1, &myobj);
if (n < 0 || len > buflen)
goto err;
json_object_array_add(*ret, myobj);
len += n;
}
break;
case 2: // structure
*ret = json_object_new_object();
len = 2;
for (i = 0; i < buf[1]; i++) {
n = parse_cosem(&buf[len], buflen - len, lvl + 1, &myobj);
if (n < 0 || len > buflen)
goto err;
sprintf(fieldname, "%s-%u", is_obis(&buf[len]) ? "obis" : cosem_typestr(buf[len]), i);
json_object_object_add(*ret, fieldname, myobj);
len += n;
}
break;
case 5: // double-long
len = 4;
*ret = cosem_object_new_int(buf, len++, true);
break;
case 6: // double-long-unsigned
len = 4;
*ret = cosem_object_new_int(buf, len++, false);
break;
case 9: // octet-string
/* is this an OBIS code? - special handling make them a bit more readable */
if (is_obis(buf)) {
sprintf(fieldname, "%u-%u:%u.%u.%u.%u", buf[2], buf[3], buf[4], buf[5], buf[6], buf[7]);
*ret = json_object_new_string(fieldname);
}
/* fall through */
case 10: // visible-string
case 12: // utf8-string
len = 2 + buf[1];
if (!*ret)
*ret = json_object_new_string_len((char *)&buf[2], buf[1]);
break;
case 15: // integer
len = 1;
*ret = cosem_object_new_int(buf, len++ , true);
break;
case 16: // long
len = 2;
*ret = cosem_object_new_int(buf, len++, true);
break;
case 17: // unsigned
len = 1;
*ret = cosem_object_new_int(buf, len++, false);
break;
case 18: // long-unsigned
len = 2;
*ret = cosem_object_new_int(buf, len++, false);
break;
case 20: // long64
len = 8;
*ret = cosem_object_new_int(buf, len++, true);
break;
case 21: // long64-unsigned
len = 8;
*ret = cosem_object_new_int(buf, len++, false);
break;
case 22: // enum
len = 2;
*ret = json_object_new_string(cosem_unit_enum(buf[1]));
break;
case 25: // date-time
len = 1 + 12;
*ret = json_object_new_int(decode_datetime(&buf[1]));
break;
default:
err("Unsupported COSEM data type: %d (%02x)\n", buf[0], buf[0]);
}
if (len > buflen) {
err("Buggy COSEM data - buffer too short: %zd < %d\n", buflen, len);
goto err;
}
if (*ret || len) // must allow NULL ret for null-data
return len;
err:
if (*ret)
json_object_put(*ret);
*ret = NULL;
return -1;
}
/*
* the first 3 bytes of the payload is LLC:
* LSAP | DSAP | Quality, fixed to e6 e7 00
*/
static json_object *parse_llc(unsigned char *buf, size_t buflen)
{
json_object *tmp;
if (buf[0] != 0xe6 || buf[1] != 0xe7 || buf[2] != 0x00) {
err("Invalid LLC header: %02x %02x %02x\n", buf[0], buf[1], buf[2]);
return NULL;
}
tmp = json_object_new_object();
json_object_object_add(tmp, "lsap", json_object_new_int(0xe6));
json_object_object_add(tmp, "dsap", json_object_new_int(0xe7));
json_object_object_add(tmp, "quality", json_object_new_int(0x00));
return tmp;
}
static bool parse_payload(unsigned char *buf, size_t buflen, json_object *json)
{
unsigned long invokeid;
unsigned char *p;
time_t t = 0;
json_object *tmp, *body;
bool datetime_bug = false;
/* header parsing failed? */
if (!buf)
return false;
/* add LLC field */
json_object_object_add(json, "llc", parse_llc(buf, buflen));
/* a xDLMS APDU should follow immediately after the LLC
0F data-notification [15]
00 00 00 00 long-invoke-id-and-priority
0C 07 E1 0A 14 05 03 3A 1E FF 80 00 00 date-time
02 19 .... notification-body
*/
p = &buf[3];
if (p[0] != 0x0f) {
err("The xDLMS APDU must be 'data-notification' [15], not [%d], according to IEC 62056-7-5:2017\n", p[0]);
return false;
}
p++;
/* don't bother decoding the individual bits of long-invoke-id-and-priority */
invokeid = p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3];
p += 4;
/* some buggy firmwares includes a 0x09 type byte before the date-time - skip it */
if (p[0] == 0x09) {
datetime_bug = true;
p++;
}
/* The date-time field should by exactly 0 or 12 bytes, */
if (p[0] == 12)
t = decode_datetime(&p[1]);
p += p[0] + 1;
/* add a data-notification field to the JSON frame */
tmp = json_object_new_object();
json_object_object_add(json, "data-notification", tmp);
json_object_object_add(tmp, "long-invoke-id-and-priority", json_object_new_int(invokeid));
if (datetime_bug)
json_object_object_add(tmp, "date-time-bug", json_object_new_boolean(true));
if (t)
json_object_object_add(tmp, "date-time", json_object_new_int(t));
/* The remaining payload is the notification-body - parse and add to the JSON frame */
if (parse_cosem(p, buflen + buf - p, 0, &body) > 0)
json_object_object_add(tmp, "notification-body", body);
return true;
}
/* take the "raw" JSON data we parsed and convert it to a common vendor-independant struct */
/*
Samples:
a) Aidon list 2:
"data-notification":{
"long-invoke-id-and-priority":1088880655,
"date-time":0,
"notification-body":[
{
"obis-0":"1-1:0.2.129.255",
"visible-string-1":"AIDON_V0001"
},
{
"obis-0":"0-0:96.1.0.255",
"visible-string-1":"7359992890941742"
},
{
"obis-0":"0-0:96.1.7.255",
"visible-string-1":"6515"
},
{
"obis-0":"1-0:1.7.0.255",
"double-long-unsigned-1":1362,
"structure-2":{
"integer-0":0,
"enum-1":27
}
},
{
"obis-0":"1-0:2.7.0.255",
"double-long-unsigned-1":0,
"structure-2":{
"integer-0":0,
"enum-1":27
}
},
{
"obis-0":"1-0:3.7.0.255",
"double-long-unsigned-1":996,
"structure-2":{
"integer-0":0,
"enum-1":29
}
},
{
"obis-0":"1-0:4.7.0.255",
"double-long-unsigned-1":0,
"structure-2":{
"integer-0":0,
"enum-1":29
}
},
{
"obis-0":"1-0:31.7.0.255",
"long-1":93,
"structure-2":{
"integer-0":255,
"enum-1":33
}
},
{
"obis-0":"1-0:32.7.0.255",
"long-unsigned-1":2500,
"structure-2":{
"integer-0":255,
"enum-1":35
}
}
]
}
b) Kaifa list 1:
"data-notification":{
"long-invoke-id-and-priority":1088880655,
"date-time-bug":true,
"date-time":1505254726,
"notification-body":{
"double-long-unsigned-0":1333
}
}
c) Kaifa list 2:
"data-notification":{
"long-invoke-id-and-priority":1088880655,
"date-time-bug":true,
"date-time":1505254730,
"notification-body":{
"octet-string-0":"KFM_001",
"octet-string-1":"6970631401753985",
"octet-string-2":"MA304H3E",
"double-long-unsigned-3":1316,
"double-long-unsigned-4":0,
"double-long-unsigned-5":0,
"double-long-unsigned-6":129,
"double-long-unsigned-7":1746,
"double-long-unsigned-8":4565,
"double-long-unsigned-9":4712,
"double-long-unsigned-10":2400,
"double-long-unsigned-11":0,
"double-long-unsigned-12":2402
}
}
d) Kaifa list 3:
"data-notification":{
"long-invoke-id-and-priority":1088880655,
"date-time-bug":true,
"date-time":1505415610,
"notification-body":{
"octet-string-0":"KFM_001",
"octet-string-1":"6970631401753985",
"octet-string-2":"MA304H3E",
"double-long-unsigned-3":1022,
"double-long-unsigned-4":0,
"double-long-unsigned-5":0,
"double-long-unsigned-6":64,
"double-long-unsigned-7":1937,
"double-long-unsigned-8":3229,
"double-long-unsigned-9":3430,
"double-long-unsigned-10":2369,
"double-long-unsigned-11":0,
"double-long-unsigned-12":2380,
"octet-string-13":"Thu Sep 14 21:00:10 2017",
"double-long-unsigned-14":180073,
"double-long-unsigned-15":0,
"double-long-unsigned-16":247,
"double-long-unsigned-17":16380
}
}
e) Kamstrup list 1:
"data-notification":{
"long-invoke-id-and-priority":15138831,
"date-time-bug":true,
"date-time":1508467410,
"notification-body":{
"visible-string-0":"Kamstrup_V0001",
"obis-1":"1-1:0.0.5.255",
"visible-string-2":"5706567274389702",
"obis-3":"1-1:96.1.1.255",
"visible-string-4":"6841121BN243101040",
"obis-5":"1-1:1.7.0.255",
"double-long-unsigned-6":1468,
"obis-7":"1-1:2.7.0.255",