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/>.
24 #include <libsigrok/libsigrok.h>
25 #include "libsigrok-internal.h"
27 #define LOG_PREFIX "es51919"
30 /** Total size of the buffer. */
32 /** Amount of data currently in the buffer. */
34 /** Offset where the data starts in the buffer. */
36 /** Space for the data. */
40 static struct dev_buffer *dev_buffer_new(size_t size)
42 struct dev_buffer *dbuf;
44 dbuf = g_malloc0(sizeof(struct dev_buffer) + size);
52 static void dev_buffer_destroy(struct dev_buffer *dbuf)
57 static int dev_buffer_fill_serial(struct dev_buffer *dbuf,
58 struct sr_dev_inst *sdi)
60 struct sr_serial_dev_inst *serial;
65 /* If we already have data, move it to the beginning of the buffer. */
66 if (dbuf->len > 0 && dbuf->offset > 0)
67 memmove(dbuf->data, dbuf->data + dbuf->offset, dbuf->len);
71 len = dbuf->size - dbuf->len;
72 len = serial_read_nonblocking(serial, dbuf->data + dbuf->len, len);
74 sr_err("Serial port read error: %d.", len);
83 static uint8_t *dev_buffer_packet_find(struct dev_buffer *dbuf,
84 gboolean (*packet_valid)(const uint8_t *),
89 while (dbuf->len >= packet_size) {
90 if (packet_valid(dbuf->data + dbuf->offset)) {
91 offset = dbuf->offset;
92 dbuf->offset += packet_size;
93 dbuf->len -= packet_size;
94 return dbuf->data + offset;
103 struct dev_limit_counter {
104 /** The current number of received samples/frames/etc. */
106 /** The limit (in number of samples/frames/etc.). */
110 static void dev_limit_counter_start(struct dev_limit_counter *cnt)
115 static void dev_limit_counter_inc(struct dev_limit_counter *cnt)
120 static void dev_limit_counter_limit_set(struct dev_limit_counter *cnt,
126 static gboolean dev_limit_counter_limit_reached(struct dev_limit_counter *cnt)
128 if (cnt->limit && cnt->count >= cnt->limit) {
129 sr_info("Requested counter limit reached.");
136 struct dev_time_counter {
137 /** The starting time of current sampling run. */
139 /** The time limit (in milliseconds). */
143 static void dev_time_counter_start(struct dev_time_counter *cnt)
145 cnt->starttime = g_get_monotonic_time();
148 static void dev_time_limit_set(struct dev_time_counter *cnt, uint64_t limit)
153 static gboolean dev_time_limit_reached(struct dev_time_counter *cnt)
158 time = (g_get_monotonic_time() - cnt->starttime) / 1000;
159 if (time > (int64_t)cnt->limit) {
160 sr_info("Requested time limit reached.");
168 static void serial_conf_get(GSList *options, const char *def_serialcomm,
169 const char **conn, const char **serialcomm)
171 struct sr_config *src;
174 *conn = *serialcomm = NULL;
175 for (l = options; l; l = l->next) {
179 *conn = g_variant_get_string(src->data, NULL);
181 case SR_CONF_SERIALCOMM:
182 *serialcomm = g_variant_get_string(src->data, NULL);
187 if (*serialcomm == NULL)
188 *serialcomm = def_serialcomm;
191 static struct sr_serial_dev_inst *serial_dev_new(GSList *options,
192 const char *def_serialcomm)
195 const char *conn, *serialcomm;
197 serial_conf_get(options, def_serialcomm, &conn, &serialcomm);
202 return sr_serial_dev_inst_new(conn, serialcomm);
205 static int serial_stream_check_buf(struct sr_serial_dev_inst *serial,
206 uint8_t *buf, size_t buflen,
208 packet_valid_callback is_valid,
209 uint64_t timeout_ms, int baudrate)
214 if ((ret = serial_open(serial, SERIAL_RDWR)) != SR_OK)
217 serial_flush(serial);
220 ret = serial_stream_detect(serial, buf, &len, packet_size,
221 is_valid, timeout_ms, baudrate);
223 serial_close(serial);
229 * If we dropped more than two packets worth of data, something is
230 * wrong. We shouldn't quit however, since the dropped bytes might be
231 * just zeroes at the beginning of the stream. Those can occur as a
232 * combination of the nonstandard cable that ships with some devices
233 * and the serial port or USB to serial adapter.
235 dropped = len - packet_size;
236 if (dropped > 2 * packet_size)
237 sr_warn("Had to drop too much data.");
242 static int serial_stream_check(struct sr_serial_dev_inst *serial,
244 packet_valid_callback is_valid,
245 uint64_t timeout_ms, int baudrate)
249 return serial_stream_check_buf(serial, buf, sizeof(buf), packet_size,
250 is_valid, timeout_ms, baudrate);
253 struct std_opt_desc {
254 const uint32_t *scanopts;
255 const int num_scanopts;
256 const uint32_t *devopts;
257 const int num_devopts;
260 static int std_config_list(uint32_t key, GVariant **data,
261 const struct std_opt_desc *d)
264 case SR_CONF_SCAN_OPTIONS:
265 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
266 d->scanopts, d->num_scanopts, sizeof(uint32_t));
268 case SR_CONF_DEVICE_OPTIONS:
269 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
270 d->devopts, d->num_devopts, sizeof(uint32_t));
279 static int send_config_update(struct sr_dev_inst *sdi, struct sr_config *cfg)
281 struct sr_datafeed_packet packet;
282 struct sr_datafeed_meta meta;
284 memset(&meta, 0, sizeof(meta));
286 packet.type = SR_DF_META;
287 packet.payload = &meta;
289 meta.config = g_slist_append(meta.config, cfg);
291 return sr_session_send(sdi, &packet);
294 static int send_config_update_key(struct sr_dev_inst *sdi, uint32_t key,
297 struct sr_config *cfg;
300 cfg = sr_config_new(key, var);
304 ret = send_config_update(sdi, cfg);
311 * Cyrustek ES51919 LCR chipset host protocol.
313 * Public official documentation does not contain the protocol
314 * description, so this is all based on reverse engineering.
316 * Packet structure (17 bytes):
318 * 0x00: header1 ?? (0x00)
319 * 0x01: header2 ?? (0x0d)
322 * bit 0 = hold enabled
323 * bit 1 = reference shown (in delta mode)
325 * bit 3 = calibration mode
326 * bit 4 = sorting mode
329 * bit 7 = parallel measurement (vs. serial)
332 * bit 0-4 = ??? (0x10)
333 * bit 5-7 = test frequency
341 * 0x04: tolerance (sorting mode)
352 * 0x05-0x09: primary measurement
353 * 0x05: measured quantity
358 * 0x06: measurement MSB (0x4e20 = 20000 = outside limits)
359 * 0x07: measurement LSB
360 * 0x08: measurement info
361 * bit 0-2 = decimal point multiplier (10^-val)
377 * 0x09: measurement status
379 * 0 = normal (measurement shown)
380 * 1 = blank (nothing shown)
382 * 3 = outside limits ("OL")
386 * 10 = shorted ("Srt")
387 * bit 4-6 = ??? (maybe part of same field with 0-3)
388 * bit 7 = ??? (some independent flag)
390 * 0x0a-0x0e: secondary measurement
391 * 0x0a: measured quantity
393 * 1 = dissipation factor
395 * 3 = parallel AC resistance / ESR
397 * 0x0b-0x0e: like primary measurement
399 * 0x0f: footer1 (0x0d) ?
400 * 0x10: footer2 (0x0a) ?
403 #define PACKET_SIZE 17
405 static const double frequencies[] = {
406 100, 120, 1000, 10000, 100000, 0,
409 enum { QUANT_AUTO = 5, };
411 static const char *const quantities1[] = {
412 "NONE", "INDUCTANCE", "CAPACITANCE", "RESISTANCE", "RESISTANCE", "AUTO",
415 static const char *const list_quantities1[] = {
416 "NONE", "INDUCTANCE", "CAPACITANCE", "RESISTANCE", "AUTO",
419 static const char *const quantities2[] = {
420 "NONE", "DISSIPATION", "QUALITY", "RESISTANCE", "ANGLE", "AUTO",
423 enum { MODEL_NONE, MODEL_PAR, MODEL_SER, MODEL_AUTO, };
425 static const char *const models[] = {
426 "NONE", "PARALLEL", "SERIES", "AUTO",
429 /** Private, per-device-instance driver context. */
431 /** Opaque pointer passed in by the frontend. */
434 /** The number of frames. */
435 struct dev_limit_counter frame_count;
437 /** The time limit counter. */
438 struct dev_time_counter time_count;
441 struct dev_buffer *buf;
443 /** The frequency of the test signal (index to frequencies[]). */
446 /** Measured primary quantity (index to quantities1[]). */
449 /** Measured secondary quantity (index to quantities2[]). */
452 /** Equivalent circuit model (index to models[]). */
456 static const uint8_t *pkt_to_buf(const uint8_t *pkt, int is_secondary)
458 return is_secondary ? pkt + 10 : pkt + 5;
461 static int parse_mq(const uint8_t *pkt, int is_secondary, int is_parallel)
465 buf = pkt_to_buf(pkt, is_secondary);
467 switch (is_secondary << 8 | buf[0]) {
470 SR_MQ_PARALLEL_INDUCTANCE : SR_MQ_SERIES_INDUCTANCE;
473 SR_MQ_PARALLEL_CAPACITANCE : SR_MQ_SERIES_CAPACITANCE;
477 SR_MQ_PARALLEL_RESISTANCE : SR_MQ_SERIES_RESISTANCE;
479 return SR_MQ_RESISTANCE;
481 return SR_MQ_DIFFERENCE;
483 return SR_MQ_DISSIPATION_FACTOR;
485 return SR_MQ_QUALITY_FACTOR;
487 return SR_MQ_PHASE_ANGLE;
490 sr_err("Unknown quantity 0x%03x.", is_secondary << 8 | buf[0]);
495 static float parse_value(const uint8_t *buf)
497 static const float decimals[] = {
498 1, 1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7
502 val = (buf[1] << 8) | buf[2];
503 return (float)val * decimals[buf[3] & 7];
506 static void parse_measurement(const uint8_t *pkt, float *floatval,
507 struct sr_datafeed_analog *analog,
510 static const struct {
514 { SR_UNIT_UNITLESS, 1 }, /* no unit */
515 { SR_UNIT_OHM, 1 }, /* Ohm */
516 { SR_UNIT_OHM, 1e3 }, /* kOhm */
517 { SR_UNIT_OHM, 1e6 }, /* MOhm */
519 { SR_UNIT_HENRY, 1e-6 }, /* uH */
520 { SR_UNIT_HENRY, 1e-3 }, /* mH */
521 { SR_UNIT_HENRY, 1 }, /* H */
522 { SR_UNIT_HENRY, 1e3 }, /* kH */
523 { SR_UNIT_FARAD, 1e-12 }, /* pF */
524 { SR_UNIT_FARAD, 1e-9 }, /* nF */
525 { SR_UNIT_FARAD, 1e-6 }, /* uF */
526 { SR_UNIT_FARAD, 1e-3 }, /* mF */
527 { SR_UNIT_PERCENTAGE, 1 }, /* % */
528 { SR_UNIT_DEGREE, 1 } /* degree */
533 buf = pkt_to_buf(pkt, is_secondary);
538 state = buf[4] & 0xf;
540 if (state != 0 && state != 3)
544 /* Calibration and Sorting modes not supported. */
550 analog->mqflags |= SR_MQFLAG_HOLD;
552 analog->mqflags |= SR_MQFLAG_REFERENCE;
555 analog->mqflags |= SR_MQFLAG_RELATIVE;
558 if ((analog->mq = parse_mq(pkt, is_secondary, pkt[2] & 0x80)) < 0)
561 if ((buf[3] >> 3) >= ARRAY_SIZE(units)) {
562 sr_err("Unknown unit %u.", buf[3] >> 3);
567 analog->unit = units[buf[3] >> 3].unit;
569 *floatval = parse_value(buf);
570 *floatval *= (state == 0) ? units[buf[3] >> 3].mult : INFINITY;
573 static unsigned int parse_freq(const uint8_t *pkt)
579 if (freq >= ARRAY_SIZE(frequencies)) {
580 sr_err("Unknown frequency %u.", freq);
581 freq = ARRAY_SIZE(frequencies) - 1;
587 static unsigned int parse_quant(const uint8_t *pkt, int is_secondary)
594 buf = pkt_to_buf(pkt, is_secondary);
599 static unsigned int parse_model(const uint8_t *pkt)
603 else if (parse_mq(pkt, 0, 0) == SR_MQ_RESISTANCE)
605 else if (pkt[2] & 0x80)
611 static gboolean packet_valid(const uint8_t *pkt)
614 * If the first two bytes of the packet are indeed a constant
615 * header, they should be checked too. Since we don't know it
616 * for sure, we'll just check the last two for now since they
617 * seem to be constant just like in the other Cyrustek chipset
620 if (pkt[15] == 0xd && pkt[16] == 0xa)
626 static int do_config_update(struct sr_dev_inst *sdi, uint32_t key,
629 struct dev_context *devc;
633 return send_config_update_key(devc->cb_data, key, var);
636 static int send_freq_update(struct sr_dev_inst *sdi, unsigned int freq)
638 return do_config_update(sdi, SR_CONF_OUTPUT_FREQUENCY,
639 g_variant_new_double(frequencies[freq]));
642 static int send_quant1_update(struct sr_dev_inst *sdi, unsigned int quant)
644 return do_config_update(sdi, SR_CONF_MEASURED_QUANTITY,
645 g_variant_new_string(quantities1[quant]));
648 static int send_quant2_update(struct sr_dev_inst *sdi, unsigned int quant)
650 return do_config_update(sdi, SR_CONF_MEASURED_2ND_QUANTITY,
651 g_variant_new_string(quantities2[quant]));
654 static int send_model_update(struct sr_dev_inst *sdi, unsigned int model)
656 return do_config_update(sdi, SR_CONF_EQUIV_CIRCUIT_MODEL,
657 g_variant_new_string(models[model]));
660 static void handle_packet(struct sr_dev_inst *sdi, const uint8_t *pkt)
662 struct sr_datafeed_packet packet;
663 struct sr_datafeed_analog analog;
664 struct dev_context *devc;
671 val = parse_freq(pkt);
672 if (val != devc->freq) {
673 if (send_freq_update(sdi, val) == SR_OK)
679 val = parse_quant(pkt, 0);
680 if (val != devc->quant1) {
681 if (send_quant1_update(sdi, val) == SR_OK)
687 val = parse_quant(pkt, 1);
688 if (val != devc->quant2) {
689 if (send_quant2_update(sdi, val) == SR_OK)
695 val = parse_model(pkt);
696 if (val != devc->model) {
697 if (send_model_update(sdi, val) == SR_OK)
705 memset(&analog, 0, sizeof(analog));
707 analog.num_samples = 1;
708 analog.data = &floatval;
710 analog.channels = g_slist_append(NULL, sdi->channels->data);
712 parse_measurement(pkt, &floatval, &analog, 0);
713 if (analog.mq >= 0) {
715 packet.type = SR_DF_FRAME_BEGIN;
716 sr_session_send(devc->cb_data, &packet);
720 packet.type = SR_DF_ANALOG;
721 packet.payload = &analog;
723 sr_session_send(devc->cb_data, &packet);
726 g_slist_free(analog.channels);
727 analog.channels = g_slist_append(NULL, sdi->channels->next->data);
729 parse_measurement(pkt, &floatval, &analog, 1);
730 if (analog.mq >= 0) {
732 packet.type = SR_DF_FRAME_BEGIN;
733 sr_session_send(devc->cb_data, &packet);
737 packet.type = SR_DF_ANALOG;
738 packet.payload = &analog;
740 sr_session_send(devc->cb_data, &packet);
743 g_slist_free(analog.channels);
746 packet.type = SR_DF_FRAME_END;
747 sr_session_send(devc->cb_data, &packet);
748 dev_limit_counter_inc(&devc->frame_count);
752 static int handle_new_data(struct sr_dev_inst *sdi)
754 struct dev_context *devc;
760 ret = dev_buffer_fill_serial(devc->buf, sdi);
764 while ((pkt = dev_buffer_packet_find(devc->buf, packet_valid,
766 handle_packet(sdi, pkt);
771 static int receive_data(int fd, int revents, void *cb_data)
773 struct sr_dev_inst *sdi;
774 struct dev_context *devc;
778 if (!(sdi = cb_data))
781 if (!(devc = sdi->priv))
784 if (revents == G_IO_IN) {
785 /* Serial data arrived. */
786 handle_new_data(sdi);
789 if (dev_limit_counter_limit_reached(&devc->frame_count) ||
790 dev_time_limit_reached(&devc->time_count))
791 sdi->driver->dev_acquisition_stop(sdi, cb_data);
796 static const char *const channel_names[] = { "P1", "P2" };
798 static int setup_channels(struct sr_dev_inst *sdi)
805 for (i = 0; i < ARRAY_SIZE(channel_names); i++)
806 sr_channel_new(sdi, i, SR_CHANNEL_ANALOG, TRUE, channel_names[i]);
811 SR_PRIV void es51919_serial_clean(void *priv)
813 struct dev_context *devc;
818 dev_buffer_destroy(devc->buf);
822 SR_PRIV struct sr_dev_inst *es51919_serial_scan(GSList *options,
826 struct sr_serial_dev_inst *serial;
827 struct sr_dev_inst *sdi;
828 struct dev_context *devc;
835 if (!(serial = serial_dev_new(options, "9600/8n1/rts=1/dtr=1")))
838 ret = serial_stream_check(serial, PACKET_SIZE, packet_valid,
843 sr_info("Found device on port %s.", serial->port);
845 sdi = g_malloc0(sizeof(struct sr_dev_inst));
846 sdi->status = SR_ST_INACTIVE;
847 sdi->vendor = g_strdup(vendor);
848 sdi->model = g_strdup(model);
849 devc = g_malloc0(sizeof(struct dev_context));
850 devc->buf = dev_buffer_new(PACKET_SIZE * 8);
851 sdi->inst_type = SR_INST_SERIAL;
855 if (setup_channels(sdi) != SR_OK)
861 es51919_serial_clean(devc);
863 sr_dev_inst_free(sdi);
865 sr_serial_dev_inst_free(serial);
870 SR_PRIV int es51919_serial_config_get(uint32_t key, GVariant **data,
871 const struct sr_dev_inst *sdi,
872 const struct sr_channel_group *cg)
874 struct dev_context *devc;
878 if (!(devc = sdi->priv))
882 case SR_CONF_OUTPUT_FREQUENCY:
883 *data = g_variant_new_double(frequencies[devc->freq]);
885 case SR_CONF_MEASURED_QUANTITY:
886 *data = g_variant_new_string(quantities1[devc->quant1]);
888 case SR_CONF_MEASURED_2ND_QUANTITY:
889 *data = g_variant_new_string(quantities2[devc->quant2]);
891 case SR_CONF_EQUIV_CIRCUIT_MODEL:
892 *data = g_variant_new_string(models[devc->model]);
895 sr_spew("%s: Unsupported key %u", __func__, key);
902 SR_PRIV int es51919_serial_config_set(uint32_t key, GVariant *data,
903 const struct sr_dev_inst *sdi,
904 const struct sr_channel_group *cg)
906 struct dev_context *devc;
911 if (!(devc = sdi->priv))
915 case SR_CONF_LIMIT_MSEC:
916 val = g_variant_get_uint64(data);
917 dev_time_limit_set(&devc->time_count, val);
918 sr_dbg("Setting time limit to %" PRIu64 ".", val);
920 case SR_CONF_LIMIT_FRAMES:
921 val = g_variant_get_uint64(data);
922 dev_limit_counter_limit_set(&devc->frame_count, val);
923 sr_dbg("Setting frame limit to %" PRIu64 ".", val);
926 sr_spew("%s: Unsupported key %u", __func__, key);
933 static const uint32_t scanopts[] = {
938 static const uint32_t devopts[] = {
941 SR_CONF_LIMIT_FRAMES | SR_CONF_SET,
942 SR_CONF_LIMIT_MSEC | SR_CONF_SET,
943 SR_CONF_OUTPUT_FREQUENCY | SR_CONF_GET | SR_CONF_LIST,
944 SR_CONF_MEASURED_QUANTITY | SR_CONF_GET | SR_CONF_LIST,
945 SR_CONF_MEASURED_2ND_QUANTITY | SR_CONF_GET | SR_CONF_LIST,
946 SR_CONF_EQUIV_CIRCUIT_MODEL | SR_CONF_GET | SR_CONF_LIST,
949 static const struct std_opt_desc opts = {
950 scanopts, ARRAY_SIZE(scanopts),
951 devopts, ARRAY_SIZE(devopts),
954 SR_PRIV int es51919_serial_config_list(uint32_t key, GVariant **data,
955 const struct sr_dev_inst *sdi,
956 const struct sr_channel_group *cg)
961 if (std_config_list(key, data, &opts) == SR_OK)
965 case SR_CONF_OUTPUT_FREQUENCY:
966 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_DOUBLE,
967 frequencies, ARRAY_SIZE(frequencies), sizeof(double));
969 case SR_CONF_MEASURED_QUANTITY:
970 *data = g_variant_new_strv(list_quantities1,
971 ARRAY_SIZE(list_quantities1));
973 case SR_CONF_MEASURED_2ND_QUANTITY:
974 *data = g_variant_new_strv(quantities2,
975 ARRAY_SIZE(quantities2));
977 case SR_CONF_EQUIV_CIRCUIT_MODEL:
978 *data = g_variant_new_strv(models, ARRAY_SIZE(models));
981 sr_spew("%s: Unsupported key %u", __func__, key);
988 SR_PRIV int es51919_serial_acquisition_start(const struct sr_dev_inst *sdi,
991 struct dev_context *devc;
992 struct sr_serial_dev_inst *serial;
994 if (sdi->status != SR_ST_ACTIVE)
995 return SR_ERR_DEV_CLOSED;
997 if (!(devc = sdi->priv))
1000 devc->cb_data = cb_data;
1002 dev_limit_counter_start(&devc->frame_count);
1003 dev_time_counter_start(&devc->time_count);
1005 /* Send header packet to the session bus. */
1006 std_session_send_df_header(cb_data, LOG_PREFIX);
1008 /* Poll every 50ms, or whenever some data comes in. */
1010 serial_source_add(sdi->session, serial, G_IO_IN, 50,
1011 receive_data, (void *)sdi);
1016 SR_PRIV int es51919_serial_acquisition_stop(struct sr_dev_inst *sdi,
1019 return std_serial_dev_acquisition_stop(sdi, cb_data,
1020 std_serial_dev_close, sdi->conn, LOG_PREFIX);