]> sigrok.org Git - libsigrok.git/blame - src/dmm/bm52x.c
serial-dmm: add support for the Brymen BM820s family
[libsigrok.git] / src / dmm / bm52x.c
CommitLineData
400bc4ff
GS
1/*
2 * This file is part of the libsigrok project.
3 *
4 * Copyright (C) 2014 Aurelien Jacobs <aurel@gnuage.org>
5 * Copyright (C) 2019-2020 Gerhard Sittig <gerhard.sittig@gmx.net>
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21/**
22 * @file
23 *
24 * Brymen BM52x serial protocol parser. The USB protocol (for the cable)
25 * and the packet description (for the meter) were retrieved from:
26 * http://brymen.com/product-html/Download2.html
27 * http://brymen.com/product-html/PD02BM520s_protocolDL.html
28 * http://brymen.com/product-html/images/DownloadList/ProtocolList/BM520-BM520s_List/BM520-BM520s-10000-count-professional-dual-display-mobile-logging-DMMs-protocol.zip
0931639a 29 *
6bee394d
GS
30 * This parser was initially created for BM520s devices and tested with
31 * BM525s. The Brymen BM820s family of devices uses the same protocol,
32 * with just 0x82 instead of 0x52 in request packets and in the fixed
33 * fields of the responses. Which means that the packet parser can get
34 * shared among the BM520s and BM820s devices, but validity check needs
35 * to be individual, and the "wrong" packet request will end up without
36 * a response. Compared to BM520s the BM820s has dBm (in the protocol)
37 * and NCV (not seen in the protocol) and is non-logging (live only).
38 * BM820s support was tested with BM829s.
39 *
0931639a
GS
40 * The parser implementation was tested with a Brymen BM525s meter. Some
41 * of the responses differ from the vendor's documentation:
42 * - Recording session total byte counts don't start after the byte count
43 * field, but instead include this field and the model ID (spans _every_
44 * byte in the stream).
45 * - Recording session start/end markers are referred to as DLE, STX,
46 * and ETX. Observed traffic instead sends 0xee, 0xa0, and 0xc0.
400bc4ff
GS
47 */
48
49/*
50 * TODO
400bc4ff
GS
51 * - Some of the meter's functions and indications cannot get expressed
52 * by means of sigrok MQ and flags terms. Some indicator's meaning is
53 * unknown or uncertain, and thus their state is not evaluated.
54 * - MAX-MIN, the span between extreme values, referred to as Vp-p.
55 * - AVG is not available in BM525s and BM521s.
56 * - LoZ, eliminating ghost voltages.
57 * - LPF, low pass filter.
400bc4ff
GS
58 * - low battery, emits sr_warn() but isn't seen in the feed.
59 * - @, 4-20mA loop, % (main display, left hand side), Hi/Lo. Some of
60 * these are in the vendor's documentation for the DMM packet but not
61 * supported by the BM525s device which motivated the creation of the
62 * parser's and was used to test its operation.
63 * - It's a guess that the many undocumented bits (44 of them) are
64 * related to the bargraph (40 ticks, overflow, sign, 6/10 scale).
65 * - Should T1-T2 have a delta ("relative") decoration? But the meter's
66 * "relative" feature is flexible, accepts any display value as the
67 * reference, including min/max/diff when displayed upon activation.
68 * - The "beep jack" displays "InEr" in the secondary display. This is
69 * not caught here, no PC side message gets emitted.
0931639a
GS
70 * - Support for recordings is mostly untested. It was written to the
71 * letter of the vendor documentation, but was not verified to work
72 * for all of the many meter's modes including ranges. Inspection of
73 * the full byte stream is necessary on one hand since random access
74 * is not available, and useful on the other hand for consistency
75 * checks.
400bc4ff
GS
76 */
77
78#include <config.h>
79#include <libsigrok/libsigrok.h>
80#include "libsigrok-internal.h"
81#include <math.h>
82#include <string.h>
0931639a 83#include <strings.h>
400bc4ff
GS
84
85#define LOG_PREFIX "brymen-bm52x"
86
0931639a
GS
87/*
88 * DMM specific device options, and state keeping. All of it is related
89 * to recorded information in contrast to live readings. There also are
90 * four types of requesting HID reports that need to be sent.
91 */
92
93static const uint32_t devopts[] = {
94 SR_CONF_CONTINUOUS,
95 SR_CONF_LIMIT_SAMPLES | SR_CONF_SET,
96 SR_CONF_LIMIT_MSEC | SR_CONF_SET,
97 SR_CONF_DATA_SOURCE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
98};
99
100struct brymen_bm52x_state {
101 size_t sess_idx;
102 struct {
103 uint8_t buff[2 * 32];
104 size_t fill_pos;
105 size_t read_pos;
106 size_t remain;
107 } rsp;
108 const struct sr_dev_inst *sdi;
109};
110
111enum bm52x_reqtype {
6bee394d
GS
112 REQ_LIVE_READ_520,
113 REQ_LIVE_READ_820,
0931639a
GS
114 REQ_REC_HEAD,
115 REQ_REC_NEXT,
116 REQ_REC_CURR,
117};
118
400bc4ff 119#ifdef HAVE_SERIAL_COMM
0931639a 120static int bm52x_send_req(struct sr_serial_dev_inst *serial, enum bm52x_reqtype t)
400bc4ff 121{
6bee394d
GS
122 static const uint8_t req_live_520[] = { 0x00, 0x00, 0x52, 0x66, };
123 static const uint8_t req_live_820[] = { 0x00, 0x00, 0x82, 0x66, };
0931639a
GS
124 static const uint8_t req_head[] = { 0x00, 0x00, 0x52, 0x88, };
125 static const uint8_t req_next[] = { 0x00, 0x00, 0x52, 0x89, };
126 static const uint8_t req_curr[] = { 0x00, 0x00, 0x52, 0x8a, };
127 static const uint8_t *req_bytes[] = {
6bee394d
GS
128 [REQ_LIVE_READ_520] = req_live_520,
129 [REQ_LIVE_READ_820] = req_live_820,
0931639a
GS
130 [REQ_REC_HEAD] = req_head,
131 [REQ_REC_NEXT] = req_next,
132 [REQ_REC_CURR] = req_curr,
133 };
6bee394d 134 static const size_t req_len = ARRAY_SIZE(req_live_520);
0931639a
GS
135
136 const uint8_t *p;
137 size_t l;
138 int ret;
400bc4ff 139
0931639a
GS
140 if (t >= ARRAY_SIZE(req_bytes))
141 return SR_ERR_ARG;
142 p = req_bytes[t];
143 l = req_len;
144 ret = serial_write_nonblocking(serial, p, l);
145 if (ret < 0)
146 return ret;
147 if ((size_t)ret != l)
148 return SR_ERR_IO;
400bc4ff
GS
149
150 return SR_OK;
151}
0931639a
GS
152
153SR_PRIV int sr_brymen_bm52x_packet_request(struct sr_serial_dev_inst *serial)
154{
6bee394d
GS
155 return bm52x_send_req(serial, REQ_LIVE_READ_520);
156}
157
158SR_PRIV int sr_brymen_bm82x_packet_request(struct sr_serial_dev_inst *serial)
159{
160 return bm52x_send_req(serial, REQ_LIVE_READ_820);
0931639a 161}
400bc4ff
GS
162#endif
163
0931639a
GS
164/*
165 * The following code interprets live readings ("real-time download")
166 * which arrive in the "traditional" bitmap for LCD segments. Reading
167 * previously recorded measurements ("memory data sets") differs a lot
168 * and is handled in other code paths.
169 */
170
400bc4ff
GS
171SR_PRIV gboolean sr_brymen_bm52x_packet_valid(const uint8_t *buf)
172{
173 if (buf[16] != 0x52)
174 return FALSE;
175 if (buf[17] != 0x52)
176 return FALSE;
177 if (buf[18] != 0x52)
178 return FALSE;
179 if (buf[19] != 0x52)
180 return FALSE;
181
182 return TRUE;
183}
184
6bee394d
GS
185SR_PRIV gboolean sr_brymen_bm82x_packet_valid(const uint8_t *buf)
186{
187 if (buf[16] != 0x82)
188 return FALSE;
189 if (buf[17] != 0x82)
190 return FALSE;
191 if (buf[18] != 0x82)
192 return FALSE;
193 if (buf[19] != 0x82)
194 return FALSE;
195
196 return TRUE;
197}
198
400bc4ff
GS
199/*
200 * Data bytes in the DMM packet encode LCD segments in an unusual order
201 * (bgcpafed) and in an unusual position (bit 4 being the decimal point
202 * for some digits, an additional indicator for others). Fortunately all
203 * eight digits encode their segments in identical ways across the bytes.
204 *
205 * These routines convert LCD segments to characters, and a section of the
206 * DMM packet (which corresponds to the primary or secondary display) to
207 * the text representation of the measurement's value, before regular text
208 * to number conversion is applied, and SI units and their prefixes get
209 * derived from more indicators. It's important to keep in mind similar
210 * indicators exist for main and secondary displays in different locations.
211 */
212
213static char brymen_bm52x_parse_digit(uint8_t b)
214{
215 switch (b & ~0x10) {
216 /* Sign. */
217 case 0x40: /* ------g */ return '-';
218 /* Decimal digits. */
219 case 0xaf: /* abcdef- */ return '0';
220 case 0xa0: /* -bc---- */ return '1';
221 case 0xcb: /* ab-de-g */ return '2';
222 case 0xe9: /* abcd--g */ return '3';
223 case 0xe4: /* -bc--fg */ return '4';
224 case 0x6d: /* a-cd-fg */ return '5';
225 case 0x6f: /* a-cdefg */ return '6';
226 case 0xa8: /* abc---- */ return '7';
227 case 0xef: /* abcdefg */ return '8';
228 case 0xed: /* abcd-fg */ return '9';
229 /* Temperature units. */
230 case 0x0f: /* a--def- */ return 'C';
231 case 0x4e: /* a---efg */ return 'F';
232 /* OL condition, and diode and "Auto" modes. */
233 case 0x07: /* ---def- */ return 'L';
234 case 0xe3: /* -bcde-g */ return 'd';
235 case 0x20: /* --c---- */ return 'i';
236 case 0x63: /* --cde-g */ return 'o';
237 case 0xee: /* abc-efg */ return 'A';
238 case 0x23: /* --cde-- */ return 'u';
239 case 0x47: /* ---defg */ return 't';
240 /* Blank digit. */
241 case 0x00: /* ------- */ return '\0';
242 /* Invalid or unknown segment combination. */
243 default:
244 sr_warn("Unknown encoding for digit: 0x%02x.", b);
245 return '\0';
246 }
247}
248
249static int brymen_bm52x_parse_digits(const uint8_t *pkt, size_t pktlen,
250 char *txtbuf, float *value, char *temp_unit, int *digits, int signflag)
251{
252 uint8_t byte;
253 char *txtptr, txtchar;
254 size_t pos;
255 int ret;
256
257 txtptr = txtbuf;
258 if (digits)
259 *digits = INT_MIN;
260
261 if (pkt[0] & signflag)
262 *txtptr++ = '-';
263 for (pos = 0; pos < pktlen; pos++) {
264 byte = pkt[1 + pos];
265 txtchar = brymen_bm52x_parse_digit(byte);
266 if (pos == 3 && (txtchar == 'C' || txtchar == 'F')) {
267 if (temp_unit)
268 *temp_unit = txtchar;
269 } else if (txtchar) {
270 *txtptr++ = txtchar;
271 if (digits)
272 (*digits)++;
273 }
274 if (pos < 3 && (byte & 0x10)) {
275 *txtptr++ = '.';
276 if (digits)
277 *digits = 0;
278 }
279 }
280 *txtptr = '\0';
281
282 if (digits && *digits < 0)
283 *digits = 0;
284
285 ret = value ? sr_atof_ascii(txtbuf, value) : SR_OK;
286 if (ret != SR_OK) {
287 sr_dbg("invalid float string: '%s'", txtbuf);
288 return ret;
289 }
290
291 return SR_OK;
292}
293
294/*
295 * Extract the measurement value and its properties for one of the
296 * meter's displays from the DMM packet.
297 */
298static void brymen_bm52x_parse(const uint8_t *buf, float *floatval,
299 struct sr_datafeed_analog *analog, size_t ch_idx)
300{
301 char txtbuf[16], temp_unit;
302 int ret, digits, scale;
303 int is_diode, is_auto, is_no_temp, is_ol, is_db, is_main_milli;
304 int is_mm_max, is_mm_min, is_mm_avg, is_mm_dash;
305
306 temp_unit = '\0';
307 if (ch_idx == 0) {
308 /*
309 * Main display. Note that _some_ of the second display's
310 * indicators are involved in the inspection of the _first_
311 * display's measurement value. So we have to get the
312 * second display's text buffer here, too.
313 */
314 (void)brymen_bm52x_parse_digits(&buf[7], 4, txtbuf,
315 NULL, NULL, NULL, 0);
316 is_diode = strcmp(txtbuf, "diod") == 0;
317 is_auto = strcmp(txtbuf, "Auto") == 0;
318 ret = brymen_bm52x_parse_digits(&buf[2], 4, txtbuf,
319 floatval, &temp_unit, &digits, 0x80);
320 is_ol = strstr(txtbuf, "0L") || strstr(txtbuf, "0.L");
321 is_no_temp = strcmp(txtbuf, "---C") == 0;
322 is_no_temp |= strcmp(txtbuf, "---F") == 0;
323 if (ret != SR_OK && !is_ol)
324 return;
325
326 /* SI unit, derived from meter's current function. */
327 is_db = buf[6] & 0x10;
328 is_main_milli = buf[14] & 0x40;
329 if (buf[14] & 0x20) {
330 analog->meaning->mq = SR_MQ_VOLTAGE;
331 analog->meaning->unit = SR_UNIT_VOLT;
332 if (is_diode) {
333 analog->meaning->mqflags |= SR_MQFLAG_DIODE;
334 analog->meaning->mqflags |= SR_MQFLAG_DC;
335 }
336 } else if (buf[14] & 0x10) {
337 analog->meaning->mq = SR_MQ_CURRENT;
338 analog->meaning->unit = SR_UNIT_AMPERE;
339 } else if (buf[14] & 0x01) {
340 analog->meaning->mq = SR_MQ_CAPACITANCE;
341 analog->meaning->unit = SR_UNIT_FARAD;
342 } else if (buf[14] & 0x02) {
343 analog->meaning->mq = SR_MQ_CONDUCTANCE;
344 analog->meaning->unit = SR_UNIT_SIEMENS;
345 } else if (buf[13] & 0x10) {
346 analog->meaning->mq = SR_MQ_FREQUENCY;
347 analog->meaning->unit = SR_UNIT_HERTZ;
348 } else if (buf[7] & 0x01) {
349 analog->meaning->mq = SR_MQ_CONTINUITY;
350 analog->meaning->unit = SR_UNIT_OHM;
351 } else if (buf[13] & 0x20) {
352 analog->meaning->mq = SR_MQ_RESISTANCE;
353 analog->meaning->unit = SR_UNIT_OHM;
354 } else if (is_db && is_main_milli) {
355 analog->meaning->mq = SR_MQ_POWER;
356 analog->meaning->unit = SR_UNIT_DECIBEL_MW;
357 } else if (buf[14] & 0x04) {
358 analog->meaning->mq = SR_MQ_DUTY_CYCLE;
359 analog->meaning->unit = SR_UNIT_PERCENTAGE;
360 } else if ((buf[2] & 0x09) && temp_unit) {
361 if (is_no_temp)
362 return;
363 analog->meaning->mq = SR_MQ_TEMPERATURE;
364 if (temp_unit == 'F')
365 analog->meaning->unit = SR_UNIT_FAHRENHEIT;
366 else
367 analog->meaning->unit = SR_UNIT_CELSIUS;
368 }
369
370 /*
371 * Remove the MIN/MAX/AVG indicators when all of them
372 * are shown at the same time (indicating that recording
373 * is active, but live readings are shown). This also
374 * removes the MAX-MIN (V p-p) indication which cannot
375 * get represented by SR_MQFLAG_* means.
376 *
377 * Keep the check conditions separate to simplify future
378 * maintenance when Vp-p gets added. Provide the value of
379 * currently unsupported modes just without flags (show
380 * the maximum amount of LCD content on screen that we
381 * can represent in sigrok).
382 */
383 is_mm_max = buf[1] & 0x01;
384 is_mm_min = buf[1] & 0x08;
385 is_mm_avg = buf[1] & 0x02;
386 is_mm_dash = buf[1] & 0x04;
387 if (is_mm_max && is_mm_min && is_mm_avg)
388 is_mm_max = is_mm_min = is_mm_avg = 0;
389 if (is_mm_max && is_mm_min && is_mm_dash)
390 is_mm_max = is_mm_min = 0;
391 if (is_mm_max && is_mm_min && !is_mm_dash)
392 is_mm_max = is_mm_min = 0;
393
394 /* AC/DC/Auto flags. Hold/Min/Max/Rel etc flags. */
395 if (buf[1] & 0x20)
396 analog->meaning->mqflags |= SR_MQFLAG_DC;
397 if (buf[1] & 0x10)
398 analog->meaning->mqflags |= SR_MQFLAG_AC;
399 if (buf[20] & 0x10)
400 analog->meaning->mqflags |= SR_MQFLAG_AUTORANGE;
401 if (buf[20] & 0x80)
402 analog->meaning->mqflags |= SR_MQFLAG_HOLD;
403 if (is_mm_max)
404 analog->meaning->mqflags |= SR_MQFLAG_MAX;
405 if (is_mm_min)
406 analog->meaning->mqflags |= SR_MQFLAG_MIN;
407 if (is_mm_avg)
408 analog->meaning->mqflags |= SR_MQFLAG_AVG;
409 if (buf[2] & 0x40)
410 analog->meaning->mqflags |= SR_MQFLAG_RELATIVE;
411
412 /*
413 * Remove the "dBm" indication's "m" indicator before the
414 * SI unit's prefixes get inspected. Avoids an interaction
415 * with the "milli" prefix. Strictly speaking BM525s does
416 * not support dBm, but other models do and we may want
417 * to share the protocol parser.
418 */
419 if (is_db)
420 is_main_milli = 0;
421
422 /* SI prefix. */
423 scale = 0;
424 if (buf[14] & 0x08) /* n */
425 scale = -9;
426 if (buf[14] & 0x80) /* u */
427 scale = -6;
428 if (is_main_milli) /* m */
429 scale = -3;
430 if (buf[13] & 0x80) /* k */
431 scale = +3;
432 if (buf[13] & 0x40) /* M */
433 scale = +6;
434 if (scale) {
435 *floatval *= pow(10, scale);
436 digits += -scale;
437 }
438
439 if (is_ol)
440 *floatval = INFINITY;
441
442 analog->encoding->digits = digits;
443 analog->spec->spec_digits = digits;
444 } else if (ch_idx == 1) {
445 /*
446 * Secondary display. Also inspect _some_ primary display
447 * data, to determine the secondary display's validity.
448 */
449 (void)brymen_bm52x_parse_digits(&buf[2], 4, txtbuf,
450 NULL, &temp_unit, NULL, 0x80);
451 ret = brymen_bm52x_parse_digits(&buf[7], 4, txtbuf,
452 floatval, NULL, &digits, 0x20);
453 is_diode = strcmp(txtbuf, "diod") == 0;
454 is_auto = strcmp(txtbuf, "Auto") == 0;
455 is_no_temp = strcmp(txtbuf, "---C") == 0;
456 is_no_temp |= strcmp(txtbuf, "---F") == 0;
457 if (is_diode || is_auto)
458 return;
459 if (is_no_temp)
460 return;
461
462 /* SI unit. */
463 if (buf[12] & 0x10) {
464 analog->meaning->mq = SR_MQ_VOLTAGE;
465 analog->meaning->unit = SR_UNIT_VOLT;
466 } else if (buf[12] & 0x20) {
467 analog->meaning->mq = SR_MQ_CURRENT;
468 if (buf[11] & 0x10)
469 analog->meaning->unit = SR_UNIT_PERCENTAGE;
470 else
471 analog->meaning->unit = SR_UNIT_AMPERE;
472 } else if (buf[13] & 0x02) {
473 analog->meaning->mq = SR_MQ_RESISTANCE;
474 analog->meaning->unit = SR_UNIT_OHM;
475 } else if (buf[12] & 0x02) {
476 analog->meaning->mq = SR_MQ_CONDUCTANCE;
477 analog->meaning->unit = SR_UNIT_SIEMENS;
478 } else if (buf[12] & 0x01) {
479 analog->meaning->mq = SR_MQ_CAPACITANCE;
480 analog->meaning->unit = SR_UNIT_FARAD;
481 } else if (buf[7] & 0x06) {
482 if (strstr(txtbuf, "---"))
483 return;
484 analog->meaning->mq = SR_MQ_TEMPERATURE;
485 if (temp_unit == 'F')
486 analog->meaning->unit = SR_UNIT_FAHRENHEIT;
487 else
488 analog->meaning->unit = SR_UNIT_CELSIUS;
489 } else if (buf[13] & 0x01) {
490 analog->meaning->mq = SR_MQ_FREQUENCY;
491 analog->meaning->unit = SR_UNIT_HERTZ;
492 } else if (buf[11] & 0x08) {
493 analog->meaning->mq = SR_MQ_DUTY_CYCLE;
494 analog->meaning->unit = SR_UNIT_PERCENTAGE;
495 }
496
497 /* DC/AC flags. */
498 if (buf[7] & 0x80)
499 analog->meaning->mqflags |= SR_MQFLAG_DC;
500 if (buf[7] & 0x40)
501 analog->meaning->mqflags |= SR_MQFLAG_AC;
502
503 /* SI prefix. */
504 scale = 0;
505 if (buf[12] & 0x04) /* n */
506 scale = -9;
507 if (buf[12] & 0x40) /* u */
508 scale = -6;
509 if (buf[12] & 0x80) /* m */
510 scale = -3;
511 if (buf[13] & 0x04) /* k */
512 scale = +3;
513 if (buf[13] & 0x08) /* M */
514 scale = +6;
515 if (scale) {
516 *floatval *= pow(10, scale);
517 digits += -scale;
518 }
519
520 analog->encoding->digits = digits;
521 analog->spec->spec_digits = digits;
522 }
523
524 if (buf[7] & 0x08)
525 sr_warn("Battery is low.");
526}
527
528SR_PRIV int sr_brymen_bm52x_parse(const uint8_t *buf, float *val,
529 struct sr_datafeed_analog *analog, void *info)
530{
531 struct brymen_bm52x_info *info_local;
532 size_t ch_idx;
533
534 /*
535 * Scan a portion of the received DMM packet which corresponds
536 * to the caller's specified display. Then prepare to scan a
537 * different portion of the packet for another display. This
538 * routine gets called multiple times for one received packet.
539 */
540 info_local = info;
541 ch_idx = info_local->ch_idx;
542 brymen_bm52x_parse(buf, val, analog, ch_idx);
543 info_local->ch_idx = ch_idx + 1;
544
545 return SR_OK;
546}
0931639a
GS
547
548/*
549 * The above code paths support live readings ("real-time download").
550 * The below code paths support recordings ("memory data sets") which
551 * use different requests and responses and measurement representation
552 * which feels like "a different meter".
553 */
554
555/*
556 * Developer notes, example data for recorded sessions.
557 *
558 * model
559 * 01
560 * total bytes
561 * e6 02 00
562 * session count
563 * 01 00
564 * "DLE/STX" marker
565 * ee a0
566 * PS/NS addresses
567 * 8a 03 a0 60 03 a0
568 * func/sel/stat (DC-V, single display)
569 * 02 00 00
570 * session page length in bytes (3 * 240)
571 * d0 02 00
572 * main[/secondary] display data
573 * 00 00 00 00
574 * checksums and padding
575 * 7c 05 00 00 00 00 00 00
576 * 00 00 80 00 00 80 00 00 80 00 00 80 00 00 00 00 00 80 00 00 80 00 00 80 80 03 00 00 00 00 00 00
577 * 00 00 00 00 00 00 00 00 80 00 00 80 00 00 80 00 00 80 00 00 80 00 00 80 00 03 00 00 00 00 00 00
578 * ...
579 * 00 00 80 00 00 00 00 00 00 00 00 80 00 00 80 00 00 80 00 00 80 00 00 80 00 03 00 00 00 00 00 00
580 * 00 00 80 00 00 80 00 00 80 00 00 80 00 00 80 00 00 80 00 00
581 * "DLE/ETX" marker
582 * ee c0
583 * ae 04 00 00 00 00 00 00
584 *
585 * - Checksum in bytes[25:24] is the mere sum of bytes[0:23].
586 * - Model ID is 0 or 1 -- does this translate to BM521s and BM525s?
587 * - Total byte count _includes_ everything starting at model ID.
588 * - There is no measurements count for a session page, but its length
589 * in bytes, and a dual display flag, which lets us derive the count.
590 * - STX/ETX/DLE markers don't use the expected ASCII codes.
591 */
592
593/*
594 * See vendor doc table 3.1 "Logging interval". Includes sub-1Hz rates,
595 * but also sub-1s intervals. Let's keep both presentations at hand.
596 */
597static const struct {
598 unsigned int ival_secs;
599 unsigned int freq_rate;
600} bm52x_rec_ivals[] = {
601 [ 0] = { 0, 20, },
602 [ 1] = { 0, 10, },
603 [ 2] = { 0, 2, },
604 [ 3] = { 1, 1, },
605 [ 4] = { 2, 0, },
606 [ 5] = { 3, 0, },
607 [ 6] = { 4, 0, },
608 [ 7] = { 5, 0, },
609 [ 8] = { 10, 0, },
610 [ 9] = { 15, 0, },
611 [10] = { 30, 0, },
612 [11] = { 60, 0, },
613 [12] = { 120, 0, },
614 [13] = { 180, 0, },
615 [14] = { 300, 0, },
616 [15] = { 600, 0, },
617};
618
619/*
620 * See vendor doc table 6 "Range bits". Temperature is not listed there
621 * but keeping it here unifies the processing code paths.
622 */
623static const int bm52x_ranges_volt[16] = { 3, 2, 1, 0, };
624static const int bm52x_ranges_millivolt[16] = { 5, 4, };
625static const int bm52x_ranges_freq[16] = { 3, 2, 1, 0, -1, -2, -3, };
626static const int bm52x_ranges_duty[16] = { 2, 1, };
627static const int bm52x_ranges_ohm[16] = { 1, 0, -1, -2, -3, -4, };
628static const int bm52x_ranges_cond[16] = { 11, };
629static const int bm52x_ranges_cap[16] = { 11, 10, 9, 8, 7, 6, 5, };
630static const int bm52x_ranges_diode[16] = { 3, };
631static const int bm52x_ranges_temp[16] = { 0, };
632static const int bm52x_ranges_amp[16] = { 3, 2, };
633static const int bm52x_ranges_milliamp[16] = { 5, 4, };
634static const int bm52x_ranges_microamp[16] = { 7, 6, };
635
636/** Calculate checksum of four-HID-report responses (recordings). */
637static uint16_t bm52x_rec_checksum(const uint8_t *b, size_t l)
638{
639 uint16_t cs;
640
641 cs = 0;
642 while (l--)
643 cs += *b++;
644
645 return cs;
646}
647
648/**
649 * Retrieve the first/next chunk of recording information.
650 * Support for live readings is theoretical, and unused/untested.
651 */
652static int bm52x_rec_next_rsp(struct sr_serial_dev_inst *serial,
653 enum bm52x_reqtype req, struct brymen_bm52x_state *state)
654{
655 uint8_t *b;
656 size_t l;
657 int ret;
658
659 /* Seed internal state when sending the HEAD request. */
6bee394d 660 if (req == REQ_REC_HEAD || req == REQ_LIVE_READ_520)
0931639a
GS
661 memset(&state->rsp, 0, sizeof(state->rsp));
662
663 /* Move unprocessed content to the front. */
664 if (state->rsp.read_pos) {
665 b = &state->rsp.buff[0];
666 l = state->rsp.fill_pos - state->rsp.read_pos;
667 if (l)
668 memmove(&b[0], &b[state->rsp.read_pos], l);
669 state->rsp.fill_pos -= state->rsp.read_pos;
670 state->rsp.read_pos = 0;
671 }
672
673 /* Avoid queries for non-existing data. Limit NEXT requests. */
674 if (req == REQ_REC_NEXT && !state->rsp.remain)
675 return SR_ERR_IO;
676
677 /* Add another response chunk to the read buffer. */
678 b = &state->rsp.buff[state->rsp.fill_pos];
6bee394d 679 l = req == REQ_LIVE_READ_520 ? 24 : 32;
0931639a
GS
680 if (sizeof(state->rsp.buff) - state->rsp.fill_pos < l)
681 return SR_ERR_BUG;
682 ret = bm52x_send_req(serial, req);
683 if (ret != SR_OK)
684 return ret;
685 ret = serial_read_blocking(serial, b, l, 1000);
686 if (ret < 0)
687 return ret;
688 if ((size_t)ret != l)
689 return SR_ERR_IO;
690 state->rsp.fill_pos += l;
691
692 /* Devel support: dump the new receive data. */
693 if (sr_log_loglevel_get() >= SR_LOG_SPEW) {
694 GString *text;
695 const char *req_text;
696
6bee394d 697 req_text = (req == REQ_LIVE_READ_520) ? "LIVE" :
0931639a
GS
698 (req == REQ_REC_HEAD) ? "MEM HEAD" :
699 (req == REQ_REC_NEXT) ? "MEM NEXT" :
700 (req == REQ_REC_CURR) ? "MEM CURR" :
701 "<inv>";
702 text = sr_hexdump_new(b, l);
703 sr_spew("%s: %s", req_text, text->str);
704 sr_hexdump_free(text);
705 }
706
707 /* Verify checksum. No CURR repetition is attempted here. */
708 if (l > 24) {
709 uint16_t calc, rcvd;
710
711 calc = bm52x_rec_checksum(b, 24);
712 rcvd = read_u16le(&b[24]);
713 if (calc != rcvd)
714 return SR_ERR_DATA;
715 state->rsp.fill_pos -= 32 - 24;
716 }
717
718 /* Seed amount of total available data from HEAD response. */
719 if (req == REQ_REC_HEAD) {
720 const uint8_t *rdptr;
721
722 rdptr = &state->rsp.buff[0];
723 (void)read_u8_inc(&rdptr); /* model ID */
724 state->rsp.remain = read_u24le_inc(&rdptr); /* byte count */
725 }
726
727 return SR_OK;
728}
729
730/** Make sure a minimum amount of response data is available. */
731static const uint8_t *bm52x_rec_ensure(struct sr_serial_dev_inst *serial,
732 size_t min_count, struct brymen_bm52x_state *state)
733{
734 size_t got;
735 const uint8_t *read_ptr;
736 int ret;
737
738 got = state->rsp.fill_pos - state->rsp.read_pos;
739 if (got >= min_count) {
740 read_ptr = &state->rsp.buff[state->rsp.read_pos];
741 return read_ptr;
742 }
743 ret = bm52x_rec_next_rsp(serial, REQ_REC_NEXT, state);
744 if (ret < 0)
745 return NULL;
746 read_ptr = &state->rsp.buff[state->rsp.read_pos];
747 return read_ptr;
748}
749
750/** Get a u8 quantity of response data, with auto-fetch and position increment. */
751static uint8_t bm52x_rec_get_u8(struct sr_serial_dev_inst *serial,
752 struct brymen_bm52x_state *state)
753{
754 const uint8_t *read_ptr;
755 uint8_t value;
756 size_t length;
757
758 length = sizeof(value);
759 if (length > state->rsp.remain) {
760 state->rsp.remain = 0;
761 return 0;
762 }
763 read_ptr = bm52x_rec_ensure(serial, length, state);
764 if (!read_ptr)
765 return 0;
766 value = read_u8(read_ptr);
767 state->rsp.read_pos += length;
768 state->rsp.remain -= length;
769 return value;
770}
771
772/** Get a u16 quantity of response data, with auto-fetch and position increment. */
773static uint16_t bm52x_rec_get_u16(struct sr_serial_dev_inst *serial,
774 struct brymen_bm52x_state *state)
775{
776 const uint8_t *read_ptr;
777 uint16_t value;
778 size_t length;
779
780 length = sizeof(value);
781 if (length > state->rsp.remain) {
782 state->rsp.remain = 0;
783 return 0;
784 }
785 read_ptr = bm52x_rec_ensure(serial, length, state);
786 if (!read_ptr)
787 return 0;
788 value = read_u16le(read_ptr);
789 state->rsp.read_pos += length;
790 state->rsp.remain -= length;
791 return value;
792}
793
794/** Get a u24 quantity of response data, with auto-fetch and position increment. */
795static uint32_t bm52x_rec_get_u24(struct sr_serial_dev_inst *serial,
796 struct brymen_bm52x_state *state)
797{
798 const uint8_t *read_ptr;
799 uint32_t value;
800 size_t length;
801
802 length = 24 / sizeof(uint8_t) / 8;
803 if (length > state->rsp.remain) {
804 state->rsp.remain = 0;
805 return 0;
806 }
807 read_ptr = bm52x_rec_ensure(serial, length, state);
808 if (!read_ptr)
809 return 0;
810 value = read_u24le(read_ptr);
811 state->rsp.read_pos += length;
812 state->rsp.remain -= length;
813 return value;
814}
815
816/** Get the HEAD chunk of recording data, determine session page count. */
817static int bm52x_rec_get_count(struct brymen_bm52x_state *state,
818 struct sr_serial_dev_inst *serial)
819{
820 int ret;
821 size_t byte_count, sess_count;
822
823 memset(&state->rsp, 0, sizeof(state->rsp));
824 ret = bm52x_rec_next_rsp(serial, REQ_REC_HEAD, state);
825 if (ret != SR_OK)
826 return ret;
827
828 (void)bm52x_rec_get_u8(serial, state); /* model ID */
829 byte_count = bm52x_rec_get_u24(serial, state); /* total bytes count */
830 sess_count = bm52x_rec_get_u16(serial, state); /* session count */
831 sr_dbg("bytes %zu, sessions %zu", byte_count, sess_count);
832
833 return sess_count;
834}
835
836static double bm52x_rec_get_value(uint32_t raw, const int *ranges, int *digits)
837{
838 uint16_t val_digs;
839 gboolean is_neg, is_ol, low_batt;
840 uint8_t range;
841 double value;
842 int decimals;
843
844 val_digs = raw >> 8;
845 is_neg = raw & (1u << 7);
846 is_ol = raw & (1u << 6);
847 low_batt = raw & (1u << 5);
848 range = raw & 0x0f;
849 sr_dbg("item: %s%u, %s %s, range %01x",
850 is_neg ? "-" : "+", val_digs,
851 is_ol ? "OL" : "ol", low_batt ? "BATT" : "batt",
852 range);
853
854 /* Convert to number. OL takes precedence. */
855 *digits = 0;
856 value = val_digs;
857 if (ranges && ranges[range]) {
858 decimals = ranges[range];
859 value /= pow(10, decimals);
860 *digits = decimals;
861 }
862 if (is_ol)
863 value = INFINITY;
864 if (is_neg)
865 value *= -1;
866
867 /*
868 * Implementor's note: "Low battery" conditions are worth a
869 * warning since the reading could be incorrect. Rate limiting
870 * is not needed since the Brymen DMM will stop recording in
871 * that case, so at most the last sample in the session page
872 * could be affected.
873 */
874 if (low_batt)
875 sr_warn("Recording was taken when battery was low.");
876
877 return value;
878}
879
880static int bm52x_rec_prep_feed(uint8_t bfunc, uint8_t bsel, uint8_t bstat,
881 struct sr_datafeed_analog *analog1, struct sr_datafeed_analog *analog2,
882 double *value1, double *value2, const int **ranges1, const int **ranges2,
883 const struct sr_dev_inst *sdi)
884{
885 struct sr_channel *ch;
886 gboolean is_amp, is_deg_f;
887 enum sr_mq *mq1, *mq2;
888 enum sr_unit *unit1, *unit2;
889 enum sr_mqflag *mqf1, *mqf2;
890 enum sr_unit unit_c_f;
891 const int *r_a_ma;
892
893 /* Prepare general submission on first channel. */
894 analog1->data = value1;
895 analog1->encoding->unitsize = sizeof(*value1);
896 analog1->num_samples = 1;
897 ch = g_slist_nth_data(sdi->channels, 0);
898 analog1->meaning->channels = g_slist_append(NULL, ch);
899 *ranges1 = NULL;
900 mq1 = &analog1->meaning->mq;
901 mqf1 = &analog1->meaning->mqflags;
902 unit1 = &analog1->meaning->unit;
903
904 /* Prepare general submission on second channel. */
905 analog2->data = value2;
906 analog2->encoding->unitsize = sizeof(*value2);
907 analog2->num_samples = 1;
908 ch = g_slist_nth_data(sdi->channels, 1);
909 analog2->meaning->channels = g_slist_append(NULL, ch);
910 *ranges2 = NULL;
911 mq2 = &analog2->meaning->mq;
912 mqf2 = &analog2->meaning->mqflags;
913 unit2 = &analog2->meaning->unit;
914
915 /* Derive main/secondary display functions from bfunc/bsel/bstat. */
916 is_amp = bstat & (1u << 5);
917 is_deg_f = bstat & (1u << 4);
918 switch (bfunc) {
919 case 1: /* AC V */
920 switch (bsel) {
921 case 0: /* AC volt, Hz */
922 *ranges1 = bm52x_ranges_volt;
923 *mq1 = SR_MQ_VOLTAGE;
924 *mqf1 |= SR_MQFLAG_AC;
925 *unit1 = SR_UNIT_VOLT;
926 *ranges2 = bm52x_ranges_freq;
927 *mq2 = SR_MQ_FREQUENCY;
928 *unit2 = SR_UNIT_HERTZ;
929 break;
930 case 1: /* Hz, AC volt */
931 *ranges1 = bm52x_ranges_freq;
932 *mq1 = SR_MQ_FREQUENCY;
933 *unit1 = SR_UNIT_HERTZ;
934 *ranges2 = bm52x_ranges_volt;
935 *mq2 = SR_MQ_VOLTAGE;
936 *mqf2 |= SR_MQFLAG_AC;
937 *unit2 = SR_UNIT_VOLT;
938 break;
939 default:
940 return SR_ERR_DATA;
941 }
942 break;
943 case 2: /* DC V */
944 switch (bsel) {
945 case 0: /* DC V, - */
946 *ranges1 = bm52x_ranges_volt;
947 *mq1 = SR_MQ_VOLTAGE;
948 *mqf1 |= SR_MQFLAG_DC;
949 *unit1 = SR_UNIT_VOLT;
950 break;
951 case 1: /* DC V, AC V */
952 *ranges1 = bm52x_ranges_volt;
953 *mq1 = SR_MQ_VOLTAGE;
954 *mqf1 |= SR_MQFLAG_DC;
955 *unit1 = SR_UNIT_VOLT;
956 *ranges2 = bm52x_ranges_volt;
957 *mq2 = SR_MQ_VOLTAGE;
958 *mqf2 |= SR_MQFLAG_AC;
959 *unit2 = SR_UNIT_VOLT;
960 break;
961 case 2: /* DC+AC V, AC V */
962 *ranges1 = bm52x_ranges_volt;
963 *mq1 = SR_MQ_VOLTAGE;
964 *mqf1 |= SR_MQFLAG_DC;
965 *mqf1 |= SR_MQFLAG_AC;
966 *unit1 = SR_UNIT_VOLT;
967 *ranges2 = bm52x_ranges_volt;
968 *mq2 = SR_MQ_VOLTAGE;
969 *mqf2 |= SR_MQFLAG_AC;
970 *unit2 = SR_UNIT_VOLT;
971 break;
972 default:
973 return SR_ERR_DATA;
974 }
975 break;
976 case 3: /* DC mV */
977 switch (bsel) {
978 case 0: /* DC mV, - */
979 *ranges1 = bm52x_ranges_millivolt;
980 *mq1 = SR_MQ_VOLTAGE;
981 *mqf1 |= SR_MQFLAG_DC;
982 *unit1 = SR_UNIT_VOLT;
983 break;
984 case 1: /* DC mV, AC mV */
985 *ranges1 = bm52x_ranges_millivolt;
986 *mq1 = SR_MQ_VOLTAGE;
987 *mqf1 |= SR_MQFLAG_DC;
988 *unit1 = SR_UNIT_VOLT;
989 *ranges2 = bm52x_ranges_millivolt;
990 *mq2 = SR_MQ_VOLTAGE;
991 *mqf2 |= SR_MQFLAG_AC;
992 *unit2 = SR_UNIT_VOLT;
993 break;
994 case 2: /* DC+AC mV, AC mV */
995 *ranges1 = bm52x_ranges_millivolt;
996 *mq1 = SR_MQ_VOLTAGE;
997 *mqf1 |= SR_MQFLAG_DC;
998 *mqf1 |= SR_MQFLAG_AC;
999 *unit1 = SR_UNIT_VOLT;
1000 *ranges2 = bm52x_ranges_millivolt;
1001 *mq2 = SR_MQ_VOLTAGE;
1002 *mqf2 |= SR_MQFLAG_AC;
1003 *unit2 = SR_UNIT_VOLT;
1004 break;
1005 case 3: /* Hz, - */
1006 *ranges1 = bm52x_ranges_freq;
1007 *mq1 = SR_MQ_FREQUENCY;
1008 *unit1 = SR_UNIT_HERTZ;
1009 break;
1010 case 4: /* %, - */
1011 *ranges1 = bm52x_ranges_duty;
1012 *mq1 = SR_MQ_DUTY_CYCLE;
1013 *unit1 = SR_UNIT_PERCENTAGE;
1014 break;
1015 default:
1016 return SR_ERR_DATA;
1017 }
1018 break;
1019 case 4: /* AC mV */
1020 switch (bsel) {
1021 case 0: /* AC mV, Hz */
1022 *ranges1 = bm52x_ranges_millivolt;
1023 *mq1 = SR_MQ_VOLTAGE;
1024 *mqf1 |= SR_MQFLAG_AC;
1025 *unit1 = SR_UNIT_VOLT;
1026 *ranges2 = bm52x_ranges_freq;
1027 *mq2 = SR_MQ_FREQUENCY;
1028 *unit2 = SR_UNIT_HERTZ;
1029 break;
1030 case 1: /* Hz, AC mV */
1031 *ranges1 = bm52x_ranges_freq;
1032 *mq1 = SR_MQ_FREQUENCY;
1033 *unit1 = SR_UNIT_HERTZ;
1034 *ranges2 = bm52x_ranges_millivolt;
1035 *mq2 = SR_MQ_VOLTAGE;
1036 *mqf2 |= SR_MQFLAG_AC;
1037 *unit2 = SR_UNIT_VOLT;
1038 break;
1039 default:
1040 return SR_ERR_DATA;
1041 }
1042 break;
1043 case 5: /* Res/Cond/Cont */
1044 switch (bsel) {
1045 case 0: /* Resistance */
1046 *ranges1 = bm52x_ranges_ohm;
1047 *mq1 = SR_MQ_RESISTANCE;
1048 *unit1 = SR_UNIT_OHM;
1049 break;
1050 case 1: /* Siemens */
1051 *ranges1 = bm52x_ranges_cond;
1052 *mq1 = SR_MQ_CONDUCTANCE;
1053 *unit1 = SR_UNIT_SIEMENS;
1054 break;
1055 case 2: /* Continuity */
1056 *ranges1 = bm52x_ranges_ohm;
1057 *mq1 = SR_MQ_CONTINUITY;
1058 *unit1 = SR_UNIT_OHM;
1059 break;
1060 default:
1061 return SR_ERR_DATA;
1062 }
1063 break;
1064 case 6: /* Temperature */
1065 unit_c_f = is_deg_f ? SR_UNIT_FAHRENHEIT : SR_UNIT_CELSIUS;
1066 switch (bsel) {
1067 case 0: /* T1, - */
1068 *ranges1 = bm52x_ranges_temp;
1069 *mq1 = SR_MQ_TEMPERATURE;
1070 *unit1 = unit_c_f;
1071 break;
1072 case 1: /* T2, - */
1073 *ranges1 = bm52x_ranges_temp;
1074 *mq1 = SR_MQ_TEMPERATURE;
1075 *unit1 = unit_c_f;
1076 break;
1077 case 2: /* T1, T2 */
1078 *ranges1 = bm52x_ranges_temp;
1079 *mq1 = SR_MQ_TEMPERATURE;
1080 *unit1 = unit_c_f;
1081 *ranges2 = bm52x_ranges_temp;
1082 *mq2 = SR_MQ_TEMPERATURE;
1083 *unit2 = unit_c_f;
1084 break;
1085 case 3: /* T1-T2, T2 */
1086 *ranges1 = bm52x_ranges_temp;
1087 *mq1 = SR_MQ_TEMPERATURE;
1088 *unit1 = unit_c_f;
1089 *ranges2 = bm52x_ranges_temp;
1090 *mq2 = SR_MQ_TEMPERATURE;
1091 *unit2 = unit_c_f;
1092 break;
1093 default:
1094 return SR_ERR_DATA;
1095 }
1096 break;
1097 case 7: /* Cap/Diode */
1098 switch (bsel) {
1099 case 0: /* Capacitance, - */
1100 *ranges1 = bm52x_ranges_cap;
1101 *mq1 = SR_MQ_CAPACITANCE;
1102 *unit1 |= SR_UNIT_FARAD;
1103 break;
1104 case 1: /* Diode voltage, - */
1105 *ranges1 = bm52x_ranges_diode;
1106 *mq1 = SR_MQ_VOLTAGE;
1107 *mqf1 |= SR_MQFLAG_DC;
1108 *mqf1 |= SR_MQFLAG_DIODE;
1109 *unit1 |= SR_UNIT_VOLT;
1110 break;
1111 default:
1112 return SR_ERR_DATA;
1113 }
1114 break;
1115 case 8: /* DC A/mA */
1116 r_a_ma = is_amp ? bm52x_ranges_amp : bm52x_ranges_milliamp;
1117 switch (bsel) {
1118 case 0: /* DC A/mA, - */
1119 *ranges1 = r_a_ma;
1120 *mq1 = SR_MQ_CURRENT;
1121 *mqf1 |= SR_MQFLAG_DC;
1122 *unit1 = SR_UNIT_AMPERE;
1123 break;
1124 case 1: /* DC A/mA, AC A/mA */
1125 *ranges1 = r_a_ma;
1126 *mq1 = SR_MQ_CURRENT;
1127 *mqf1 |= SR_MQFLAG_DC;
1128 *unit1 = SR_UNIT_AMPERE;
1129 *ranges2 = r_a_ma;
1130 *mq2 = SR_MQ_CURRENT;
1131 *mqf2 |= SR_MQFLAG_AC;
1132 *unit2 = SR_UNIT_AMPERE;
1133 break;
1134 case 2: /* DC+AC A/mA, AC A/mA */
1135 *ranges1 = r_a_ma;
1136 *mq1 = SR_MQ_CURRENT;
1137 *mqf1 |= SR_MQFLAG_DC;
1138 *mqf1 |= SR_MQFLAG_AC;
1139 *unit1 = SR_UNIT_AMPERE;
1140 *ranges2 = r_a_ma;
1141 *mq2 = SR_MQ_CURRENT;
1142 *mqf2 |= SR_MQFLAG_AC;
1143 *unit2 = SR_UNIT_AMPERE;
1144 break;
1145 case 3: /* AC A/mA, Hz */
1146 *ranges1 = r_a_ma;
1147 *mq1 = SR_MQ_CURRENT;
1148 *mqf1 |= SR_MQFLAG_AC;
1149 *unit1 = SR_UNIT_AMPERE;
1150 *ranges2 = bm52x_ranges_freq;
1151 *mq2 = SR_MQ_FREQUENCY;
1152 *unit2 = SR_UNIT_HERTZ;
1153 break;
1154 default:
1155 return SR_ERR_DATA;
1156 }
1157 break;
1158 case 9: /* DC uA */
1159 switch (bsel) {
1160 case 0: /* DC uA, - */
1161 *ranges1 = bm52x_ranges_microamp;
1162 *mq1 = SR_MQ_CURRENT;
1163 *mqf1 |= SR_MQFLAG_DC;
1164 *unit1 = SR_UNIT_AMPERE;
1165 break;
1166 case 1: /* DC uA, AC uA */
1167 *ranges1 = bm52x_ranges_microamp;
1168 *mq1 = SR_MQ_CURRENT;
1169 *mqf1 |= SR_MQFLAG_DC;
1170 *unit1 = SR_UNIT_AMPERE;
1171 *ranges2 = bm52x_ranges_microamp;
1172 *mq2 = SR_MQ_CURRENT;
1173 *mqf2 |= SR_MQFLAG_AC;
1174 *unit2 = SR_UNIT_AMPERE;
1175 break;
1176 case 2: /* DC+AC uA, AC uA */
1177 *ranges1 = bm52x_ranges_microamp;
1178 *mq1 = SR_MQ_CURRENT;
1179 *mqf1 |= SR_MQFLAG_DC;
1180 *mqf1 |= SR_MQFLAG_AC;
1181 *unit1 = SR_UNIT_AMPERE;
1182 *ranges2 = bm52x_ranges_microamp;
1183 *mq2 = SR_MQ_CURRENT;
1184 *mqf2 |= SR_MQFLAG_AC;
1185 *unit2 = SR_UNIT_AMPERE;
1186 break;
1187 case 3: /* AC uA, Hz */
1188 *ranges1 = bm52x_ranges_microamp;
1189 *mq1 = SR_MQ_CURRENT;
1190 *mqf1 |= SR_MQFLAG_AC;
1191 *unit1 = SR_UNIT_AMPERE;
1192 *ranges2 = bm52x_ranges_freq;
1193 *mq2 = SR_MQ_FREQUENCY;
1194 *unit2 = SR_UNIT_HERTZ;
1195 break;
1196 default:
1197 return SR_ERR_DATA;
1198 }
1199 break;
1200 default:
1201 return SR_ERR_DATA;
1202 }
1203
1204 return SR_OK;
1205}
1206
1207/** Traverse one recorded session page, optionally feed session bus. */
1208static int bm52x_rec_read_page_int(const struct sr_dev_inst *sdi,
1209 struct brymen_bm52x_state *state, struct sr_serial_dev_inst *serial,
1210 gboolean skip)
1211{
1212 uint8_t bfunc, bsel, bstat;
1213 uint8_t ival;
1214 gboolean has_sec_disp;
1215 size_t page_len, meas_len, meas_count;
1216 uint32_t meas_data;
1217 struct sr_datafeed_packet packet;
1218 struct sr_datafeed_analog analog1, analog2;
1219 struct sr_analog_encoding encoding1, encoding2;
1220 struct sr_analog_meaning meaning1, meaning2;
1221 struct sr_analog_spec spec1, spec2;
1222 int digits, ret;
1223 double values[2];
1224 const int *ranges1, *ranges2;
1225 enum sr_configkey key;
1226 uint64_t num;
1227
1228 sr_dbg("progress: %s, %s", __func__, skip ? "skip" : "feed");
1229
1230 /* Get the header information of the session page (raw). */
1231 if (bm52x_rec_get_u8(serial, state) != 0xee) /* "DLE" */
1232 return SR_ERR_DATA;
1233 if (bm52x_rec_get_u8(serial, state) != 0xa0) /* "STX" */
1234 return SR_ERR_DATA;
1235 (void)bm52x_rec_get_u24(serial, state); /* prev page addr */
1236 (void)bm52x_rec_get_u24(serial, state); /* next page addr */
1237 bfunc = bm52x_rec_get_u8(serial, state); /* meter function */
1238 bsel = bm52x_rec_get_u8(serial, state); /* fun selection */
1239 bstat = bm52x_rec_get_u8(serial, state); /* status */
1240 page_len = bm52x_rec_get_u24(serial, state); /* page length */
1241 sr_dbg("page head: func/sel/state %02x/%02x/%02x, len %zu",
1242 bfunc, bsel, bstat, page_len);
1243
1244 /* Interpret the header information of the session page. */
1245 ival = bstat & 0x0f;
1246 has_sec_disp = bstat & (1u << 7);
1247 meas_len = (has_sec_disp ? 2 : 1) * 3;
1248 if (page_len % meas_len)
1249 return SR_ERR_DATA;
1250 meas_count = page_len / meas_len;
1251 sr_dbg("page head: ival %u, %s, samples %zu",
1252 ival, has_sec_disp ? "dual" : "main", meas_count);
1253
1254 /* Prepare feed to the sigrok session. Send rate/interval. */
1255 sr_analog_init(&analog1, &encoding1, &meaning1, &spec1, 0);
1256 sr_analog_init(&analog2, &encoding2, &meaning2, &spec2, 0);
1257 ret = bm52x_rec_prep_feed(bfunc, bsel, bstat,
1258 &analog1, &analog2, &values[0], &values[1],
1259 &ranges1, &ranges2, sdi);
1260 if (ret != SR_OK)
1261 return SR_ERR_DATA;
1262 if (!skip) {
1263 memset(&packet, 0, sizeof(packet));
1264 packet.type = SR_DF_ANALOG;
1265
1266 if (bm52x_rec_ivals[ival].freq_rate) {
1267 sr_dbg("rate: %u", bm52x_rec_ivals[ival].freq_rate);
1268 key = SR_CONF_SAMPLERATE;
1269 num = bm52x_rec_ivals[ival].freq_rate;
1270 (void)sr_session_send_meta(sdi,
1271 key, g_variant_new_uint64(num));
1272 }
1273 if (bm52x_rec_ivals[ival].ival_secs) {
1274 sr_dbg("ival: %u", bm52x_rec_ivals[ival].ival_secs);
1275 key = SR_CONF_SAMPLE_INTERVAL;
1276 num = bm52x_rec_ivals[ival].ival_secs * 1000; /* in ms */
1277 (void)sr_session_send_meta(sdi,
1278 key, g_variant_new_uint64(num));
1279 }
1280 }
1281
1282 /*
1283 * Implementor's note:
1284 * Software limits require devc access, which is an internal
1285 * detail of the serial-dmm driver, which this bm52x parser
1286 * is not aware of. So we always provide the complete set of
1287 * recorded samples. Should be acceptable. Duplicating limit
1288 * support in local config get/set is considered undesirable.
1289 */
1290 while (meas_count--) {
1291 meas_data = bm52x_rec_get_u24(serial, state);
1292 values[0] = bm52x_rec_get_value(meas_data, ranges1, &digits);
1293 if (!skip) {
1294 analog1.encoding->digits = digits;
1295 analog1.spec->spec_digits = digits;
1296 packet.payload = &analog1;
1297 ret = sr_session_send(sdi, &packet);
1298 if (ret != SR_OK)
1299 return ret;
1300 }
1301
1302 if (!has_sec_disp)
1303 continue;
1304 meas_data = bm52x_rec_get_u24(serial, state);
1305 values[1] = bm52x_rec_get_value(meas_data, ranges2, &digits);
1306 if (!skip) {
1307 analog2.encoding->digits = digits;
1308 analog2.spec->spec_digits = digits;
1309 packet.payload = &analog2;
1310 ret = sr_session_send(sdi, &packet);
1311 if (ret != SR_OK)
1312 return ret;
1313 }
1314 }
1315
1316 /* Check termination of the session page. */
1317 if (bm52x_rec_get_u8(serial, state) != 0xee) /* "DLE" */
1318 return SR_ERR_DATA;
1319 if (bm52x_rec_get_u8(serial, state) != 0xc0) /* "ETX" */
1320 return SR_ERR_DATA;
1321
1322 return SR_OK;
1323}
1324
1325/** Skip one recorded session page. */
1326static int bm52x_rec_skip_page(const struct sr_dev_inst *sdi,
1327 struct brymen_bm52x_state *state, struct sr_serial_dev_inst *serial)
1328{
1329 return bm52x_rec_read_page_int(sdi, state, serial, TRUE);
1330}
1331
1332/** Forward one recorded session page. */
1333static int bm52x_rec_read_page(const struct sr_dev_inst *sdi,
1334 struct brymen_bm52x_state *state, struct sr_serial_dev_inst *serial)
1335{
1336 return bm52x_rec_read_page_int(sdi, state, serial, FALSE);
1337}
1338
1339SR_PRIV void *brymen_bm52x_state_init(void)
1340{
1341 return g_malloc0(sizeof(struct brymen_bm52x_state));
1342}
1343
1344SR_PRIV void brymen_bm52x_state_free(void *state)
1345{
1346 g_free(state);
1347}
1348
1349SR_PRIV int brymen_bm52x_config_get(void *st, uint32_t key, GVariant **data,
1350 const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
1351{
1352 struct brymen_bm52x_state *state;
1353 char text[20];
1354
1355 state = st;
1356
1357 if (!sdi)
1358 return SR_ERR_NA;
1359 (void)cg;
1360
1361 switch (key) {
1362 case SR_CONF_DATA_SOURCE:
1363 if (!state)
1364 return SR_ERR_ARG;
1365 if (state->sess_idx == 0)
1366 snprintf(text, sizeof(text), "Live");
1367 else
1368 snprintf(text, sizeof(text), "Rec-%zu", state->sess_idx);
1369 *data = g_variant_new_string(text);
1370 return SR_OK;
1371 default:
1372 return SR_ERR_NA;
1373 }
1374}
1375
1376SR_PRIV int brymen_bm52x_config_set(void *st, uint32_t key, GVariant *data,
1377 const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
1378{
1379 struct brymen_bm52x_state *state;
1380 const char *s;
1381 int ret, nr;
1382
1383 state = st;
1384
1385 if (!sdi)
1386 return SR_ERR_NA;
1387 (void)cg;
1388
1389 switch (key) {
1390 case SR_CONF_DATA_SOURCE:
1391 s = g_variant_get_string(data, NULL);
1392 if (!s || !*s)
1393 return SR_ERR_ARG;
1394 if (strcasecmp(s, "Live") == 0) {
1395 state->sess_idx = 0;
1396 return SR_OK;
1397 }
1398 if (strncasecmp(s, "Rec-", strlen("Rec-")) != 0)
1399 return SR_ERR_ARG;
1400 s += strlen("Rec-");
1401 ret = sr_atoi(s, &nr);
1402 if (ret != SR_OK || nr <= 0 || nr > 999)
1403 return SR_ERR_ARG;
1404 state->sess_idx = nr;
1405 return SR_OK;
1406 default:
1407 return SR_ERR_NA;
1408 }
1409}
1410
1411SR_PRIV int brymen_bm52x_config_list(void *st, uint32_t key, GVariant **data,
1412 const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
1413{
1414 struct brymen_bm52x_state *state;
1415 struct sr_serial_dev_inst *serial;
1416 int ret;
1417 size_t count, idx;
1418 GVariantBuilder gvb;
1419 char name[20];
1420
1421 /*
1422 * Have common keys handled by caller's common code.
1423 * ERR N/A results in the caller's logic handling the request.
1424 * Only handle strictly local properties here in this code path.
1425 */
1426 switch (key) {
1427 case SR_CONF_SCAN_OPTIONS:
1428 /* Scan options. Common property. */
1429 return SR_ERR_NA;
1430 case SR_CONF_DEVICE_OPTIONS:
1431 if (!sdi)
1432 /* Driver options. Common property. */
1433 return SR_ERR_NA;
1434 if (cg)
1435 /* Channel group's devopts. Common error path. */
1436 return SR_ERR_NA;
1437 /* List meter's local device options. Overrides common data. */
1438 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
1439 devopts, ARRAY_SIZE(devopts), sizeof(uint32_t));
1440 return SR_OK;
1441 case SR_CONF_DATA_SOURCE:
1442 state = st;
1443 if (!sdi)
1444 return SR_ERR_ARG;
1445 serial = sdi->conn;
1446 ret = bm52x_rec_get_count(state, serial);
1447 if (ret < 0)
1448 return ret;
1449 count = ret;
1450 g_variant_builder_init(&gvb, G_VARIANT_TYPE_ARRAY);
1451 for (idx = 0; idx <= count; idx++) {
1452 if (idx == 0)
1453 snprintf(name, sizeof(name), "Live");
1454 else
1455 snprintf(name, sizeof(name), "Rec-%zu", idx);
1456 g_variant_builder_add(&gvb, "s", name);
1457 }
1458 *data = g_variant_builder_end(&gvb);
1459 return SR_OK;
1460 default:
1461 return SR_ERR_NA;
1462 }
1463}
1464
1465/**
1466 * BM520s specific receive routine for recorded measurements.
1467 *
1468 * @param[in] fd File descriptor.
1469 * @param[in] revents Mask of pending events.
1470 * @param[in] cb_data Call back data (receive handler state).
1471 *
1472 * @return TRUE when the routine needs to get re-invoked, FALSE when the
1473 * routine is done and no further invocations are required.
1474 *
1475 * @private
1476 *
1477 * It's an implementation detail that a single invocation will carry out
1478 * all the work that is involved in reading back recorded measurements.
1479 */
1480static int bm52x_rec_receive_data(int fd, int revents, void *cb_data)
1481{
1482 struct brymen_bm52x_state *state;
1483 const struct sr_dev_inst *sdi;
1484 struct sr_dev_inst *sdi_rw;
1485 struct sr_serial_dev_inst *serial;
1486 int ret;
1487 size_t count, idx;
1488
1489 (void)fd;
1490 (void)revents;
1491 state = cb_data;
1492
1493 sdi = state->sdi;
1494 serial = sdi->conn;
1495
1496 ret = bm52x_rec_get_count(state, serial);
1497 if (ret < 0)
1498 return FALSE;
1499 count = ret;
1500
1501 /* Un-const 'sdi' since sr_dev_acquisition_stop() needs that. */
1502 sdi_rw = (struct sr_dev_inst *)sdi;
1503
1504 /*
1505 * Immediate (silent, zero data) stop for non-existent sessions.
1506 * Early exit is an arbitrary implementation detail, in theory
1507 * the loop below would transparently handle the situation when
1508 * users request non-existing session pages.
1509 */
1510 if (state->sess_idx > count) {
1511 sr_dev_acquisition_stop(sdi_rw);
1512 return FALSE;
1513 }
1514
1515 /* Iterate all session pages, forward the one of interest. */
1516 for (idx = 1; idx <= count; idx++) {
1517 if (idx == state->sess_idx)
1518 ret = bm52x_rec_read_page(sdi, state, serial);
1519 else
1520 ret = bm52x_rec_skip_page(sdi, state, serial);
1521 if (ret != SR_OK)
1522 break;
1523 }
1524
1525 sr_dev_acquisition_stop(sdi_rw);
1526 return FALSE;
1527}
1528
1529/**
1530 * BM520s specific acquisition start callback.
1531 *
1532 * @param[in] st DMM parser state.
1533 * @param[in] sdi Device instance.
1534 * @param[out] cb Receive callback for the acquisition.
1535 * @param[out] cb_data Callback data for receive callback.
1536 *
1537 * @returns SR_OK upon success.
1538 * @returns SR_ERR* upon failure.
1539 *
1540 * @private
1541 *
1542 * The BM520s protocol parser uses common logic and the packet parser
1543 * for live acquisition, but runs a different set of requests and a
1544 * different response layout interpretation for recorded measurements.
1545 */
1546SR_PRIV int brymen_bm52x_acquire_start(void *st, const struct sr_dev_inst *sdi,
1547 sr_receive_data_callback *cb, void **cb_data)
1548{
1549 struct brymen_bm52x_state *state;
1550
1551 if (!sdi || !st)
1552 return SR_ERR_ARG;
1553 state = st;
1554
1555 /* Read live measurements. No local override required. */
1556 if (state->sess_idx == 0)
1557 return SR_OK;
1558
1559 /* Arrange to read back recorded session. */
1560 sr_dbg("session page requested: %zu", state->sess_idx);
1561 state->sdi = sdi;
1562 *cb = bm52x_rec_receive_data;
1563 *cb_data = state;
1564 return SR_OK;
1565}