-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmbus-device.c
371 lines (316 loc) · 10 KB
/
mbus-device.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
/* Very basic M-Bus device that can act as a 'slave'
*
* Copyright (C) 2022 Addiva Elektronik AB
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <err.h>
#include <getopt.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <mbus/mbus.h>
#define dbg(...) if (debug) warnx(__VA_ARGS__)
#define log(...) warnx(__VA_ARGS__)
static char *device;
static int address;
static int debug;
static char *arg0;
/* Our fake identity, from std. pp 35 */
unsigned char fixed_response[] = {
0x68, 0x13, 0x13, 0x68, /* header of RSP_UD telegram (L-Field = 13h = 19d) */
0x08, 0x05, 0x73, /* C field = 08h (RSP_UD), address 5, CI field = 73h (fixed, LSByte first) */
0x78, 0x56, 0x34, 0x12, /* identification number = 12345678 */
0x0a, /* transmission counter = 0Ah = 10d */
0x00, /* status 00h: counters coded BCD, actual values, no errors */
0xe9, 0x7e, /* Type&Unit: medium water, unit1 = 1l, unit2 = 1l (same, but historic) */
0x01, 0x00, 0x00, 0x00, /* counter 1 = 1l (actual value) */
0x35, 0x01, 0x00, 0x00, /* counter 2 = 135 l (historic value) */
0x3c, 0x16 /* checksum and stop sign */
};
/* Our fake identity, from std. pp 43, variable data structure (mode 1) */
unsigned char raw_response[] = {
0x68, 0x1f, 0x1f, 0x68, /* header of RSP_UD telegram (length 1fh) */
0x08, 0x02, 0x72, /* C field = 08h (RSP_UD), address 2, CI field = 72h */
0x78, 0x56, 0x34, 0x12, /* identification number = 12345678 */
0x24, 0x40, 0x01, 0x07, /* manuf. ID 4024h (PAD in EN 61107), generation 1, water */
0x55, 0x00, 0x00, 0x00, /* TC 55h, Status 00h, Signature 0000h */
0x03, 0x13, 0x15, 0x31, 0x00, /* Data block 1: unit 0, storage No 0, no tariff, instantaneous volume, 12565 l (24 bit integer */
0xda, 0x02, 0x3b, 0x13, 0x01, /* Data block 2: unit 0, storage No 5, no tariff, maximum volume flow, 113 l/h (4 digit BCD) */
0x8b, 0x60, 0x04, 0x37, 0x18, 0x02, /* Data block 3: unit 1, storage No 0, tariff 2, instantaneous energy, 218,37 kWh (6 digit BCD) */
0x18, 0x16 /* checksum and stop sign */
};
/*
* random delay of ACK so multiple devices don't collide on the bus.
*/
static void mbus_send_ack(mbus_handle *h)
{
mbus_frame *f;
usleep((rand() % 1000) + 1);
f = mbus_frame_new(MBUS_FRAME_TYPE_ACK);
if (mbus_send_frame(h, f))
warnx("Failed sending ACK");
free(f);
}
static int match_secondary(mbus_frame *f, mbus_frame_data *me)
{
unsigned char mask[4];
unsigned char addr[4];
long long fid, oid;
int match = 0;
int i;
if (f->data_size < 8 || f->data_size > 8) {
warnx("Invalid scan frame: %s", mbus_error_str());
return 0;
}
memcpy(mask, f->data, 4);
memcpy(addr, me->data_var.header.id_bcd, 4);
fid = mbus_data_bcd_decode_hex(mask, 4);
oid = mbus_data_bcd_decode_hex(addr, 4);
for (i = 0; i < 8; i++) {
int shift = 28 - i * 4;
char f, o;
f = (fid >> shift) & 0x0f;
o = (oid >> shift) & 0x0f;
if (f == 0xf)
continue;
if (f == o)
match = 1;
}
if (match) {
dbg("Select by secondary %lld [%02X %02X %02X %02X], me %lld [%02X %02X %02X %02X]",
fid, mask[0], mask[1], mask[2], mask[3],
oid, addr[0], addr[1], addr[2], addr[3]);
}
return match;
}
static int usage(int rc)
{
fprintf(stderr,
"Usage: %s [-d] [-a ADDR] [-b RATE] [-f FILE] DEVICE\n"
"\n"
"Options:\n"
" -a ADDR Set primary address, default: 0\n"
" -b RATE Set baudrate: 300, 2400, 9600, default: 2400\n"
" -d Enable debug messages\n"
" -f file Test data to reuse, simulate another product\n"
" -F Use fixed data structure instead of variable\n"
" -p Disable parity bit => 8N1, default: 8E1\n"
"Arguments:\n"
" DEVICE Serial port/pty to use\n"
"\n"
"Copyright (c) 2022 Addiva Elektronik AB\n", arg0);
return rc;
}
int main(int argc, char **argv)
{
mbus_frame ack, request, response;
mbus_handle *handle;
unsigned char *buf;
char *file = NULL;
int parity = 1;
int fixed = 0;
long rate = 0;
size_t len;
int result;
int c;
arg0 = argv[0];
while ((c = getopt(argc, argv, "a:b:dFf:p")) != EOF) {
switch (c) {
case 'a':
address = atoi(optarg);
break;
case 'b':
rate = atol(optarg);
break;
case 'd':
debug = 1;
break;
case 'f':
file = optarg;
break;
case 'F':
fixed = 1;
break;
case 'p':
parity = 0;
break;
default:
return usage(0);
}
}
if (optind >= argc)
return usage(1);
device = argv[optind++];
srand(time(NULL));
memset(&request, 0, sizeof(mbus_frame));
handle = mbus_context_serial(device);
if (!handle) {
warnx("Failed initializing M-Bus context: %s", mbus_error_str());
return 1;
}
if (debug) {
mbus_register_send_event(handle, &mbus_dump_send_event);
mbus_register_recv_event(handle, &mbus_dump_recv_event);
}
if (mbus_connect(handle) == -1)
errx(1, "Failed opening serial port: %s", mbus_error_str());
if (rate && mbus_serial_set_baudrate(handle, rate) == -1)
errx(1, "Failed setting baud rate %ld on serial port %s: %s",
rate, device, mbus_error_str());
if (!parity)
mbus_serial_set_parity(handle, 0);
if (file) {
unsigned char filebuf[1024], binbuf[1024];
FILE *fp;
fp = fopen(file, "r");
if (!fp)
err(1, "Failed opening %s", file);
len = fread(filebuf, 1, sizeof(filebuf) - 1, fp);
filebuf[len] = 0;
fclose(fp);
buf = binbuf;
len = mbus_hex2bin(binbuf, sizeof(binbuf), filebuf, sizeof(filebuf));
} else {
if (fixed) {
buf = fixed_response;
len = sizeof(fixed_response);
} else {
/* variable response example */
buf = raw_response;
len = sizeof(raw_response);
}
}
result = mbus_parse(&response, buf, len);
if (result != 0)
errx(1, "Invalid M-Bus response frame, rc %d: %s", result, mbus_error_str());
mbus_frame_data *me = mbus_frame_data_new();
if (!me)
errx(1, "Failed allocating device data");
if (mbus_frame_data_parse(&response, me) == -1)
errx(1, "Failed parsing my identity");
response.address = address;
char *secondary = mbus_frame_get_secondary_address(&response);
if (!secondary) {
dbg("Starting up, primary addr %d, no secondary: %s", address, mbus_error_str());
} else {
dbg("Starting up, primary addr %d, secondary addr %s", address, secondary);
}
int selected = 0;
while (1) {
int fcb = 0, forus = 0;
int rc;
/*
* Workaround. Currently libmbus is solely focused on
* the master role. As such the mbus_recv_frame() has
* safeguards that don't apply to a slave device, which
* means we cannot use that function or we lose every
* other frame.
*/
rc = handle->recv(handle, &request);
if (rc != MBUS_RECV_RESULT_OK) {
if (rc == MBUS_RECV_RESULT_ERROR) {
warn("Bailing out, %s", mbus_error_str());
break;
}
continue;
}
time(&request.timestamp);
if (request.start1 == MBUS_FRAME_ACK_START)
continue;
switch (request.address) {
case MBUS_ADDRESS_BROADCAST_NOREPLY:
continue; /* nop */
case MBUS_ADDRESS_BROADCAST_REPLY:
forus = 1;
break; /* all should respond */
case MBUS_ADDRESS_NETWORK_LAYER:
/* secondary address selection in progress? */
if (selected) {
/* Respond to REQ_UD2 */
forus = 1;
}
break;
default:
if (request.address == address) {
forus = 1;
break;
}
dbg("Not for us (%d), got addr %d control %d",
address, request.address, request.control);
continue;
}
if (request.control & MBUS_CONTROL_MASK_FCB) {
request.control &= ~MBUS_CONTROL_MASK_FCB;
fcb = 1;
}
switch (request.control) {
case MBUS_CONTROL_MASK_SND_NKE: /* wakeup */
dbg("SND_NKE (0x%X)", MBUS_CONTROL_MASK_SND_NKE);
if (request.address == MBUS_ADDRESS_NETWORK_LAYER) {
selected = 0; /* std. v4.8 ch 7.1 pp 64 */
mbus_send_ack(handle);
}
if (forus) /* std. v4.8 ch 5.4 pp 25 */
mbus_send_ack(handle);
break;
case MBUS_CONTROL_MASK_REQ_UD2: /* req data */
dbg("REQ_UD2 (0x%X) forus:%d", MBUS_CONTROL_MASK_REQ_UD2, forus);
if (!forus)
break;
if (mbus_send_frame(handle, &response))
warnx("Failed sending response: %s", mbus_error_str());
break;
case MBUS_CONTROL_MASK_SND_UD: /* select secondary? */
switch (request.control_information) {
case MBUS_CONTROL_INFO_DATA_SEND:
dbg("SND_UD (0x%X) INFO DATA (0x%X)", MBUS_CONTROL_MASK_SND_UD, MBUS_CONTROL_INFO_DATA_SEND);
if (request.data[0] == 0x01 && request.data[1] == 0x7a) {
/* Secondary selection or Primary addressing */
if (!selected && request.address != address)
break;
log("Setting new primary address %d", request.data[2]);
address = request.data[2];
response.address = address;
mbus_send_ack(handle);
}
break;
case MBUS_CONTROL_INFO_SELECT_SLAVE:
dbg("SND_UD (0x%X) SELECT SLAVE (0x%X)", MBUS_CONTROL_MASK_SND_UD, MBUS_CONTROL_INFO_SELECT_SLAVE);
if (match_secondary(&request, me)) {
mbus_send_ack(handle);
selected = 1;
} else {
selected = 0; /* std. v4.8 ch 7.1 pp 64 */
}
break;
default:
/* unsupported atm */
break;
}
break;
default:
warnx("Unsupported request, C %d", request.control);
continue;
}
}
mbus_disconnect(handle);
mbus_context_free(handle);
return 0;
}