]> sigrok.org Git - libsigrok.git/blob - src/lcr/es51919.c
deree-de5000: properly set encoding digits
[libsigrok.git] / src / lcr / es51919.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2014 Janne Huttunen <jahuttun@gmail.com>
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 #include <config.h>
21 #include <stdint.h>
22 #include <string.h>
23 #include <math.h>
24 #include <glib.h>
25 #include <libsigrok/libsigrok.h>
26 #include "libsigrok-internal.h"
27
28 #define LOG_PREFIX "es51919"
29
30 struct dev_buffer {
31         /** Total size of the buffer. */
32         size_t size;
33         /** Amount of data currently in the buffer. */
34         size_t len;
35         /** Offset where the data starts in the buffer. */
36         size_t offset;
37         /** Space for the data. */
38         uint8_t data[];
39 };
40
41 static struct dev_buffer *dev_buffer_new(size_t size)
42 {
43         struct dev_buffer *dbuf;
44
45         dbuf = g_malloc0(sizeof(struct dev_buffer) + size);
46         dbuf->size = size;
47         dbuf->len = 0;
48         dbuf->offset = 0;
49
50         return dbuf;
51 }
52
53 static void dev_buffer_destroy(struct dev_buffer *dbuf)
54 {
55         g_free(dbuf);
56 }
57
58 static int dev_buffer_fill_serial(struct dev_buffer *dbuf,
59                                   struct sr_dev_inst *sdi)
60 {
61         struct sr_serial_dev_inst *serial;
62         int len;
63
64         serial = sdi->conn;
65
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);
69
70         dbuf->offset = 0;
71
72         len = dbuf->size - dbuf->len;
73         len = serial_read_nonblocking(serial, dbuf->data + dbuf->len, len);
74         if (len < 0) {
75                 sr_err("Serial port read error: %d.", len);
76                 return len;
77         }
78
79         dbuf->len += len;
80
81         return SR_OK;
82 }
83
84 static uint8_t *dev_buffer_packet_find(struct dev_buffer *dbuf,
85                                 gboolean (*packet_valid)(const uint8_t *),
86                                 size_t packet_size)
87 {
88         size_t offset;
89
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;
96                 }
97                 dbuf->offset++;
98                 dbuf->len--;
99         }
100
101         return NULL;
102 }
103
104 struct dev_limit_counter {
105         /** The current number of received samples/frames/etc. */
106         uint64_t count;
107         /** The limit (in number of samples/frames/etc.). */
108         uint64_t limit;
109 };
110
111 static void dev_limit_counter_start(struct dev_limit_counter *cnt)
112 {
113         cnt->count = 0;
114 }
115
116 static void dev_limit_counter_inc(struct dev_limit_counter *cnt)
117 {
118         cnt->count++;
119 }
120
121 static void dev_limit_counter_limit_set(struct dev_limit_counter *cnt,
122                                         uint64_t limit)
123 {
124         cnt->limit = limit;
125 }
126
127 static gboolean dev_limit_counter_limit_reached(struct dev_limit_counter *cnt)
128 {
129         if (cnt->limit && cnt->count >= cnt->limit) {
130                 sr_info("Requested counter limit reached.");
131                 return TRUE;
132         }
133
134         return FALSE;
135 }
136
137 struct dev_time_counter {
138         /** The starting time of current sampling run. */
139         int64_t starttime;
140         /** The time limit (in milliseconds). */
141         uint64_t limit;
142 };
143
144 static void dev_time_counter_start(struct dev_time_counter *cnt)
145 {
146         cnt->starttime = g_get_monotonic_time();
147 }
148
149 static void dev_time_limit_set(struct dev_time_counter *cnt, uint64_t limit)
150 {
151         cnt->limit = limit;
152 }
153
154 static gboolean dev_time_limit_reached(struct dev_time_counter *cnt)
155 {
156         int64_t time;
157
158         if (cnt->limit) {
159                 time = (g_get_monotonic_time() - cnt->starttime) / 1000;
160                 if (time > (int64_t)cnt->limit) {
161                         sr_info("Requested time limit reached.");
162                         return TRUE;
163                 }
164         }
165
166         return FALSE;
167 }
168
169 static void serial_conf_get(GSList *options, const char *def_serialcomm,
170                             const char **conn, const char **serialcomm)
171 {
172         struct sr_config *src;
173         GSList *l;
174
175         *conn = *serialcomm = NULL;
176         for (l = options; l; l = l->next) {
177                 src = l->data;
178                 switch (src->key) {
179                 case SR_CONF_CONN:
180                         *conn = g_variant_get_string(src->data, NULL);
181                         break;
182                 case SR_CONF_SERIALCOMM:
183                         *serialcomm = g_variant_get_string(src->data, NULL);
184                         break;
185                 }
186         }
187
188         if (*serialcomm == NULL)
189                 *serialcomm = def_serialcomm;
190 }
191
192 static struct sr_serial_dev_inst *serial_dev_new(GSList *options,
193                                                  const char *def_serialcomm)
194
195 {
196         const char *conn, *serialcomm;
197
198         serial_conf_get(options, def_serialcomm, &conn, &serialcomm);
199
200         if (!conn)
201                 return NULL;
202
203         return sr_serial_dev_inst_new(conn, serialcomm);
204 }
205
206 static int serial_stream_check_buf(struct sr_serial_dev_inst *serial,
207                                    uint8_t *buf, size_t buflen,
208                                    size_t packet_size,
209                                    packet_valid_callback is_valid,
210                                    uint64_t timeout_ms, int baudrate)
211 {
212         size_t len, dropped;
213         int ret;
214
215         if ((ret = serial_open(serial, SERIAL_RDWR)) != SR_OK)
216                 return ret;
217
218         serial_flush(serial);
219
220         len = buflen;
221         ret = serial_stream_detect(serial, buf, &len, packet_size,
222                                    is_valid, timeout_ms, baudrate);
223
224         serial_close(serial);
225
226         if (ret != SR_OK)
227                 return ret;
228
229         /*
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.
235          */
236         dropped = len - packet_size;
237         if (dropped > 2 * packet_size)
238                 sr_warn("Had to drop too much data.");
239
240         return SR_OK;
241 }
242
243 static int serial_stream_check(struct sr_serial_dev_inst *serial,
244                                size_t packet_size,
245                                packet_valid_callback is_valid,
246                                uint64_t timeout_ms, int baudrate)
247 {
248         uint8_t buf[128];
249
250         return serial_stream_check_buf(serial, buf, sizeof(buf), packet_size,
251                                        is_valid, timeout_ms, baudrate);
252 }
253
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;
259 };
260
261 static int std_config_list(uint32_t key, GVariant **data,
262                            const struct std_opt_desc *d)
263 {
264         switch (key) {
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));
268                 break;
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));
272                 break;
273         default:
274                 return SR_ERR_NA;
275         }
276
277         return SR_OK;
278 }
279
280 static int send_config_update(struct sr_dev_inst *sdi, struct sr_config *cfg)
281 {
282         struct sr_datafeed_packet packet;
283         struct sr_datafeed_meta meta;
284
285         memset(&meta, 0, sizeof(meta));
286
287         packet.type = SR_DF_META;
288         packet.payload = &meta;
289
290         meta.config = g_slist_append(meta.config, cfg);
291
292         return sr_session_send(sdi, &packet);
293 }
294
295 static int send_config_update_key(struct sr_dev_inst *sdi, uint32_t key,
296                                   GVariant *var)
297 {
298         struct sr_config *cfg;
299         int ret;
300
301         cfg = sr_config_new(key, var);
302         if (!cfg)
303                 return SR_ERR;
304
305         ret = send_config_update(sdi, cfg);
306         sr_config_free(cfg);
307
308         return ret;
309 }
310
311 /*
312  * Cyrustek ES51919 LCR chipset host protocol.
313  *
314  * Public official documentation does not contain the protocol
315  * description, so this is all based on reverse engineering.
316  *
317  * Packet structure (17 bytes):
318  *
319  * 0x00: header1 ?? (0x00)
320  * 0x01: header2 ?? (0x0d)
321  *
322  * 0x02: flags
323  *         bit 0 = hold enabled
324  *         bit 1 = reference shown (in delta mode)
325  *         bit 2 = delta mode
326  *         bit 3 = calibration mode
327  *         bit 4 = sorting mode
328  *         bit 5 = LCR mode
329  *         bit 6 = auto mode
330  *         bit 7 = parallel measurement (vs. serial)
331  *
332  * 0x03: config
333  *         bit 0-4 = ??? (0x10)
334  *         bit 5-7 = test frequency
335  *                     0 = 100 Hz
336  *                     1 = 120 Hz
337  *                     2 = 1 kHz
338  *                     3 = 10 kHz
339  *                     4 = 100 kHz
340  *                     5 = 0 Hz (DC)
341  *
342  * 0x04: tolerance (sorting mode)
343  *         0 = not set
344  *         3 = +-0.25%
345  *         4 = +-0.5%
346  *         5 = +-1%
347  *         6 = +-2%
348  *         7 = +-5%
349  *         8 = +-10%
350  *         9 = +-20%
351  *        10 = -20+80%
352  *
353  * 0x05-0x09: primary measurement
354  *   0x05: measured quantity
355  *           1 = inductance
356  *           2 = capacitance
357  *           3 = resistance
358  *           4 = DC resistance
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)
363  *           bit 3-7 = unit
364  *                       0 = no unit
365  *                       1 = Ohm
366  *                       2 = kOhm
367  *                       3 = MOhm
368  *                       5 = uH
369  *                       6 = mH
370  *                       7 = H
371  *                       8 = kH
372  *                       9 = pF
373  *                       10 = nF
374  *                       11 = uF
375  *                       12 = mF
376  *                       13 = %
377  *                       14 = degree
378  *   0x09: measurement status
379  *           bit 0-3 = status
380  *                       0 = normal (measurement shown)
381  *                       1 = blank (nothing shown)
382  *                       2 = lines ("----")
383  *                       3 = outside limits ("OL")
384  *                       7 = pass ("PASS")
385  *                       8 = fail ("FAIL")
386  *                       9 = open ("OPEn")
387  *                      10 = shorted ("Srt")
388  *           bit 4-6 = ??? (maybe part of same field with 0-3)
389  *           bit 7   = ??? (some independent flag)
390  *
391  * 0x0a-0x0e: secondary measurement
392  *   0x0a: measured quantity
393  *           0 = none
394  *           1 = dissipation factor
395  *           2 = quality factor
396  *           3 = parallel AC resistance / ESR
397  *           4 = phase angle
398  *   0x0b-0x0e: like primary measurement
399  *
400  * 0x0f: footer1 (0x0d) ?
401  * 0x10: footer2 (0x0a) ?
402  */
403
404 #define PACKET_SIZE 17
405
406 static const double frequencies[] = {
407         100, 120, 1000, 10000, 100000, 0,
408 };
409
410 enum { MODEL_NONE, MODEL_PAR, MODEL_SER, MODEL_AUTO, };
411
412 static const char *const models[] = {
413         "NONE", "PARALLEL", "SERIES", "AUTO",
414 };
415
416 /** Private, per-device-instance driver context. */
417 struct dev_context {
418         /** The number of frames. */
419         struct dev_limit_counter frame_count;
420
421         /** The time limit counter. */
422         struct dev_time_counter time_count;
423
424         /** Data buffer. */
425         struct dev_buffer *buf;
426
427         /** The frequency of the test signal (index to frequencies[]). */
428         unsigned int freq;
429
430         /** Equivalent circuit model (index to models[]). */
431         unsigned int model;
432 };
433
434 static const uint8_t *pkt_to_buf(const uint8_t *pkt, int is_secondary)
435 {
436         return is_secondary ? pkt + 10 : pkt + 5;
437 }
438
439 static int parse_mq(const uint8_t *pkt, int is_secondary, int is_parallel)
440 {
441         const uint8_t *buf;
442
443         buf = pkt_to_buf(pkt, is_secondary);
444
445         switch (is_secondary << 8 | buf[0]) {
446         case 0x001:
447                 return is_parallel ?
448                         SR_MQ_PARALLEL_INDUCTANCE : SR_MQ_SERIES_INDUCTANCE;
449         case 0x002:
450                 return is_parallel ?
451                         SR_MQ_PARALLEL_CAPACITANCE : SR_MQ_SERIES_CAPACITANCE;
452         case 0x003:
453         case 0x103:
454                 return is_parallel ?
455                         SR_MQ_PARALLEL_RESISTANCE : SR_MQ_SERIES_RESISTANCE;
456         case 0x004:
457                 return SR_MQ_RESISTANCE;
458         case 0x100:
459                 return SR_MQ_DIFFERENCE;
460         case 0x101:
461                 return SR_MQ_DISSIPATION_FACTOR;
462         case 0x102:
463                 return SR_MQ_QUALITY_FACTOR;
464         case 0x104:
465                 return SR_MQ_PHASE_ANGLE;
466         }
467
468         sr_err("Unknown quantity 0x%03x.", is_secondary << 8 | buf[0]);
469
470         return 0;
471 }
472
473 static float parse_value(const uint8_t *buf, int *digits)
474 {
475         static const int exponents[] = {0, -1, -2, -3, -4, -5, -6, -7};
476         int exponent;
477         int16_t val;
478
479         exponent = exponents[buf[3] & 7];
480         *digits = -exponent;
481         val = (buf[1] << 8) | buf[2];
482         return (float)val * powf(10, exponent);
483 }
484
485 static void parse_measurement(const uint8_t *pkt, float *floatval,
486                               struct sr_datafeed_analog *analog,
487                               int is_secondary)
488 {
489         static const struct {
490                 int unit;
491                 int exponent;
492         } units[] = {
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    */
497                 { -1,                 0 },      /* ???     */
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  */
508         };
509         const uint8_t *buf;
510         int digits, exponent;
511         int state;
512
513         buf = pkt_to_buf(pkt, is_secondary);
514
515         analog->meaning->mq = 0;
516         analog->meaning->mqflags = 0;
517
518         state = buf[4] & 0xf;
519
520         if (state != 0 && state != 3)
521                 return;
522
523         if (pkt[2] & 0x18) {
524                 /* Calibration and Sorting modes not supported. */
525                 return;
526         }
527
528         if (!is_secondary) {
529                 if (pkt[2] & 0x01)
530                         analog->meaning->mqflags |= SR_MQFLAG_HOLD;
531                 if (pkt[2] & 0x02)
532                         analog->meaning->mqflags |= SR_MQFLAG_REFERENCE;
533         } else {
534                 if (pkt[2] & 0x04)
535                         analog->meaning->mqflags |= SR_MQFLAG_RELATIVE;
536         }
537
538         if ((analog->meaning->mq = parse_mq(pkt, is_secondary, pkt[2] & 0x80)) < 0)
539                 return;
540
541         if ((buf[3] >> 3) >= ARRAY_SIZE(units)) {
542                 sr_err("Unknown unit %u.", buf[3] >> 3);
543                 analog->meaning->mq = 0;
544                 return;
545         }
546
547         analog->meaning->unit = units[buf[3] >> 3].unit;
548
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;
554 }
555
556 static unsigned int parse_freq(const uint8_t *pkt)
557 {
558         unsigned int freq;
559
560         freq = pkt[3] >> 5;
561
562         if (freq >= ARRAY_SIZE(frequencies)) {
563                 sr_err("Unknown frequency %u.", freq);
564                 freq = ARRAY_SIZE(frequencies) - 1;
565         }
566
567         return freq;
568 }
569
570 static unsigned int parse_model(const uint8_t *pkt)
571 {
572         if (pkt[2] & 0x40)
573                 return MODEL_AUTO;
574         else if (parse_mq(pkt, 0, 0) == SR_MQ_RESISTANCE)
575                 return MODEL_NONE;
576         else if (pkt[2] & 0x80)
577                 return MODEL_PAR;
578         else
579                 return MODEL_SER;
580 }
581
582 static gboolean packet_valid(const uint8_t *pkt)
583 {
584         /*
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
589          * protocols.
590          */
591         if (pkt[15] == 0xd && pkt[16] == 0xa)
592                 return TRUE;
593
594         return FALSE;
595 }
596
597 static int do_config_update(struct sr_dev_inst *sdi, uint32_t key,
598                             GVariant *var)
599 {
600         return send_config_update_key(sdi, key, var);
601 }
602
603 static int send_freq_update(struct sr_dev_inst *sdi, unsigned int freq)
604 {
605         return do_config_update(sdi, SR_CONF_OUTPUT_FREQUENCY,
606                                 g_variant_new_double(frequencies[freq]));
607 }
608
609 static int send_model_update(struct sr_dev_inst *sdi, unsigned int model)
610 {
611         return do_config_update(sdi, SR_CONF_EQUIV_CIRCUIT_MODEL,
612                                 g_variant_new_string(models[model]));
613 }
614
615 static void handle_packet(struct sr_dev_inst *sdi, const uint8_t *pkt)
616 {
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;
623         unsigned int val;
624         float floatval;
625         gboolean frame;
626
627         devc = sdi->priv;
628
629         val = parse_freq(pkt);
630         if (val != devc->freq) {
631                 if (send_freq_update(sdi, val) == SR_OK)
632                         devc->freq = val;
633                 else
634                         return;
635         }
636
637         val = parse_model(pkt);
638         if (val != devc->model) {
639                 if (send_model_update(sdi, val) == SR_OK)
640                         devc->model = val;
641                 else
642                         return;
643         }
644
645         frame = FALSE;
646
647         sr_analog_init(&analog, &encoding, &meaning, &spec, 0);
648
649         analog.num_samples = 1;
650         analog.data = &floatval;
651
652         analog.meaning->channels = g_slist_append(NULL, sdi->channels->data);
653
654         parse_measurement(pkt, &floatval, &analog, 0);
655         if (analog.meaning->mq != 0) {
656                 if (!frame) {
657                         packet.type = SR_DF_FRAME_BEGIN;
658                         sr_session_send(sdi, &packet);
659                         frame = TRUE;
660                 }
661
662                 packet.type = SR_DF_ANALOG;
663                 packet.payload = &analog;
664
665                 sr_session_send(sdi, &packet);
666         }
667
668         g_slist_free(analog.meaning->channels);
669         analog.meaning->channels = g_slist_append(NULL, sdi->channels->next->data);
670
671         parse_measurement(pkt, &floatval, &analog, 1);
672         if (analog.meaning->mq != 0) {
673                 if (!frame) {
674                         packet.type = SR_DF_FRAME_BEGIN;
675                         sr_session_send(sdi, &packet);
676                         frame = TRUE;
677                 }
678
679                 packet.type = SR_DF_ANALOG;
680                 packet.payload = &analog;
681
682                 sr_session_send(sdi, &packet);
683         }
684
685         g_slist_free(analog.meaning->channels);
686
687         if (frame) {
688                 packet.type = SR_DF_FRAME_END;
689                 sr_session_send(sdi, &packet);
690                 dev_limit_counter_inc(&devc->frame_count);
691         }
692 }
693
694 static int handle_new_data(struct sr_dev_inst *sdi)
695 {
696         struct dev_context *devc;
697         uint8_t *pkt;
698         int ret;
699
700         devc = sdi->priv;
701
702         ret = dev_buffer_fill_serial(devc->buf, sdi);
703         if (ret < 0)
704                 return ret;
705
706         while ((pkt = dev_buffer_packet_find(devc->buf, packet_valid,
707                                              PACKET_SIZE)))
708                 handle_packet(sdi, pkt);
709
710         return SR_OK;
711 }
712
713 static int receive_data(int fd, int revents, void *cb_data)
714 {
715         struct sr_dev_inst *sdi;
716         struct dev_context *devc;
717
718         (void)fd;
719
720         if (!(sdi = cb_data))
721                 return TRUE;
722
723         if (!(devc = sdi->priv))
724                 return TRUE;
725
726         if (revents == G_IO_IN) {
727                 /* Serial data arrived. */
728                 handle_new_data(sdi);
729         }
730
731         if (dev_limit_counter_limit_reached(&devc->frame_count) ||
732             dev_time_limit_reached(&devc->time_count))
733                 sdi->driver->dev_acquisition_stop(sdi);
734
735         return TRUE;
736 }
737
738 static const char *const channel_names[] = { "P1", "P2" };
739
740 static int setup_channels(struct sr_dev_inst *sdi)
741 {
742         unsigned int i;
743         int ret;
744
745         ret = SR_ERR_BUG;
746
747         for (i = 0; i < ARRAY_SIZE(channel_names); i++)
748                 sr_channel_new(sdi, i, SR_CHANNEL_ANALOG, TRUE, channel_names[i]);
749
750         return ret;
751 }
752
753 SR_PRIV void es51919_serial_clean(void *priv)
754 {
755         struct dev_context *devc;
756
757         if (!(devc = priv))
758                 return;
759
760         dev_buffer_destroy(devc->buf);
761         g_free(devc);
762 }
763
764 SR_PRIV struct sr_dev_inst *es51919_serial_scan(GSList *options,
765                                                 const char *vendor,
766                                                 const char *model)
767 {
768         struct sr_serial_dev_inst *serial;
769         struct sr_dev_inst *sdi;
770         struct dev_context *devc;
771         int ret;
772
773         serial = NULL;
774         sdi = NULL;
775         devc = NULL;
776
777         if (!(serial = serial_dev_new(options, "9600/8n1/rts=1/dtr=1")))
778                 goto scan_cleanup;
779
780         ret = serial_stream_check(serial, PACKET_SIZE, packet_valid,
781                                   3000, 9600);
782         if (ret != SR_OK)
783                 goto scan_cleanup;
784
785         sr_info("Found device on port %s.", serial->port);
786
787         sdi = g_malloc0(sizeof(struct sr_dev_inst));
788         sdi->status = SR_ST_INACTIVE;
789         sdi->vendor = g_strdup(vendor);
790         sdi->model = g_strdup(model);
791         devc = g_malloc0(sizeof(struct dev_context));
792         devc->buf = dev_buffer_new(PACKET_SIZE * 8);
793         sdi->inst_type = SR_INST_SERIAL;
794         sdi->conn = serial;
795         sdi->priv = devc;
796
797         if (setup_channels(sdi) != SR_OK)
798                 goto scan_cleanup;
799
800         return sdi;
801
802 scan_cleanup:
803         es51919_serial_clean(devc);
804         if (sdi)
805                 sr_dev_inst_free(sdi);
806         if (serial)
807                 sr_serial_dev_inst_free(serial);
808
809         return NULL;
810 }
811
812 SR_PRIV int es51919_serial_config_get(uint32_t key, GVariant **data,
813                                       const struct sr_dev_inst *sdi,
814                                       const struct sr_channel_group *cg)
815 {
816         struct dev_context *devc;
817
818         (void)cg;
819
820         devc = sdi->priv;
821
822         switch (key) {
823         case SR_CONF_OUTPUT_FREQUENCY:
824                 *data = g_variant_new_double(frequencies[devc->freq]);
825                 break;
826         case SR_CONF_EQUIV_CIRCUIT_MODEL:
827                 *data = g_variant_new_string(models[devc->model]);
828                 break;
829         default:
830                 return SR_ERR_NA;
831         }
832
833         return SR_OK;
834 }
835
836 SR_PRIV int es51919_serial_config_set(uint32_t key, GVariant *data,
837                                       const struct sr_dev_inst *sdi,
838                                       const struct sr_channel_group *cg)
839 {
840         struct dev_context *devc;
841         uint64_t val;
842
843         (void)cg;
844
845         if (!(devc = sdi->priv))
846                 return SR_ERR_BUG;
847
848         switch (key) {
849         case SR_CONF_LIMIT_MSEC:
850                 val = g_variant_get_uint64(data);
851                 dev_time_limit_set(&devc->time_count, val);
852                 sr_dbg("Setting time limit to %" PRIu64 ".", val);
853                 break;
854         case SR_CONF_LIMIT_FRAMES:
855                 val = g_variant_get_uint64(data);
856                 dev_limit_counter_limit_set(&devc->frame_count, val);
857                 sr_dbg("Setting frame limit to %" PRIu64 ".", val);
858                 break;
859         default:
860                 sr_spew("%s: Unsupported key %u", __func__, key);
861                 return SR_ERR_NA;
862         }
863
864         return SR_OK;
865 }
866
867 static const uint32_t scanopts[] = {
868         SR_CONF_CONN,
869         SR_CONF_SERIALCOMM,
870 };
871
872 static const uint32_t devopts[] = {
873         SR_CONF_LCRMETER,
874         SR_CONF_CONTINUOUS,
875         SR_CONF_LIMIT_FRAMES | SR_CONF_SET,
876         SR_CONF_LIMIT_MSEC | SR_CONF_SET,
877         SR_CONF_OUTPUT_FREQUENCY | SR_CONF_GET | SR_CONF_LIST,
878         SR_CONF_EQUIV_CIRCUIT_MODEL | SR_CONF_GET | SR_CONF_LIST,
879 };
880
881 static const struct std_opt_desc opts = {
882         scanopts, ARRAY_SIZE(scanopts),
883         devopts, ARRAY_SIZE(devopts),
884 };
885
886 SR_PRIV int es51919_serial_config_list(uint32_t key, GVariant **data,
887                                        const struct sr_dev_inst *sdi,
888                                        const struct sr_channel_group *cg)
889 {
890         (void)sdi;
891         (void)cg;
892
893         if (std_config_list(key, data, &opts) == SR_OK)
894                 return SR_OK;
895
896         switch (key) {
897         case SR_CONF_OUTPUT_FREQUENCY:
898                 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_DOUBLE,
899                         frequencies, ARRAY_SIZE(frequencies), sizeof(double));
900                 break;
901         case SR_CONF_EQUIV_CIRCUIT_MODEL:
902                 *data = g_variant_new_strv(models, ARRAY_SIZE(models));
903                 break;
904         default:
905                 return SR_ERR_NA;
906         }
907
908         return SR_OK;
909 }
910
911 SR_PRIV int es51919_serial_acquisition_start(const struct sr_dev_inst *sdi)
912 {
913         struct dev_context *devc;
914         struct sr_serial_dev_inst *serial;
915
916         if (sdi->status != SR_ST_ACTIVE)
917                 return SR_ERR_DEV_CLOSED;
918
919         if (!(devc = sdi->priv))
920                 return SR_ERR_BUG;
921
922         dev_limit_counter_start(&devc->frame_count);
923         dev_time_counter_start(&devc->time_count);
924
925         std_session_send_df_header(sdi);
926
927         /* Poll every 50ms, or whenever some data comes in. */
928         serial = sdi->conn;
929         serial_source_add(sdi->session, serial, G_IO_IN, 50,
930                           receive_data, (void *)sdi);
931
932         return SR_OK;
933 }