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"
30 #ifdef HAVE_SERIAL_COMM
33 /** Total size of the buffer. */
35 /** Amount of data currently in the buffer. */
37 /** Offset where the data starts in the buffer. */
39 /** Space for the data. */
43 static struct dev_buffer *dev_buffer_new(size_t size)
45 struct dev_buffer *dbuf;
47 dbuf = g_malloc0(sizeof(struct dev_buffer) + size);
55 static void dev_buffer_destroy(struct dev_buffer *dbuf)
60 static int dev_buffer_fill_serial(struct dev_buffer *dbuf,
61 struct sr_dev_inst *sdi)
63 struct sr_serial_dev_inst *serial;
68 /* If we already have data, move it to the beginning of the buffer. */
69 if (dbuf->len > 0 && dbuf->offset > 0)
70 memmove(dbuf->data, dbuf->data + dbuf->offset, dbuf->len);
74 len = dbuf->size - dbuf->len;
75 len = serial_read_nonblocking(serial, dbuf->data + dbuf->len, len);
77 sr_err("Serial port read error: %d.", len);
86 static uint8_t *dev_buffer_packet_find(struct dev_buffer *dbuf,
87 gboolean (*packet_valid)(const uint8_t *),
92 while (dbuf->len >= packet_size) {
93 if (packet_valid(dbuf->data + dbuf->offset)) {
94 offset = dbuf->offset;
95 dbuf->offset += packet_size;
96 dbuf->len -= packet_size;
97 return dbuf->data + offset;
106 struct dev_limit_counter {
107 /** The current number of received samples/frames/etc. */
109 /** The limit (in number of samples/frames/etc.). */
113 static void dev_limit_counter_start(struct dev_limit_counter *cnt)
118 static void dev_limit_counter_inc(struct dev_limit_counter *cnt)
123 static void dev_limit_counter_limit_set(struct dev_limit_counter *cnt,
129 static gboolean dev_limit_counter_limit_reached(struct dev_limit_counter *cnt)
131 if (cnt->limit && cnt->count >= cnt->limit) {
132 sr_info("Requested counter limit reached.");
139 struct dev_time_counter {
140 /** The starting time of current sampling run. */
142 /** The time limit (in milliseconds). */
146 static void dev_time_counter_start(struct dev_time_counter *cnt)
148 cnt->starttime = g_get_monotonic_time();
151 static void dev_time_limit_set(struct dev_time_counter *cnt, uint64_t limit)
156 static gboolean dev_time_limit_reached(struct dev_time_counter *cnt)
161 time = (g_get_monotonic_time() - cnt->starttime) / 1000;
162 if (time > (int64_t)cnt->limit) {
163 sr_info("Requested time limit reached.");
171 static void serial_conf_get(GSList *options, const char *def_serialcomm,
172 const char **conn, const char **serialcomm)
174 struct sr_config *src;
177 *conn = *serialcomm = NULL;
178 for (l = options; l; l = l->next) {
182 *conn = g_variant_get_string(src->data, NULL);
184 case SR_CONF_SERIALCOMM:
185 *serialcomm = g_variant_get_string(src->data, NULL);
190 if (*serialcomm == NULL)
191 *serialcomm = def_serialcomm;
194 static struct sr_serial_dev_inst *serial_dev_new(GSList *options,
195 const char *def_serialcomm)
198 const char *conn, *serialcomm;
200 serial_conf_get(options, def_serialcomm, &conn, &serialcomm);
205 return sr_serial_dev_inst_new(conn, serialcomm);
208 static int serial_stream_check_buf(struct sr_serial_dev_inst *serial,
209 uint8_t *buf, size_t buflen,
211 packet_valid_callback is_valid,
217 if ((ret = serial_open(serial, SERIAL_RDWR)) != SR_OK)
220 serial_flush(serial);
223 ret = serial_stream_detect(serial, buf, &len, packet_size,
224 is_valid, timeout_ms);
226 serial_close(serial);
232 * If we dropped more than two packets worth of data, something is
233 * wrong. We shouldn't quit however, since the dropped bytes might be
234 * just zeroes at the beginning of the stream. Those can occur as a
235 * combination of the nonstandard cable that ships with some devices
236 * and the serial port or USB to serial adapter.
238 dropped = len - packet_size;
239 if (dropped > 2 * packet_size)
240 sr_warn("Had to drop too much data.");
245 static int serial_stream_check(struct sr_serial_dev_inst *serial,
247 packet_valid_callback is_valid,
252 return serial_stream_check_buf(serial, buf, sizeof(buf), packet_size,
253 is_valid, timeout_ms);
257 * Cyrustek ES51919 LCR chipset host protocol.
259 * Public official documentation does not contain the protocol
260 * description, so this is all based on reverse engineering.
262 * Packet structure (17 bytes):
264 * 0x00: header1 ?? (0x00)
265 * 0x01: header2 ?? (0x0d)
268 * bit 0 = hold enabled
269 * bit 1 = reference shown (in delta mode)
271 * bit 3 = calibration mode
272 * bit 4 = sorting mode
275 * bit 7 = parallel measurement (vs. serial)
278 * bit 0-4 = ??? (0x10)
279 * bit 5-7 = test frequency
287 * 0x04: tolerance (sorting mode)
298 * 0x05-0x09: primary measurement
299 * 0x05: measured quantity
304 * 0x06: measurement MSB (0x4e20 = 20000 = outside limits)
305 * 0x07: measurement LSB
306 * 0x08: measurement info
307 * bit 0-2 = decimal point multiplier (10^-val)
323 * 0x09: measurement status
325 * 0 = normal (measurement shown)
326 * 1 = blank (nothing shown)
328 * 3 = outside limits ("OL")
332 * 10 = shorted ("Srt")
333 * bit 4-6 = ??? (maybe part of same field with 0-3)
334 * bit 7 = ??? (some independent flag)
336 * 0x0a-0x0e: secondary measurement
337 * 0x0a: measured quantity
339 * 1 = dissipation factor
341 * 3 = parallel AC resistance / ESR
343 * 0x0b-0x0e: like primary measurement
345 * 0x0f: footer1 (0x0d) ?
346 * 0x10: footer2 (0x0a) ?
349 #define PACKET_SIZE 17
351 static const double frequencies[] = {
352 100, 120, 1000, 10000, 100000, 0,
355 enum { MODEL_NONE, MODEL_PAR, MODEL_SER, MODEL_AUTO, };
357 static const char *const models[] = {
358 "NONE", "PARALLEL", "SERIES", "AUTO",
362 struct dev_limit_counter frame_count;
364 struct dev_time_counter time_count;
366 struct dev_buffer *buf;
368 /** The frequency of the test signal (index to frequencies[]). */
371 /** Equivalent circuit model (index to models[]). */
375 static const uint8_t *pkt_to_buf(const uint8_t *pkt, int is_secondary)
377 return is_secondary ? pkt + 10 : pkt + 5;
380 static int parse_mq(const uint8_t *pkt, int is_secondary, int is_parallel)
384 buf = pkt_to_buf(pkt, is_secondary);
386 switch (is_secondary << 8 | buf[0]) {
389 SR_MQ_PARALLEL_INDUCTANCE : SR_MQ_SERIES_INDUCTANCE;
392 SR_MQ_PARALLEL_CAPACITANCE : SR_MQ_SERIES_CAPACITANCE;
396 SR_MQ_PARALLEL_RESISTANCE : SR_MQ_SERIES_RESISTANCE;
398 return SR_MQ_RESISTANCE;
400 return SR_MQ_DIFFERENCE;
402 return SR_MQ_DISSIPATION_FACTOR;
404 return SR_MQ_QUALITY_FACTOR;
406 return SR_MQ_PHASE_ANGLE;
409 sr_err("Unknown quantity 0x%03x.", is_secondary << 8 | buf[0]);
414 static float parse_value(const uint8_t *buf, int *digits)
416 static const int exponents[] = {0, -1, -2, -3, -4, -5, -6, -7};
420 exponent = exponents[buf[3] & 7];
422 val = (buf[1] << 8) | buf[2];
423 return (float)val * powf(10, exponent);
426 static void parse_measurement(const uint8_t *pkt, float *floatval,
427 struct sr_datafeed_analog *analog,
430 static const struct {
434 { SR_UNIT_UNITLESS, 0 }, /* no unit */
435 { SR_UNIT_OHM, 0 }, /* Ohm */
436 { SR_UNIT_OHM, 3 }, /* kOhm */
437 { SR_UNIT_OHM, 6 }, /* MOhm */
439 { SR_UNIT_HENRY, -6 }, /* uH */
440 { SR_UNIT_HENRY, -3 }, /* mH */
441 { SR_UNIT_HENRY, 0 }, /* H */
442 { SR_UNIT_HENRY, 3 }, /* kH */
443 { SR_UNIT_FARAD, -12 }, /* pF */
444 { SR_UNIT_FARAD, -9 }, /* nF */
445 { SR_UNIT_FARAD, -6 }, /* uF */
446 { SR_UNIT_FARAD, -3 }, /* mF */
447 { SR_UNIT_PERCENTAGE, 0 }, /* % */
448 { SR_UNIT_DEGREE, 0 }, /* degree */
451 int digits, exponent;
454 buf = pkt_to_buf(pkt, is_secondary);
456 analog->meaning->mq = 0;
457 analog->meaning->mqflags = 0;
459 state = buf[4] & 0xf;
461 if (state != 0 && state != 3)
465 /* Calibration and Sorting modes not supported. */
471 analog->meaning->mqflags |= SR_MQFLAG_HOLD;
473 analog->meaning->mqflags |= SR_MQFLAG_REFERENCE;
476 analog->meaning->mqflags |= SR_MQFLAG_RELATIVE;
479 if ((analog->meaning->mq = parse_mq(pkt, is_secondary, pkt[2] & 0x80)) == 0)
482 if ((buf[3] >> 3) >= ARRAY_SIZE(units)) {
483 sr_err("Unknown unit %u.", buf[3] >> 3);
484 analog->meaning->mq = 0;
488 analog->meaning->unit = units[buf[3] >> 3].unit;
490 exponent = units[buf[3] >> 3].exponent;
491 *floatval = parse_value(buf, &digits);
492 *floatval *= (state == 0) ? powf(10, exponent) : INFINITY;
493 analog->encoding->digits = digits - exponent;
494 analog->spec->spec_digits = digits - exponent;
497 static unsigned int parse_freq(const uint8_t *pkt)
503 if (freq >= ARRAY_SIZE(frequencies)) {
504 sr_err("Unknown frequency %u.", freq);
505 freq = ARRAY_SIZE(frequencies) - 1;
511 static unsigned int parse_model(const uint8_t *pkt)
515 else if (parse_mq(pkt, 0, 0) == SR_MQ_RESISTANCE)
517 else if (pkt[2] & 0x80)
523 static gboolean packet_valid(const uint8_t *pkt)
526 * If the first two bytes of the packet are indeed a constant
527 * header, they should be checked too. Since we don't know it
528 * for sure, we'll just check the last two for now since they
529 * seem to be constant just like in the other Cyrustek chipset
532 if (pkt[15] == 0xd && pkt[16] == 0xa)
538 static int send_freq_update(struct sr_dev_inst *sdi, unsigned int freq)
540 return sr_session_send_meta(sdi, SR_CONF_OUTPUT_FREQUENCY,
541 g_variant_new_double(frequencies[freq]));
544 static int send_model_update(struct sr_dev_inst *sdi, unsigned int model)
546 return sr_session_send_meta(sdi, SR_CONF_EQUIV_CIRCUIT_MODEL,
547 g_variant_new_string(models[model]));
550 static void handle_packet(struct sr_dev_inst *sdi, const uint8_t *pkt)
552 struct sr_datafeed_packet packet;
553 struct sr_datafeed_analog analog;
554 struct sr_analog_encoding encoding;
555 struct sr_analog_meaning meaning;
556 struct sr_analog_spec spec;
557 struct dev_context *devc;
561 struct sr_channel *channel;
565 val = parse_freq(pkt);
566 if (val != devc->freq) {
567 if (send_freq_update(sdi, val) == SR_OK)
573 val = parse_model(pkt);
574 if (val != devc->model) {
575 if (send_model_update(sdi, val) == SR_OK)
583 /* Note: digits/spec_digits will be overridden later. */
584 sr_analog_init(&analog, &encoding, &meaning, &spec, 0);
586 analog.num_samples = 1;
587 analog.data = &floatval;
589 channel = sdi->channels->data;
590 analog.meaning->channels = g_slist_append(NULL, channel);
592 parse_measurement(pkt, &floatval, &analog, 0);
593 if (analog.meaning->mq != 0 && channel->enabled) {
595 packet.type = SR_DF_FRAME_BEGIN;
596 sr_session_send(sdi, &packet);
600 packet.type = SR_DF_ANALOG;
601 packet.payload = &analog;
603 sr_session_send(sdi, &packet);
606 g_slist_free(analog.meaning->channels);
608 channel = sdi->channels->next->data;
609 analog.meaning->channels = g_slist_append(NULL, channel);
611 parse_measurement(pkt, &floatval, &analog, 1);
612 if (analog.meaning->mq != 0 && channel->enabled) {
614 packet.type = SR_DF_FRAME_BEGIN;
615 sr_session_send(sdi, &packet);
619 packet.type = SR_DF_ANALOG;
620 packet.payload = &analog;
622 sr_session_send(sdi, &packet);
625 g_slist_free(analog.meaning->channels);
628 packet.type = SR_DF_FRAME_END;
629 sr_session_send(sdi, &packet);
630 dev_limit_counter_inc(&devc->frame_count);
634 static int handle_new_data(struct sr_dev_inst *sdi)
636 struct dev_context *devc;
642 ret = dev_buffer_fill_serial(devc->buf, sdi);
646 while ((pkt = dev_buffer_packet_find(devc->buf, packet_valid,
648 handle_packet(sdi, pkt);
653 static int receive_data(int fd, int revents, void *cb_data)
655 struct sr_dev_inst *sdi;
656 struct dev_context *devc;
660 if (!(sdi = cb_data))
663 if (!(devc = sdi->priv))
666 if (revents == G_IO_IN) {
667 /* Serial data arrived. */
668 handle_new_data(sdi);
671 if (dev_limit_counter_limit_reached(&devc->frame_count) ||
672 dev_time_limit_reached(&devc->time_count))
673 sr_dev_acquisition_stop(sdi);
678 static const char *const channel_names[] = { "P1", "P2" };
680 static int setup_channels(struct sr_dev_inst *sdi)
684 for (i = 0; i < ARRAY_SIZE(channel_names); i++)
685 sr_channel_new(sdi, i, SR_CHANNEL_ANALOG, TRUE, channel_names[i]);
690 SR_PRIV void es51919_serial_clean(void *priv)
692 struct dev_context *devc;
697 dev_buffer_destroy(devc->buf);
700 SR_PRIV struct sr_dev_inst *es51919_serial_scan(GSList *options,
704 struct sr_serial_dev_inst *serial;
705 struct sr_dev_inst *sdi;
706 struct dev_context *devc;
713 if (!(serial = serial_dev_new(options, "9600/8n1/rts=1/dtr=1")))
716 ret = serial_stream_check(serial, PACKET_SIZE, packet_valid, 3000);
720 sr_info("Found device on port %s.", serial->port);
722 sdi = g_malloc0(sizeof(struct sr_dev_inst));
723 sdi->status = SR_ST_INACTIVE;
724 sdi->vendor = g_strdup(vendor);
725 sdi->model = g_strdup(model);
726 devc = g_malloc0(sizeof(struct dev_context));
727 devc->buf = dev_buffer_new(PACKET_SIZE * 8);
728 sdi->inst_type = SR_INST_SERIAL;
732 if (setup_channels(sdi) != SR_OK)
738 es51919_serial_clean(devc);
739 sr_dev_inst_free(sdi);
740 sr_serial_dev_inst_free(serial);
745 SR_PRIV int es51919_serial_config_get(uint32_t key, GVariant **data,
746 const struct sr_dev_inst *sdi,
747 const struct sr_channel_group *cg)
749 struct dev_context *devc;
756 case SR_CONF_OUTPUT_FREQUENCY:
757 *data = g_variant_new_double(frequencies[devc->freq]);
759 case SR_CONF_EQUIV_CIRCUIT_MODEL:
760 *data = g_variant_new_string(models[devc->model]);
769 SR_PRIV int es51919_serial_config_set(uint32_t key, GVariant *data,
770 const struct sr_dev_inst *sdi,
771 const struct sr_channel_group *cg)
773 struct dev_context *devc;
778 if (!(devc = sdi->priv))
782 case SR_CONF_LIMIT_MSEC:
783 val = g_variant_get_uint64(data);
784 dev_time_limit_set(&devc->time_count, val);
785 sr_dbg("Setting time limit to %" PRIu64 ".", val);
787 case SR_CONF_LIMIT_FRAMES:
788 val = g_variant_get_uint64(data);
789 dev_limit_counter_limit_set(&devc->frame_count, val);
790 sr_dbg("Setting frame limit to %" PRIu64 ".", val);
793 sr_spew("%s: Unsupported key %u", __func__, key);
800 static const uint32_t scanopts[] = {
805 static const uint32_t drvopts[] = {
809 static const uint32_t devopts[] = {
811 SR_CONF_LIMIT_FRAMES | SR_CONF_SET,
812 SR_CONF_LIMIT_MSEC | SR_CONF_SET,
813 SR_CONF_OUTPUT_FREQUENCY | SR_CONF_GET | SR_CONF_LIST,
814 SR_CONF_EQUIV_CIRCUIT_MODEL | SR_CONF_GET | SR_CONF_LIST,
817 SR_PRIV int es51919_serial_config_list(uint32_t key, GVariant **data,
818 const struct sr_dev_inst *sdi,
819 const struct sr_channel_group *cg)
822 case SR_CONF_SCAN_OPTIONS:
823 case SR_CONF_DEVICE_OPTIONS:
824 return STD_CONFIG_LIST(key, data, sdi, cg, scanopts, drvopts, devopts);
825 case SR_CONF_OUTPUT_FREQUENCY:
826 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_DOUBLE,
827 ARRAY_AND_SIZE(frequencies), sizeof(double));
829 case SR_CONF_EQUIV_CIRCUIT_MODEL:
830 *data = g_variant_new_strv(ARRAY_AND_SIZE(models));
839 SR_PRIV int es51919_serial_acquisition_start(const struct sr_dev_inst *sdi)
841 struct dev_context *devc;
842 struct sr_serial_dev_inst *serial;
844 if (!(devc = sdi->priv))
847 dev_limit_counter_start(&devc->frame_count);
848 dev_time_counter_start(&devc->time_count);
850 std_session_send_df_header(sdi);
853 serial_source_add(sdi->session, serial, G_IO_IN, 50,
854 receive_data, (void *)sdi);