2 * This file is part of the libsigrok project.
4 * Copyright (C) 2014 Janne Huttunen <jahuttun@gmail.com>
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 #include <libsigrok/libsigrok.h>
26 #include "libsigrok-internal.h"
28 #define LOG_PREFIX "es51919"
31 /** Total size of the buffer. */
33 /** Amount of data currently in the buffer. */
35 /** Offset where the data starts in the buffer. */
37 /** Space for the data. */
41 static struct dev_buffer *dev_buffer_new(size_t size)
43 struct dev_buffer *dbuf;
45 dbuf = g_malloc0(sizeof(struct dev_buffer) + size);
53 static void dev_buffer_destroy(struct dev_buffer *dbuf)
58 static int dev_buffer_fill_serial(struct dev_buffer *dbuf,
59 struct sr_dev_inst *sdi)
61 struct sr_serial_dev_inst *serial;
66 /* If we already have data, move it to the beginning of the buffer. */
67 if (dbuf->len > 0 && dbuf->offset > 0)
68 memmove(dbuf->data, dbuf->data + dbuf->offset, dbuf->len);
72 len = dbuf->size - dbuf->len;
73 len = serial_read_nonblocking(serial, dbuf->data + dbuf->len, len);
75 sr_err("Serial port read error: %d.", len);
84 static uint8_t *dev_buffer_packet_find(struct dev_buffer *dbuf,
85 gboolean (*packet_valid)(const uint8_t *),
90 while (dbuf->len >= packet_size) {
91 if (packet_valid(dbuf->data + dbuf->offset)) {
92 offset = dbuf->offset;
93 dbuf->offset += packet_size;
94 dbuf->len -= packet_size;
95 return dbuf->data + offset;
104 struct dev_limit_counter {
105 /** The current number of received samples/frames/etc. */
107 /** The limit (in number of samples/frames/etc.). */
111 static void dev_limit_counter_start(struct dev_limit_counter *cnt)
116 static void dev_limit_counter_inc(struct dev_limit_counter *cnt)
121 static void dev_limit_counter_limit_set(struct dev_limit_counter *cnt,
127 static gboolean dev_limit_counter_limit_reached(struct dev_limit_counter *cnt)
129 if (cnt->limit && cnt->count >= cnt->limit) {
130 sr_info("Requested counter limit reached.");
137 struct dev_time_counter {
138 /** The starting time of current sampling run. */
140 /** The time limit (in milliseconds). */
144 static void dev_time_counter_start(struct dev_time_counter *cnt)
146 cnt->starttime = g_get_monotonic_time();
149 static void dev_time_limit_set(struct dev_time_counter *cnt, uint64_t limit)
154 static gboolean dev_time_limit_reached(struct dev_time_counter *cnt)
159 time = (g_get_monotonic_time() - cnt->starttime) / 1000;
160 if (time > (int64_t)cnt->limit) {
161 sr_info("Requested time limit reached.");
169 static void serial_conf_get(GSList *options, const char *def_serialcomm,
170 const char **conn, const char **serialcomm)
172 struct sr_config *src;
175 *conn = *serialcomm = NULL;
176 for (l = options; l; l = l->next) {
180 *conn = g_variant_get_string(src->data, NULL);
182 case SR_CONF_SERIALCOMM:
183 *serialcomm = g_variant_get_string(src->data, NULL);
188 if (*serialcomm == NULL)
189 *serialcomm = def_serialcomm;
192 static struct sr_serial_dev_inst *serial_dev_new(GSList *options,
193 const char *def_serialcomm)
196 const char *conn, *serialcomm;
198 serial_conf_get(options, def_serialcomm, &conn, &serialcomm);
203 return sr_serial_dev_inst_new(conn, serialcomm);
206 static int serial_stream_check_buf(struct sr_serial_dev_inst *serial,
207 uint8_t *buf, size_t buflen,
209 packet_valid_callback is_valid,
210 uint64_t timeout_ms, int baudrate)
215 if ((ret = serial_open(serial, SERIAL_RDWR)) != SR_OK)
218 serial_flush(serial);
221 ret = serial_stream_detect(serial, buf, &len, packet_size,
222 is_valid, timeout_ms, baudrate);
224 serial_close(serial);
230 * If we dropped more than two packets worth of data, something is
231 * wrong. We shouldn't quit however, since the dropped bytes might be
232 * just zeroes at the beginning of the stream. Those can occur as a
233 * combination of the nonstandard cable that ships with some devices
234 * and the serial port or USB to serial adapter.
236 dropped = len - packet_size;
237 if (dropped > 2 * packet_size)
238 sr_warn("Had to drop too much data.");
243 static int serial_stream_check(struct sr_serial_dev_inst *serial,
245 packet_valid_callback is_valid,
246 uint64_t timeout_ms, int baudrate)
250 return serial_stream_check_buf(serial, buf, sizeof(buf), packet_size,
251 is_valid, timeout_ms, baudrate);
254 struct std_opt_desc {
255 const uint32_t *scanopts;
256 const int num_scanopts;
257 const uint32_t *devopts;
258 const int num_devopts;
261 static int std_config_list(uint32_t key, GVariant **data,
262 const struct std_opt_desc *d)
265 case SR_CONF_SCAN_OPTIONS:
266 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
267 d->scanopts, d->num_scanopts, sizeof(uint32_t));
269 case SR_CONF_DEVICE_OPTIONS:
270 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
271 d->devopts, d->num_devopts, sizeof(uint32_t));
280 static int send_config_update(struct sr_dev_inst *sdi, struct sr_config *cfg)
282 struct sr_datafeed_packet packet;
283 struct sr_datafeed_meta meta;
285 memset(&meta, 0, sizeof(meta));
287 packet.type = SR_DF_META;
288 packet.payload = &meta;
290 meta.config = g_slist_append(meta.config, cfg);
292 return sr_session_send(sdi, &packet);
295 static int send_config_update_key(struct sr_dev_inst *sdi, uint32_t key,
298 struct sr_config *cfg;
301 cfg = sr_config_new(key, var);
305 ret = send_config_update(sdi, cfg);
312 * Cyrustek ES51919 LCR chipset host protocol.
314 * Public official documentation does not contain the protocol
315 * description, so this is all based on reverse engineering.
317 * Packet structure (17 bytes):
319 * 0x00: header1 ?? (0x00)
320 * 0x01: header2 ?? (0x0d)
323 * bit 0 = hold enabled
324 * bit 1 = reference shown (in delta mode)
326 * bit 3 = calibration mode
327 * bit 4 = sorting mode
330 * bit 7 = parallel measurement (vs. serial)
333 * bit 0-4 = ??? (0x10)
334 * bit 5-7 = test frequency
342 * 0x04: tolerance (sorting mode)
353 * 0x05-0x09: primary measurement
354 * 0x05: measured quantity
359 * 0x06: measurement MSB (0x4e20 = 20000 = outside limits)
360 * 0x07: measurement LSB
361 * 0x08: measurement info
362 * bit 0-2 = decimal point multiplier (10^-val)
378 * 0x09: measurement status
380 * 0 = normal (measurement shown)
381 * 1 = blank (nothing shown)
383 * 3 = outside limits ("OL")
387 * 10 = shorted ("Srt")
388 * bit 4-6 = ??? (maybe part of same field with 0-3)
389 * bit 7 = ??? (some independent flag)
391 * 0x0a-0x0e: secondary measurement
392 * 0x0a: measured quantity
394 * 1 = dissipation factor
396 * 3 = parallel AC resistance / ESR
398 * 0x0b-0x0e: like primary measurement
400 * 0x0f: footer1 (0x0d) ?
401 * 0x10: footer2 (0x0a) ?
404 #define PACKET_SIZE 17
406 static const double frequencies[] = {
407 100, 120, 1000, 10000, 100000, 0,
410 enum { MODEL_NONE, MODEL_PAR, MODEL_SER, MODEL_AUTO, };
412 static const char *const models[] = {
413 "NONE", "PARALLEL", "SERIES", "AUTO",
416 /** Private, per-device-instance driver context. */
418 /** The number of frames. */
419 struct dev_limit_counter frame_count;
421 /** The time limit counter. */
422 struct dev_time_counter time_count;
425 struct dev_buffer *buf;
427 /** The frequency of the test signal (index to frequencies[]). */
430 /** Equivalent circuit model (index to models[]). */
434 static const uint8_t *pkt_to_buf(const uint8_t *pkt, int is_secondary)
436 return is_secondary ? pkt + 10 : pkt + 5;
439 static int parse_mq(const uint8_t *pkt, int is_secondary, int is_parallel)
443 buf = pkt_to_buf(pkt, is_secondary);
445 switch (is_secondary << 8 | buf[0]) {
448 SR_MQ_PARALLEL_INDUCTANCE : SR_MQ_SERIES_INDUCTANCE;
451 SR_MQ_PARALLEL_CAPACITANCE : SR_MQ_SERIES_CAPACITANCE;
455 SR_MQ_PARALLEL_RESISTANCE : SR_MQ_SERIES_RESISTANCE;
457 return SR_MQ_RESISTANCE;
459 return SR_MQ_DIFFERENCE;
461 return SR_MQ_DISSIPATION_FACTOR;
463 return SR_MQ_QUALITY_FACTOR;
465 return SR_MQ_PHASE_ANGLE;
468 sr_err("Unknown quantity 0x%03x.", is_secondary << 8 | buf[0]);
473 static float parse_value(const uint8_t *buf, int *digits)
475 static const int exponents[] = {0, -1, -2, -3, -4, -5, -6, -7};
479 exponent = exponents[buf[3] & 7];
481 val = (buf[1] << 8) | buf[2];
482 return (float)val * powf(10, exponent);
485 static void parse_measurement(const uint8_t *pkt, float *floatval,
486 struct sr_datafeed_analog *analog,
489 static const struct {
493 { SR_UNIT_UNITLESS, 0 }, /* no unit */
494 { SR_UNIT_OHM, 0 }, /* Ohm */
495 { SR_UNIT_OHM, 3 }, /* kOhm */
496 { SR_UNIT_OHM, 6 }, /* MOhm */
498 { SR_UNIT_HENRY, -6 }, /* uH */
499 { SR_UNIT_HENRY, -3 }, /* mH */
500 { SR_UNIT_HENRY, 0 }, /* H */
501 { SR_UNIT_HENRY, 3 }, /* kH */
502 { SR_UNIT_FARAD, -12 }, /* pF */
503 { SR_UNIT_FARAD, -9 }, /* nF */
504 { SR_UNIT_FARAD, -6 }, /* uF */
505 { SR_UNIT_FARAD, -3 }, /* mF */
506 { SR_UNIT_PERCENTAGE, 0 }, /* % */
507 { SR_UNIT_DEGREE, 0 }, /* degree */
510 int digits, exponent;
513 buf = pkt_to_buf(pkt, is_secondary);
515 analog->meaning->mq = 0;
516 analog->meaning->mqflags = 0;
518 state = buf[4] & 0xf;
520 if (state != 0 && state != 3)
524 /* Calibration and Sorting modes not supported. */
530 analog->meaning->mqflags |= SR_MQFLAG_HOLD;
532 analog->meaning->mqflags |= SR_MQFLAG_REFERENCE;
535 analog->meaning->mqflags |= SR_MQFLAG_RELATIVE;
538 if ((analog->meaning->mq = parse_mq(pkt, is_secondary, pkt[2] & 0x80)) < 0)
541 if ((buf[3] >> 3) >= ARRAY_SIZE(units)) {
542 sr_err("Unknown unit %u.", buf[3] >> 3);
543 analog->meaning->mq = 0;
547 analog->meaning->unit = units[buf[3] >> 3].unit;
549 exponent = units[buf[3] >> 3].exponent;
550 *floatval = parse_value(buf, &digits);
551 *floatval *= (state == 0) ? powf(10, exponent) : INFINITY;
552 analog->encoding->digits = digits - exponent;
553 analog->spec->spec_digits = digits - exponent;
556 static unsigned int parse_freq(const uint8_t *pkt)
562 if (freq >= ARRAY_SIZE(frequencies)) {
563 sr_err("Unknown frequency %u.", freq);
564 freq = ARRAY_SIZE(frequencies) - 1;
570 static unsigned int parse_model(const uint8_t *pkt)
574 else if (parse_mq(pkt, 0, 0) == SR_MQ_RESISTANCE)
576 else if (pkt[2] & 0x80)
582 static gboolean packet_valid(const uint8_t *pkt)
585 * If the first two bytes of the packet are indeed a constant
586 * header, they should be checked too. Since we don't know it
587 * for sure, we'll just check the last two for now since they
588 * seem to be constant just like in the other Cyrustek chipset
591 if (pkt[15] == 0xd && pkt[16] == 0xa)
597 static int do_config_update(struct sr_dev_inst *sdi, uint32_t key,
600 return send_config_update_key(sdi, key, var);
603 static int send_freq_update(struct sr_dev_inst *sdi, unsigned int freq)
605 return do_config_update(sdi, SR_CONF_OUTPUT_FREQUENCY,
606 g_variant_new_double(frequencies[freq]));
609 static int send_model_update(struct sr_dev_inst *sdi, unsigned int model)
611 return do_config_update(sdi, SR_CONF_EQUIV_CIRCUIT_MODEL,
612 g_variant_new_string(models[model]));
615 static void handle_packet(struct sr_dev_inst *sdi, const uint8_t *pkt)
617 struct sr_datafeed_packet packet;
618 struct sr_datafeed_analog analog;
619 struct sr_analog_encoding encoding;
620 struct sr_analog_meaning meaning;
621 struct sr_analog_spec spec;
622 struct dev_context *devc;
629 val = parse_freq(pkt);
630 if (val != devc->freq) {
631 if (send_freq_update(sdi, val) == SR_OK)
637 val = parse_model(pkt);
638 if (val != devc->model) {
639 if (send_model_update(sdi, val) == SR_OK)
647 /* Note: digits/spec_digits will be overridden later. */
648 sr_analog_init(&analog, &encoding, &meaning, &spec, 0);
650 analog.num_samples = 1;
651 analog.data = &floatval;
653 analog.meaning->channels = g_slist_append(NULL, sdi->channels->data);
655 parse_measurement(pkt, &floatval, &analog, 0);
656 if (analog.meaning->mq != 0) {
658 packet.type = SR_DF_FRAME_BEGIN;
659 sr_session_send(sdi, &packet);
663 packet.type = SR_DF_ANALOG;
664 packet.payload = &analog;
666 sr_session_send(sdi, &packet);
669 g_slist_free(analog.meaning->channels);
670 analog.meaning->channels = g_slist_append(NULL, sdi->channels->next->data);
672 parse_measurement(pkt, &floatval, &analog, 1);
673 if (analog.meaning->mq != 0) {
675 packet.type = SR_DF_FRAME_BEGIN;
676 sr_session_send(sdi, &packet);
680 packet.type = SR_DF_ANALOG;
681 packet.payload = &analog;
683 sr_session_send(sdi, &packet);
686 g_slist_free(analog.meaning->channels);
689 packet.type = SR_DF_FRAME_END;
690 sr_session_send(sdi, &packet);
691 dev_limit_counter_inc(&devc->frame_count);
695 static int handle_new_data(struct sr_dev_inst *sdi)
697 struct dev_context *devc;
703 ret = dev_buffer_fill_serial(devc->buf, sdi);
707 while ((pkt = dev_buffer_packet_find(devc->buf, packet_valid,
709 handle_packet(sdi, pkt);
714 static int receive_data(int fd, int revents, void *cb_data)
716 struct sr_dev_inst *sdi;
717 struct dev_context *devc;
721 if (!(sdi = cb_data))
724 if (!(devc = sdi->priv))
727 if (revents == G_IO_IN) {
728 /* Serial data arrived. */
729 handle_new_data(sdi);
732 if (dev_limit_counter_limit_reached(&devc->frame_count) ||
733 dev_time_limit_reached(&devc->time_count))
734 sdi->driver->dev_acquisition_stop(sdi);
739 static const char *const channel_names[] = { "P1", "P2" };
741 static int setup_channels(struct sr_dev_inst *sdi)
748 for (i = 0; i < ARRAY_SIZE(channel_names); i++)
749 sr_channel_new(sdi, i, SR_CHANNEL_ANALOG, TRUE, channel_names[i]);
754 SR_PRIV void es51919_serial_clean(void *priv)
756 struct dev_context *devc;
761 dev_buffer_destroy(devc->buf);
765 SR_PRIV struct sr_dev_inst *es51919_serial_scan(GSList *options,
769 struct sr_serial_dev_inst *serial;
770 struct sr_dev_inst *sdi;
771 struct dev_context *devc;
778 if (!(serial = serial_dev_new(options, "9600/8n1/rts=1/dtr=1")))
781 ret = serial_stream_check(serial, PACKET_SIZE, packet_valid,
786 sr_info("Found device on port %s.", serial->port);
788 sdi = g_malloc0(sizeof(struct sr_dev_inst));
789 sdi->status = SR_ST_INACTIVE;
790 sdi->vendor = g_strdup(vendor);
791 sdi->model = g_strdup(model);
792 devc = g_malloc0(sizeof(struct dev_context));
793 devc->buf = dev_buffer_new(PACKET_SIZE * 8);
794 sdi->inst_type = SR_INST_SERIAL;
798 if (setup_channels(sdi) != SR_OK)
804 es51919_serial_clean(devc);
806 sr_dev_inst_free(sdi);
808 sr_serial_dev_inst_free(serial);
813 SR_PRIV int es51919_serial_config_get(uint32_t key, GVariant **data,
814 const struct sr_dev_inst *sdi,
815 const struct sr_channel_group *cg)
817 struct dev_context *devc;
824 case SR_CONF_OUTPUT_FREQUENCY:
825 *data = g_variant_new_double(frequencies[devc->freq]);
827 case SR_CONF_EQUIV_CIRCUIT_MODEL:
828 *data = g_variant_new_string(models[devc->model]);
837 SR_PRIV int es51919_serial_config_set(uint32_t key, GVariant *data,
838 const struct sr_dev_inst *sdi,
839 const struct sr_channel_group *cg)
841 struct dev_context *devc;
846 if (!(devc = sdi->priv))
850 case SR_CONF_LIMIT_MSEC:
851 val = g_variant_get_uint64(data);
852 dev_time_limit_set(&devc->time_count, val);
853 sr_dbg("Setting time limit to %" PRIu64 ".", val);
855 case SR_CONF_LIMIT_FRAMES:
856 val = g_variant_get_uint64(data);
857 dev_limit_counter_limit_set(&devc->frame_count, val);
858 sr_dbg("Setting frame limit to %" PRIu64 ".", val);
861 sr_spew("%s: Unsupported key %u", __func__, key);
868 static const uint32_t scanopts[] = {
873 static const uint32_t devopts[] = {
876 SR_CONF_LIMIT_FRAMES | SR_CONF_SET,
877 SR_CONF_LIMIT_MSEC | SR_CONF_SET,
878 SR_CONF_OUTPUT_FREQUENCY | SR_CONF_GET | SR_CONF_LIST,
879 SR_CONF_EQUIV_CIRCUIT_MODEL | SR_CONF_GET | SR_CONF_LIST,
882 static const struct std_opt_desc opts = {
883 scanopts, ARRAY_SIZE(scanopts),
884 devopts, ARRAY_SIZE(devopts),
887 SR_PRIV int es51919_serial_config_list(uint32_t key, GVariant **data,
888 const struct sr_dev_inst *sdi,
889 const struct sr_channel_group *cg)
894 if (std_config_list(key, data, &opts) == SR_OK)
898 case SR_CONF_OUTPUT_FREQUENCY:
899 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_DOUBLE,
900 frequencies, ARRAY_SIZE(frequencies), sizeof(double));
902 case SR_CONF_EQUIV_CIRCUIT_MODEL:
903 *data = g_variant_new_strv(models, ARRAY_SIZE(models));
912 SR_PRIV int es51919_serial_acquisition_start(const struct sr_dev_inst *sdi)
914 struct dev_context *devc;
915 struct sr_serial_dev_inst *serial;
917 if (sdi->status != SR_ST_ACTIVE)
918 return SR_ERR_DEV_CLOSED;
920 if (!(devc = sdi->priv))
923 dev_limit_counter_start(&devc->frame_count);
924 dev_time_counter_start(&devc->time_count);
926 std_session_send_df_header(sdi);
928 /* Poll every 50ms, or whenever some data comes in. */
930 serial_source_add(sdi->session, serial, G_IO_IN, 50,
931 receive_data, (void *)sdi);