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.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 if (!(dbuf = g_try_malloc(sizeof(struct dev_buffer) + size))) {
45 sr_err("Dev buffer malloc failed (size=%zu).", size);
56 static void dev_buffer_destroy(struct dev_buffer *dbuf)
61 static int dev_buffer_fill_serial(struct dev_buffer *dbuf,
62 struct sr_dev_inst *sdi)
64 struct sr_serial_dev_inst *serial;
69 /* If we already have data, move it to the beginning of the buffer. */
70 if (dbuf->len > 0 && dbuf->offset > 0)
71 memmove(dbuf->data, dbuf->data + dbuf->offset, dbuf->len);
75 len = dbuf->size - dbuf->len;
76 len = serial_read_nonblocking(serial, dbuf->data + dbuf->len, len);
78 sr_err("Serial port read error: %d.", len);
87 static uint8_t *dev_buffer_packet_find(struct dev_buffer *dbuf,
88 gboolean (*packet_valid)(const uint8_t *),
93 while (dbuf->len >= packet_size) {
94 if (packet_valid(dbuf->data + dbuf->offset)) {
95 offset = dbuf->offset;
96 dbuf->offset += packet_size;
97 dbuf->len -= packet_size;
98 return dbuf->data + offset;
107 struct dev_sample_counter {
108 /** The current number of already received samples. */
110 /** The current sampling limit (in number of samples). */
114 static void dev_sample_counter_start(struct dev_sample_counter *cnt)
119 static void dev_sample_counter_inc(struct dev_sample_counter *cnt)
124 static void dev_sample_limit_set(struct dev_sample_counter *cnt, uint64_t limit)
129 static gboolean dev_sample_limit_reached(struct dev_sample_counter *cnt)
131 if (cnt->limit && cnt->count >= cnt->limit) {
132 sr_info("Requested sample 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,
212 uint64_t timeout_ms, int baudrate)
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, baudrate);
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,
248 uint64_t timeout_ms, int baudrate)
252 return serial_stream_check_buf(serial, buf, sizeof(buf), packet_size,
253 is_valid, timeout_ms, baudrate);
256 struct std_opt_desc {
257 const uint32_t *scanopts;
258 const int num_scanopts;
259 const uint32_t *devopts;
260 const int num_devopts;
263 static int std_config_list(uint32_t key, GVariant **data,
264 const struct std_opt_desc *d)
267 case SR_CONF_SCAN_OPTIONS:
268 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
269 d->scanopts, d->num_scanopts, sizeof(uint32_t));
271 case SR_CONF_DEVICE_OPTIONS:
272 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
273 d->devopts, d->num_devopts, sizeof(uint32_t));
282 static int send_config_update(struct sr_dev_inst *sdi, struct sr_config *cfg)
284 struct sr_datafeed_packet packet;
285 struct sr_datafeed_meta meta;
287 memset(&meta, 0, sizeof(meta));
289 packet.type = SR_DF_META;
290 packet.payload = &meta;
292 meta.config = g_slist_append(meta.config, cfg);
294 return sr_session_send(sdi, &packet);
298 * Cyrustek ES51919 LCR chipset host protocol.
300 * Public official documentation does not contain the protocol
301 * description, so this is all based on reverse engineering.
303 * Packet structure (17 bytes):
305 * 0x00: header1 ?? (0x00)
306 * 0x01: header2 ?? (0x0d)
309 * bit 0 = hold enabled
310 * bit 1 = reference shown (in delta mode)
312 * bit 3 = calibration mode
313 * bit 4 = sorting mode
316 * bit 7 = parallel measurement (vs. serial)
319 * bit 0-4 = ??? (0x10)
320 * bit 5-7 = test frequency
328 * 0x04: tolerance (sorting mode)
339 * 0x05-0x09: primary measurement
340 * 0x05: measured quantity
345 * 0x06: measurement MSB (0x4e20 = 20000 = outside limits)
346 * 0x07: measurement LSB
347 * 0x08: measurement info
348 * bit 0-2 = decimal point multiplier (10^-val)
364 * 0x09: measurement status
366 * 0 = normal (measurement shown)
367 * 1 = blank (nothing shown)
369 * 3 = ouside limits ("OL")
373 * 10 = shorted ("Srt")
374 * bit 4-6 = ??? (maybe part of same field with 0-3)
375 * bit 7 = ??? (some independent flag)
377 * 0x0a-0x0e: secondary measurement
378 * 0x0a: measured quantity
380 * 1 = dissipation factor
382 * 3 = parallel AC resistance / ESR
384 * 0x0b-0x0e: like primary measurement
386 * 0x0f: footer1 (0x0d) ?
387 * 0x10: footer2 (0x0a) ?
390 #define PACKET_SIZE 17
392 static const uint64_t frequencies[] = {
393 100, 120, 1000, 10000, 100000, 0,
396 /** Private, per-device-instance driver context. */
398 /** Opaque pointer passed in by the frontend. */
401 /** The number of samples. */
402 struct dev_sample_counter sample_count;
404 /** The time limit counter. */
405 struct dev_time_counter time_count;
408 struct dev_buffer *buf;
410 /** The frequency of the test signal (index to frequencies[]). */
414 static int parse_mq(const uint8_t *buf, int is_secondary, int is_parallel)
416 switch (is_secondary << 8 | buf[0]) {
419 SR_MQ_PARALLEL_INDUCTANCE : SR_MQ_SERIES_INDUCTANCE;
422 SR_MQ_PARALLEL_CAPACITANCE : SR_MQ_SERIES_CAPACITANCE;
426 SR_MQ_PARALLEL_RESISTANCE : SR_MQ_SERIES_RESISTANCE;
428 return SR_MQ_RESISTANCE;
430 return SR_MQ_DIFFERENCE;
432 return SR_MQ_DISSIPATION_FACTOR;
434 return SR_MQ_QUALITY_FACTOR;
436 return SR_MQ_PHASE_ANGLE;
439 sr_err("Unknown quantity 0x%03x.", is_secondary << 8 | buf[0]);
444 static float parse_value(const uint8_t *buf)
446 static const float decimals[] = {
447 1, 1e-1, 1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7
451 val = (buf[1] << 8) | buf[2];
452 return (float)val * decimals[buf[3] & 7];
455 static void parse_measurement(const uint8_t *pkt, float *floatval,
456 struct sr_datafeed_analog *analog,
459 static const struct {
463 { SR_UNIT_UNITLESS, 1 }, /* no unit */
464 { SR_UNIT_OHM, 1 }, /* Ohm */
465 { SR_UNIT_OHM, 1e3 }, /* kOhm */
466 { SR_UNIT_OHM, 1e6 }, /* MOhm */
468 { SR_UNIT_HENRY, 1e-6 }, /* uH */
469 { SR_UNIT_HENRY, 1e-3 }, /* mH */
470 { SR_UNIT_HENRY, 1 }, /* H */
471 { SR_UNIT_HENRY, 1e3 }, /* kH */
472 { SR_UNIT_FARAD, 1e-12 }, /* pF */
473 { SR_UNIT_FARAD, 1e-9 }, /* nF */
474 { SR_UNIT_FARAD, 1e-6 }, /* uF */
475 { SR_UNIT_FARAD, 1e-3 }, /* mF */
476 { SR_UNIT_PERCENTAGE, 1 }, /* % */
477 { SR_UNIT_DEGREE, 1 } /* degree */
482 buf = pkt + (is_secondary ? 10 : 5);
487 state = buf[4] & 0xf;
489 if (state != 0 && state != 3)
493 /* Calibration and Sorting modes not supported. */
499 analog->mqflags |= SR_MQFLAG_HOLD;
501 analog->mqflags |= SR_MQFLAG_REFERENCE;
503 analog->mqflags |= SR_MQFLAG_AUTOMQ;
505 analog->mqflags |= SR_MQFLAG_AUTOMODEL;
508 analog->mqflags |= SR_MQFLAG_RELATIVE;
511 if ((analog->mq = parse_mq(buf, is_secondary, pkt[2] & 0x80)) < 0)
514 if ((buf[3] >> 3) >= ARRAY_SIZE(units)) {
515 sr_err("Unknown unit %u.", buf[3] >> 3);
520 analog->unit = units[buf[3] >> 3].unit;
522 *floatval = parse_value(buf);
523 *floatval *= (state == 0) ? units[buf[3] >> 3].mult : INFINITY;
526 static unsigned int parse_frequency(const uint8_t *pkt)
532 if (freq >= ARRAY_SIZE(frequencies)) {
533 sr_err("Unknown frequency %u.", freq);
534 freq = ARRAY_SIZE(frequencies) - 1;
540 static gboolean packet_valid(const uint8_t *pkt)
543 * If the first two bytes of the packet are indeed a constant
544 * header, they should be checked too. Since we don't know it
545 * for sure, we'll just check the last two for now since they
546 * seem to be constant just like in the other Cyrustek chipset
549 if (pkt[15] == 0xd && pkt[16] == 0xa)
555 static int send_frequency_update(struct sr_dev_inst *sdi, unsigned int freq)
557 struct sr_config *cfg;
558 struct dev_context *devc;
563 cfg = sr_config_new(SR_CONF_OUTPUT_FREQUENCY,
564 g_variant_new_uint64(frequencies[freq]));
569 ret = send_config_update(devc->cb_data, cfg);
575 static void handle_packet(struct sr_dev_inst *sdi, const uint8_t *pkt)
577 struct sr_datafeed_packet packet;
578 struct sr_datafeed_analog analog;
579 struct dev_context *devc;
586 freq = parse_frequency(pkt);
587 if (freq != devc->freq) {
588 if (send_frequency_update(sdi, freq) == SR_OK)
596 memset(&analog, 0, sizeof(analog));
598 analog.num_samples = 1;
599 analog.data = &floatval;
601 packet.type = SR_DF_ANALOG;
602 packet.payload = &analog;
604 analog.channels = g_slist_append(NULL, sdi->channels->data);
606 parse_measurement(pkt, &floatval, &analog, 0);
607 if (analog.mq >= 0) {
608 if (sr_session_send(devc->cb_data, &packet) == SR_OK)
612 analog.channels = g_slist_append(NULL, sdi->channels->next->data);
614 parse_measurement(pkt, &floatval, &analog, 1);
615 if (analog.mq >= 0) {
616 if (sr_session_send(devc->cb_data, &packet) == SR_OK)
621 dev_sample_counter_inc(&devc->sample_count);
624 static int handle_new_data(struct sr_dev_inst *sdi)
626 struct dev_context *devc;
632 ret = dev_buffer_fill_serial(devc->buf, sdi);
636 while ((pkt = dev_buffer_packet_find(devc->buf, packet_valid,
638 handle_packet(sdi, pkt);
643 static int receive_data(int fd, int revents, void *cb_data)
645 struct sr_dev_inst *sdi;
646 struct dev_context *devc;
650 if (!(sdi = cb_data))
653 if (!(devc = sdi->priv))
656 if (revents == G_IO_IN) {
657 /* Serial data arrived. */
658 handle_new_data(sdi);
661 if (dev_sample_limit_reached(&devc->sample_count) ||
662 dev_time_limit_reached(&devc->time_count))
663 sdi->driver->dev_acquisition_stop(sdi, cb_data);
668 static int add_channel(struct sr_dev_inst *sdi, const char *name)
670 struct sr_channel *ch;
672 if (!(ch = sr_channel_new(0, SR_CHANNEL_ANALOG, TRUE, name)))
675 sdi->channels = g_slist_append(sdi->channels, ch);
680 static const char *const channel_names[] = { "P1", "P2" };
682 static int setup_channels(struct sr_dev_inst *sdi)
689 for (i = 0; i < ARRAY_SIZE(channel_names); i++) {
690 ret = add_channel(sdi, channel_names[i]);
698 SR_PRIV void es51919_serial_clean(void *priv)
700 struct dev_context *devc;
705 dev_buffer_destroy(devc->buf);
709 SR_PRIV struct sr_dev_inst *es51919_serial_scan(GSList *options,
713 struct sr_serial_dev_inst *serial;
714 struct sr_dev_inst *sdi;
715 struct dev_context *devc;
722 if (!(serial = serial_dev_new(options, "9600/8n1/rts=1/dtr=1")))
725 ret = serial_stream_check(serial, PACKET_SIZE, packet_valid,
730 sr_info("Found device on port %s.", serial->port);
732 if (!(sdi = sr_dev_inst_new(SR_ST_INACTIVE, vendor, model, NULL)))
735 if (!(devc = g_try_malloc0(sizeof(struct dev_context)))) {
736 sr_err("Device context malloc failed.");
740 if (!(devc->buf = dev_buffer_new(PACKET_SIZE * 8)))
745 sdi->inst_type = SR_INST_SERIAL;
750 if (setup_channels(sdi) != SR_OK)
756 es51919_serial_clean(devc);
758 sr_dev_inst_free(sdi);
760 sr_serial_dev_inst_free(serial);
765 SR_PRIV int es51919_serial_config_get(uint32_t key, GVariant **data,
766 const struct sr_dev_inst *sdi,
767 const struct sr_channel_group *cg)
769 struct dev_context *devc;
773 if (!(devc = sdi->priv))
777 case SR_CONF_OUTPUT_FREQUENCY:
778 *data = g_variant_new_uint64(frequencies[devc->freq]);
781 sr_spew("%s: Unsupported key %u", __func__, key);
788 SR_PRIV int es51919_serial_config_set(uint32_t key, GVariant *data,
789 const struct sr_dev_inst *sdi,
790 const struct sr_channel_group *cg)
792 struct dev_context *devc;
797 if (!(devc = sdi->priv))
801 case SR_CONF_LIMIT_MSEC:
802 val = g_variant_get_uint64(data);
803 dev_time_limit_set(&devc->time_count, val);
804 sr_dbg("Setting time limit to %" PRIu64 ".", val);
806 case SR_CONF_LIMIT_SAMPLES:
807 val = g_variant_get_uint64(data);
808 dev_sample_limit_set(&devc->sample_count, val);
809 sr_dbg("Setting sample limit to %" PRIu64 ".", val);
812 sr_spew("%s: Unsupported key %u", __func__, key);
819 static const uint32_t scanopts[] = {
824 static const uint32_t devopts[] = {
827 SR_CONF_LIMIT_SAMPLES | SR_CONF_SET,
828 SR_CONF_LIMIT_MSEC | SR_CONF_SET,
829 SR_CONF_OUTPUT_FREQUENCY | SR_CONF_GET | SR_CONF_LIST,
832 static const struct std_opt_desc opts = {
833 scanopts, ARRAY_SIZE(scanopts),
834 devopts, ARRAY_SIZE(devopts),
837 SR_PRIV int es51919_serial_config_list(uint32_t key, GVariant **data,
838 const struct sr_dev_inst *sdi,
839 const struct sr_channel_group *cg)
844 if (std_config_list(key, data, &opts) == SR_OK)
848 case SR_CONF_OUTPUT_FREQUENCY:
849 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT64,
850 frequencies, ARRAY_SIZE(frequencies), sizeof(uint64_t));
853 sr_spew("%s: Unsupported key %u", __func__, key);
860 SR_PRIV int es51919_serial_acquisition_start(const struct sr_dev_inst *sdi,
863 struct dev_context *devc;
864 struct sr_serial_dev_inst *serial;
866 if (sdi->status != SR_ST_ACTIVE)
867 return SR_ERR_DEV_CLOSED;
869 if (!(devc = sdi->priv))
872 devc->cb_data = cb_data;
874 dev_sample_counter_start(&devc->sample_count);
875 dev_time_counter_start(&devc->time_count);
877 /* Send header packet to the session bus. */
878 std_session_send_df_header(cb_data, LOG_PREFIX);
880 /* Poll every 50ms, or whenever some data comes in. */
882 serial_source_add(sdi->session, serial, G_IO_IN, 50,
883 receive_data, (void *)sdi);
888 SR_PRIV int es51919_serial_acquisition_stop(struct sr_dev_inst *sdi,
891 return std_serial_dev_acquisition_stop(sdi, cb_data,
892 std_serial_dev_close, sdi->conn, LOG_PREFIX);