]> sigrok.org Git - libsigrok.git/blob - src/hardware/kingst-la2016/api.c
5a4ee6fa2ad48add223df0057ac6b1aefc4ebf9d
[libsigrok.git] / src / hardware / kingst-la2016 / api.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2022 Gerhard Sittig <gerhard.sittig@gmx.net>
5  * Copyright (C) 2020 Florian Schmidt <schmidt_florian@gmx.de>
6  * Copyright (C) 2013 Marcus Comstedt <marcus@mc.pp.se>
7  * Copyright (C) 2013 Bert Vermeulen <bert@biot.com>
8  * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  */
23
24 /*
25  * This driver implementation initially was derived from the
26  * src/hardware/saleae-logic16/ source code.
27  */
28
29 #include <config.h>
30
31 #include <libsigrok/libsigrok.h>
32 #include <string.h>
33
34 #include "libsigrok-internal.h"
35 #include "protocol.h"
36
37 static const uint32_t scanopts[] = {
38         SR_CONF_CONN,
39         SR_CONF_PROBE_NAMES,
40 };
41
42 static const uint32_t drvopts[] = {
43         SR_CONF_LOGIC_ANALYZER,
44         SR_CONF_SIGNAL_GENERATOR,
45 };
46
47 static const uint32_t devopts[] = {
48         SR_CONF_CONN | SR_CONF_GET,
49         SR_CONF_SAMPLERATE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
50         SR_CONF_LIMIT_SAMPLES | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
51         SR_CONF_LIMIT_MSEC | SR_CONF_GET | SR_CONF_SET,
52 #if WITH_THRESHOLD_DEVCFG
53         SR_CONF_VOLTAGE_THRESHOLD | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
54 #endif
55         SR_CONF_TRIGGER_MATCH | SR_CONF_LIST,
56         SR_CONF_CAPTURE_RATIO | SR_CONF_GET | SR_CONF_SET,
57         SR_CONF_CONTINUOUS | SR_CONF_GET | SR_CONF_SET,
58 };
59
60 static const uint32_t devopts_cg_logic[] = {
61 #if !WITH_THRESHOLD_DEVCFG
62         SR_CONF_VOLTAGE_THRESHOLD | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
63 #endif
64 };
65
66 static const uint32_t devopts_cg_pwm[] = {
67         SR_CONF_ENABLED | SR_CONF_GET | SR_CONF_SET,
68         SR_CONF_OUTPUT_FREQUENCY | SR_CONF_GET | SR_CONF_SET,
69         SR_CONF_DUTY_CYCLE | SR_CONF_GET | SR_CONF_SET,
70 };
71
72 static const int32_t trigger_matches[] = {
73         SR_TRIGGER_ZERO,
74         SR_TRIGGER_ONE,
75         SR_TRIGGER_RISING,
76         SR_TRIGGER_FALLING,
77 };
78
79 static const char *channel_names_logic[] = {
80         "CH0", "CH1", "CH2", "CH3", "CH4", "CH5", "CH6", "CH7",
81         "CH8", "CH9", "CH10", "CH11", "CH12", "CH13", "CH14", "CH15",
82         "CH16", "CH17", "CH18", "CH19", "CH20", "CH21", "CH22", "CH23",
83         "CH24", "CH25", "CH26", "CH27", "CH28", "CH29", "CH30", "CH31",
84 };
85
86 static const char *channel_names_pwm[] = {
87         "PWM1", "PWM2",
88 };
89
90 /*
91  * The devices have an upper samplerate limit of 100/200/500 MHz each.
92  * But their hardware uses different base clocks (100/200/800MHz, this
93  * is _not_ a typo) and a 16bit divider. Which results in per-model ranges
94  * of supported rates which not only differ in the upper boundary, but
95  * also at the lower boundary. It's assumed that the 10kHz rate is not
96  * useful enough to provide by all means. Starting at 20kHz for all models
97  * simplfies the implementation of the config API routines, and eliminates
98  * redundancy in these samplerates tables.
99  *
100  * Streaming mode is constrained by the channel count and samplerate
101  * product (the bits per second which need to travel the USB connection
102  * while the acquisition is executing). Because streaming mode does not
103  * compress the capture data, a later implementation may desire a finer
104  * resolution. For now let's just stick with the 1/2/5 steps.
105  */
106
107 static const uint64_t rates_500mhz[] = {
108         SR_KHZ(20),
109         SR_KHZ(50),
110         SR_KHZ(100),
111         SR_KHZ(200),
112         SR_KHZ(500),
113         SR_MHZ(1),
114         SR_MHZ(2),
115         SR_MHZ(5),
116         SR_MHZ(10),
117         SR_MHZ(20),
118         SR_MHZ(50),
119         SR_MHZ(100),
120         SR_MHZ(200),
121         SR_MHZ(500),
122 };
123
124 static const uint64_t rates_200mhz[] = {
125         SR_KHZ(20),
126         SR_KHZ(50),
127         SR_KHZ(100),
128         SR_KHZ(200),
129         SR_KHZ(500),
130         SR_MHZ(1),
131         SR_MHZ(2),
132         SR_MHZ(5),
133         SR_MHZ(10),
134         SR_MHZ(20),
135         SR_MHZ(50),
136         SR_MHZ(100),
137         SR_MHZ(200),
138 };
139
140 static const uint64_t rates_100mhz[] = {
141         SR_KHZ(20),
142         SR_KHZ(50),
143         SR_KHZ(100),
144         SR_KHZ(200),
145         SR_KHZ(500),
146         SR_MHZ(1),
147         SR_MHZ(2),
148         SR_MHZ(5),
149         SR_MHZ(10),
150         SR_MHZ(20),
151         SR_MHZ(50),
152         SR_MHZ(100),
153 };
154
155 /*
156  * Only list a few discrete voltages, to form a useful set which covers
157  * most logic families. Too many choices can make some applications use
158  * a slider again. Which may lack a scale for the current value, and
159  * leave users without feedback what the currently used value might be.
160  */
161 static const double threshold_ranges[][2] = {
162         { 0.4, 0.4, },
163         { 0.6, 0.6, },
164         { 0.9, 0.9, },
165         { 1.2, 1.2, },
166         { 1.4, 1.4, }, /* Default, 1.4V, index 4. */
167         { 2.0, 2.0, },
168         { 2.5, 2.5, },
169         { 4.0, 4.0, },
170 };
171 #define LOGIC_THRESHOLD_IDX_DFLT        4
172
173 static double threshold_voltage(const struct sr_dev_inst *sdi, double *high)
174 {
175         struct dev_context *devc;
176         size_t idx;
177         double voltage;
178
179         devc = sdi->priv;
180         idx = devc->threshold_voltage_idx;
181         voltage = threshold_ranges[idx][0];
182         if (high)
183                 *high = threshold_ranges[idx][1];
184
185         return voltage;
186 }
187
188 /* Convenience. Release an allocated devc from error paths. */
189 static void kingst_la2016_free_devc(struct dev_context *devc)
190 {
191         if (!devc)
192                 return;
193         g_free(devc->mcu_firmware);
194         g_free(devc->fpga_bitstream);
195         g_free(devc);
196 }
197
198 /* Convenience. Release an allocated sdi from error paths. */
199 static void kingst_la2016_free_sdi(struct sr_dev_inst *sdi)
200 {
201         struct sr_usb_dev_inst *usb;
202         struct dev_context *devc;
203
204         if (!sdi)
205                 return;
206
207         usb = sdi->conn;
208         if (usb && usb->devhdl)
209                 sr_usb_close(usb);
210         sr_usb_dev_inst_free(usb);
211
212         devc = sdi->priv;
213         kingst_la2016_free_devc(devc);
214
215         sr_dev_inst_free(sdi);
216 }
217
218 /* Convenience. Open a USB device (including claiming an interface). */
219 static int la2016_open_usb(struct sr_usb_dev_inst *usb,
220         libusb_device *dev, gboolean show_message)
221 {
222         int ret;
223
224         ret = libusb_open(dev, &usb->devhdl);
225         if (ret != 0) {
226                 if (show_message) {
227                         sr_err("Cannot open device: %s.",
228                                 libusb_error_name(ret));
229                 }
230                 return SR_ERR_IO;
231         }
232
233         if (usb->address == 0xff) {
234                 /*
235                  * First encounter after firmware upload.
236                  * Grab current address after enumeration.
237                  */
238                 usb->address = libusb_get_device_address(dev);
239         }
240
241         ret = libusb_claim_interface(usb->devhdl, USB_INTERFACE);
242         if (ret == LIBUSB_ERROR_BUSY) {
243                 sr_err("Cannot claim USB interface. Another program or driver using it?");
244                 return SR_ERR_IO;
245         } else if (ret == LIBUSB_ERROR_NO_DEVICE) {
246                 sr_err("Device has been disconnected.");
247                 return SR_ERR_IO;
248         } else if (ret != 0) {
249                 sr_err("Cannot claim USB interface: %s.",
250                         libusb_error_name(ret));
251                 return SR_ERR_IO;
252         }
253
254         return SR_OK;
255 }
256
257 /* Convenience. Close an opened USB device (and release the interface). */
258 static void la2016_close_usb(struct sr_usb_dev_inst *usb)
259 {
260
261         if (!usb)
262                 return;
263
264         if (usb->devhdl) {
265                 libusb_release_interface(usb->devhdl, USB_INTERFACE);
266                 libusb_close(usb->devhdl);
267                 usb->devhdl = NULL;
268         }
269 }
270
271 /* Communicate to an USB device to identify the Kingst LA model. */
272 static int la2016_identify_read(struct sr_dev_inst *sdi,
273         struct sr_usb_dev_inst *usb, libusb_device *dev,
274         gboolean show_message)
275 {
276         int ret;
277
278         ret = la2016_open_usb(usb, dev, show_message);
279         if (ret != SR_OK) {
280                 if (show_message)
281                         sr_err("Cannot communicate to MCU firmware.");
282                 return ret;
283         }
284
285         /*
286          * Also complete the hardware configuration (FPGA bitstream)
287          * when MCU firmware communication became operational. Either
288          * failure is considered fatal when probing for the device.
289          */
290         ret = la2016_identify_device(sdi, show_message);
291         if (ret == SR_OK) {
292                 ret = la2016_init_hardware(sdi);
293         }
294
295         la2016_close_usb(usb);
296
297         return ret;
298 }
299
300 /* Find given conn_id in another USB enum. Identify Kingst LA model. */
301 static int la2016_identify_enum(struct sr_dev_inst *sdi)
302 {
303         struct sr_dev_driver *di;
304         struct drv_context *drvc;
305         struct sr_context *ctx;
306         libusb_device **devlist, *dev;
307         struct libusb_device_descriptor des;
308         int ret, id_ret;
309         size_t device_count, dev_idx;
310         char conn_id[64];
311
312         di = sdi->driver;
313         drvc = di->context;
314         ctx = drvc->sr_ctx;;
315
316         ret = libusb_get_device_list(ctx->libusb_ctx, &devlist);
317         if (ret < 0)
318                 return SR_ERR_IO;
319         device_count = ret;
320         if (!device_count)
321                 return SR_ERR_IO;
322         id_ret = SR_ERR_IO;
323         for (dev_idx = 0; dev_idx < device_count; dev_idx++) {
324                 dev = devlist[dev_idx];
325                 libusb_get_device_descriptor(dev, &des);
326                 if (des.idVendor != LA2016_VID || des.idProduct != LA2016_PID)
327                         continue;
328                 if (des.iProduct != LA2016_IPRODUCT_INDEX)
329                         continue;
330                 ret = usb_get_port_path(dev, conn_id, sizeof(conn_id));
331                 if (ret < 0)
332                         continue;
333                 if (strcmp(sdi->connection_id, conn_id) != 0)
334                         continue;
335                 id_ret = la2016_identify_read(sdi, sdi->conn, dev, FALSE);
336                 break;
337         }
338         libusb_free_device_list(devlist, 1);
339
340         return id_ret;
341 }
342
343 /* Wait for a device to re-appear after firmware upload. */
344 static int la2016_identify_wait(struct sr_dev_inst *sdi)
345 {
346         struct dev_context *devc;
347         uint64_t reset_done, now, elapsed_ms;
348         int ret;
349
350         devc = sdi->priv;
351
352         sr_info("Waiting for device to reset after firmware upload.");
353         now = g_get_monotonic_time();
354         reset_done = devc->fw_uploaded + RENUM_GONE_DELAY_MS * 1000;
355         if (now < reset_done)
356                 g_usleep(reset_done - now);
357         do {
358                 now = g_get_monotonic_time();
359                 elapsed_ms = (now - devc->fw_uploaded) / 1000;
360                 sr_spew("Waited %" PRIu64 "ms.", elapsed_ms);
361                 ret = la2016_identify_enum(sdi);
362                 if (ret == SR_OK) {
363                         devc->fw_uploaded = 0;
364                         break;
365                 }
366                 g_usleep(RENUM_POLL_INTERVAL_MS * 1000);
367         } while (elapsed_ms < RENUM_CHECK_PERIOD_MS);
368         if (ret != SR_OK) {
369                 sr_err("Device failed to re-enumerate.");
370                 return ret;
371         }
372         sr_info("Device came back after %" PRIi64 "ms.", elapsed_ms);
373
374         return SR_OK;
375 }
376
377 /*
378  * Open given conn_id from another USB enum. Used by dev_open(). Similar
379  * to, and should be kept in sync with la2016_identify_enum().
380  */
381 static int la2016_open_enum(struct sr_dev_inst *sdi)
382 {
383         struct sr_dev_driver *di;
384         struct drv_context *drvc;
385         struct sr_context *ctx;
386         libusb_device **devlist, *dev;
387         struct libusb_device_descriptor des;
388         int ret, open_ret;
389         size_t device_count, dev_idx;
390         char conn_id[64];
391
392         di = sdi->driver;
393         drvc = di->context;
394         ctx = drvc->sr_ctx;;
395
396         ret = libusb_get_device_list(ctx->libusb_ctx, &devlist);
397         if (ret < 0)
398                 return SR_ERR_IO;
399         device_count = ret;
400         if (!device_count)
401                 return SR_ERR_IO;
402         open_ret = SR_ERR_IO;
403         for (dev_idx = 0; dev_idx < device_count; dev_idx++) {
404                 dev = devlist[dev_idx];
405                 libusb_get_device_descriptor(dev, &des);
406                 if (des.idVendor != LA2016_VID || des.idProduct != LA2016_PID)
407                         continue;
408                 if (des.iProduct != LA2016_IPRODUCT_INDEX)
409                         continue;
410                 ret = usb_get_port_path(dev, conn_id, sizeof(conn_id));
411                 if (ret < 0)
412                         continue;
413                 if (strcmp(sdi->connection_id, conn_id) != 0)
414                         continue;
415                 open_ret = la2016_open_usb(sdi->conn, dev, TRUE);
416                 break;
417         }
418         libusb_free_device_list(devlist, 1);
419
420         return open_ret;
421 }
422
423 static GSList *scan(struct sr_dev_driver *di, GSList *options)
424 {
425         struct drv_context *drvc;
426         struct sr_context *ctx;
427         struct dev_context *devc;
428         struct sr_dev_inst *sdi;
429         struct sr_usb_dev_inst *usb;
430         struct sr_config *src;
431         GSList *l;
432         GSList *devices, *found_devices, *renum_devices;
433         GSList *conn_devices;
434         struct libusb_device_descriptor des;
435         libusb_device **devlist, *dev;
436         size_t dev_count, dev_idx, ch_idx;
437         uint8_t bus, addr;
438         uint16_t pid;
439         const char *conn;
440         const char *probe_names;
441         char conn_id[64];
442         int ret;
443         size_t ch_off, ch_max;
444         struct sr_channel *ch;
445         struct sr_channel_group *cg;
446
447         drvc = di->context;
448         ctx = drvc->sr_ctx;;
449
450         conn = NULL;
451         conn_devices = NULL;
452         probe_names = NULL;
453         for (l = options; l; l = l->next) {
454                 src = l->data;
455                 switch (src->key) {
456                 case SR_CONF_CONN:
457                         conn = g_variant_get_string(src->data, NULL);
458                         break;
459                 case SR_CONF_PROBE_NAMES:
460                         probe_names = g_variant_get_string(src->data, NULL);
461                         break;
462                 }
463         }
464         if (conn)
465                 conn_devices = sr_usb_find(ctx->libusb_ctx, conn);
466         if (conn && !conn_devices) {
467                 sr_err("Cannot find the specified connection '%s'.", conn);
468                 return NULL;
469         }
470
471         /*
472          * Find all LA2016 devices, optionally upload firmware to them.
473          * Defer completion of sdi/devc creation until all (selected)
474          * devices were found in a usable state, and their models got
475          * identified which affect their feature set. It appears that
476          * we cannot communicate to the device within the same USB enum
477          * cycle, needs another USB enumeration after firmware upload.
478          */
479         devices = NULL;
480         found_devices = NULL;
481         renum_devices = NULL;
482         ret = libusb_get_device_list(ctx->libusb_ctx, &devlist);
483         if (ret < 0) {
484                 sr_err("Cannot get device list: %s.", libusb_error_name(ret));
485                 return devices;
486         }
487         dev_count = ret;
488         for (dev_idx = 0; dev_idx < dev_count; dev_idx++) {
489                 dev = devlist[dev_idx];
490                 bus = libusb_get_bus_number(dev);
491                 addr = libusb_get_device_address(dev);
492
493                 /* Filter by connection when externally specified. */
494                 for (l = conn_devices; l; l = l->next) {
495                         usb = l->data;
496                         if (usb->bus == bus && usb->address == addr)
497                                 break;
498                 }
499                 if (conn_devices && !l) {
500                         sr_spew("Bus %hhu, addr %hhu do not match specified filter.",
501                                 bus, addr);
502                         continue;
503                 }
504
505                 /* Check USB VID:PID. Get the connection string. */
506                 libusb_get_device_descriptor(dev, &des);
507                 if (des.idVendor != LA2016_VID || des.idProduct != LA2016_PID)
508                         continue;
509                 pid = des.idProduct;
510                 ret = usb_get_port_path(dev, conn_id, sizeof(conn_id));
511                 if (ret < 0)
512                         continue;
513                 sr_dbg("USB enum found %04x:%04x at path %s, %d.%d.",
514                         des.idVendor, des.idProduct, conn_id, bus, addr);
515                 usb = sr_usb_dev_inst_new(bus, addr, NULL);
516
517                 sdi = g_malloc0(sizeof(*sdi));
518                 sdi->driver = di;
519                 sdi->status = SR_ST_INITIALIZING;
520                 sdi->inst_type = SR_INST_USB;
521                 sdi->connection_id = g_strdup(conn_id);
522                 sdi->conn = usb;
523
524                 devc = g_malloc0(sizeof(*devc));
525                 sdi->priv = devc;
526
527                 /*
528                  * Load MCU firmware if it is currently missing. Which
529                  * makes the device disappear and renumerate in USB.
530                  * We need to come back another time to communicate to
531                  * this device.
532                  */
533                 devc->fw_uploaded = 0;
534                 devc->usb_pid = pid;
535                 if (des.iProduct != LA2016_IPRODUCT_INDEX) {
536                         sr_info("Uploading MCU firmware to '%s'.", conn_id);
537                         ret = la2016_upload_firmware(sdi, ctx, dev, FALSE);
538                         if (ret != SR_OK) {
539                                 sr_err("MCU firmware upload failed.");
540                                 kingst_la2016_free_sdi(sdi);
541                                 continue;
542                         }
543                         devc->fw_uploaded = g_get_monotonic_time();
544                         usb->address = 0xff;
545                         renum_devices = g_slist_append(renum_devices, sdi);
546                         continue;
547                 } else {
548                         ret = la2016_upload_firmware(sdi, NULL, NULL, TRUE);
549                         if (ret != SR_OK) {
550                                 sr_err("MCU firmware filename check failed.");
551                                 kingst_la2016_free_sdi(sdi);
552                                 continue;
553                         }
554                 }
555
556                 /*
557                  * Communicate to the MCU firmware to access EEPROM data
558                  * which lets us identify the device type. Then stop, to
559                  * share remaining sdi/devc creation with those devices
560                  * which had their MCU firmware uploaded above and which
561                  * get revisited later.
562                  */
563                 ret = la2016_identify_read(sdi, usb, dev, TRUE);
564                 if (ret != SR_OK || !devc->model) {
565                         sr_err("Unknown or unsupported device type.");
566                         kingst_la2016_free_sdi(sdi);
567                         continue;
568                 }
569                 found_devices = g_slist_append(found_devices, sdi);
570         }
571         libusb_free_device_list(devlist, 1);
572         g_slist_free_full(conn_devices, sr_usb_dev_inst_free_cb);
573
574         /*
575          * Wait for devices to re-appear after firmware upload. Append
576          * the yet unidentified device to the list of found devices, or
577          * release the previously allocated sdi/devc.
578          */
579         for (l = renum_devices; l; l = l->next) {
580                 sdi = l->data;
581                 devc = sdi->priv;
582                 ret = la2016_identify_wait(sdi);
583                 if (ret != SR_OK || !devc->model) {
584                         sr_dbg("Skipping unusable '%s'.", sdi->connection_id);
585                         kingst_la2016_free_sdi(sdi);
586                         continue;
587                 }
588                 found_devices = g_slist_append(found_devices, sdi);
589         }
590         g_slist_free(renum_devices);
591
592         /*
593          * All found devices got identified, their type is known here.
594          * Complete the sdi/devc creation. Assign default settings
595          * because the vendor firmware would not let us read back the
596          * previously written configuration.
597          */
598         for (l = found_devices; l; l = l->next) {
599                 sdi = l->data;
600                 devc = sdi->priv;
601
602                 sdi->vendor = g_strdup("Kingst");
603                 sdi->model = g_strdup(devc->model->name);
604                 ch_off = 0;
605
606                 /* Create the "Logic" channel group. */
607                 ch_max = ARRAY_SIZE(channel_names_logic);
608                 if (ch_max > devc->model->channel_count)
609                         ch_max = devc->model->channel_count;
610                 devc->channel_names_logic = sr_parse_probe_names(probe_names,
611                         channel_names_logic, ch_max, ch_max, &ch_max);
612                 cg = sr_channel_group_new(sdi, "Logic", NULL);
613                 devc->cg_logic = cg;
614                 for (ch_idx = 0; ch_idx < ch_max; ch_idx++) {
615                         ch = sr_channel_new(sdi, ch_off,
616                                 SR_CHANNEL_LOGIC, TRUE,
617                                 devc->channel_names_logic[ch_idx]);
618                         ch_off++;
619                         cg->channels = g_slist_append(cg->channels, ch);
620                 }
621
622                 /* Create the "PWMx" channel groups. */
623                 ch_max = ARRAY_SIZE(channel_names_pwm);
624                 for (ch_idx = 0; ch_idx < ch_max; ch_idx++) {
625                         const char *name;
626                         name = channel_names_pwm[ch_idx];
627                         cg = sr_channel_group_new(sdi, name, NULL);
628                         if (!devc->cg_pwm)
629                                 devc->cg_pwm = cg;
630                         ch = sr_channel_new(sdi, ch_off,
631                                 SR_CHANNEL_ANALOG, FALSE, name);
632                         ch_off++;
633                         cg->channels = g_slist_append(cg->channels, ch);
634                 }
635
636                 /*
637                  * Ideally we'd get the previous configuration from the
638                  * hardware, but this device is write-only. So we have
639                  * to assign a fixed set of initial configuration values.
640                  */
641                 sr_sw_limits_init(&devc->sw_limits);
642                 devc->sw_limits.limit_samples = 0;
643                 devc->capture_ratio = 50;
644                 devc->samplerate = devc->model->samplerate;
645                 if (!devc->model->memory_bits)
646                         devc->continuous = TRUE;
647                 devc->threshold_voltage_idx = LOGIC_THRESHOLD_IDX_DFLT;
648                 if  (ARRAY_SIZE(devc->pwm_setting) >= 1) {
649                         devc->pwm_setting[0].enabled = FALSE;
650                         devc->pwm_setting[0].freq = SR_KHZ(1);
651                         devc->pwm_setting[0].duty = 50;
652                 }
653                 if  (ARRAY_SIZE(devc->pwm_setting) >= 2) {
654                         devc->pwm_setting[1].enabled = FALSE;
655                         devc->pwm_setting[1].freq = SR_KHZ(100);
656                         devc->pwm_setting[1].duty = 50;
657                 }
658
659                 sdi->status = SR_ST_INACTIVE;
660                 devices = g_slist_append(devices, sdi);
661         }
662         g_slist_free(found_devices);
663
664         return std_scan_complete(di, devices);
665 }
666
667 static int dev_open(struct sr_dev_inst *sdi)
668 {
669         struct dev_context *devc;
670         int ret;
671         size_t ch;
672
673         devc = sdi->priv;
674
675         ret = la2016_open_enum(sdi);
676         if (ret != SR_OK) {
677                 sr_err("Cannot open device.");
678                 return ret;
679         }
680
681         /* Send most recent PWM configuration to the device. */
682         for (ch = 0; ch < ARRAY_SIZE(devc->pwm_setting); ch++) {
683                 ret = la2016_write_pwm_config(sdi, ch);
684                 if (ret != SR_OK)
685                         return ret;
686         }
687
688         return SR_OK;
689 }
690
691 static int dev_close(struct sr_dev_inst *sdi)
692 {
693         struct sr_usb_dev_inst *usb;
694
695         usb = sdi->conn;
696
697         if (!usb->devhdl)
698                 return SR_ERR_BUG;
699
700         la2016_release_resources(sdi);
701
702         if (WITH_DEINIT_IN_CLOSE)
703                 la2016_deinit_hardware(sdi);
704
705         sr_info("Closing device on %d.%d (logical) / %s (physical) interface %d.",
706                 usb->bus, usb->address, sdi->connection_id, USB_INTERFACE);
707         la2016_close_usb(sdi->conn);
708
709         return SR_OK;
710 }
711
712 /* Config API helper. Get type and index of a channel group. */
713 static int get_cg_index(const struct sr_dev_inst *sdi,
714         const struct sr_channel_group *cg,
715         int *type, size_t *logic, size_t *analog)
716 {
717         struct dev_context *devc;
718         GSList *l;
719         size_t idx;
720
721         /* Preset return values. */
722         if (type)
723                 *type = 0;
724         if (logic)
725                 *logic = 0;
726         if (analog)
727                 *analog = 0;
728
729         /* Start categorizing the received cg. */
730         if (!sdi)
731                 return SR_ERR_ARG;
732         devc = sdi->priv;
733         if (!cg)
734                 return SR_OK;
735         l = sdi->channel_groups;
736
737         /* First sdi->channelgroups item is "Logic". */
738         if (!l)
739                 return SR_ERR_BUG;
740         if (cg == l->data) {
741                 if (type)
742                         *type = SR_CHANNEL_LOGIC;
743                 if (logic)
744                         *logic = 0;
745                 return SR_OK;
746         }
747         l = l->next;
748
749         /* Next sdi->channelgroups items are "PWMx". */
750         idx = 0;
751         while (l && l->data != cg) {
752                 idx++;
753                 l = l->next;
754         }
755         if (l && idx < ARRAY_SIZE(devc->pwm_setting)) {
756                 if (type)
757                         *type = SR_CHANNEL_ANALOG;
758                 if (analog)
759                         *analog = idx;
760                 return SR_OK;
761         }
762
763         return SR_ERR_ARG;
764 }
765
766 static int config_get(uint32_t key, GVariant **data,
767         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
768 {
769         struct dev_context *devc;
770         int ret, cg_type;
771         size_t logic_idx, analog_idx;
772         struct pwm_setting *pwm;
773         struct sr_usb_dev_inst *usb;
774         double voltage, rounded;
775
776         (void)rounded;
777         (void)voltage;
778
779         if (!sdi)
780                 return SR_ERR_ARG;
781         devc = sdi->priv;
782
783         /* Check for types (and index) of channel groups. */
784         ret = get_cg_index(sdi, cg, &cg_type, &logic_idx, &analog_idx);
785         if (cg && ret != SR_OK)
786                 return SR_ERR_ARG;
787
788         /* Handle requests for the "Logic" channel group. */
789         if (cg && cg_type == SR_CHANNEL_LOGIC) {
790                 switch (key) {
791 #if !WITH_THRESHOLD_DEVCFG
792                 case SR_CONF_VOLTAGE_THRESHOLD:
793                         voltage = threshold_voltage(sdi, NULL);
794                         *data = std_gvar_tuple_double(voltage, voltage);
795                         break;
796 #endif /* WITH_THRESHOLD_DEVCFG */
797                 default:
798                         return SR_ERR_NA;
799                 }
800                 return SR_OK;
801         }
802
803         /* Handle requests for the "PWMx" channel groups. */
804         if (cg && cg_type == SR_CHANNEL_ANALOG) {
805                 pwm = &devc->pwm_setting[analog_idx];
806                 switch (key) {
807                 case SR_CONF_ENABLED:
808                         *data = g_variant_new_boolean(pwm->enabled);
809                         break;
810                 case SR_CONF_OUTPUT_FREQUENCY:
811                         *data = g_variant_new_double(pwm->freq);
812                         break;
813                 case SR_CONF_DUTY_CYCLE:
814                         *data = g_variant_new_double(pwm->duty);
815                         break;
816                 default:
817                         return SR_ERR_NA;
818                 }
819                 return SR_OK;
820         }
821
822         switch (key) {
823         case SR_CONF_CONN:
824                 usb = sdi->conn;
825                 *data = g_variant_new_printf("%d.%d", usb->bus, usb->address);
826                 break;
827         case SR_CONF_SAMPLERATE:
828                 *data = g_variant_new_uint64(devc->samplerate);
829                 break;
830         case SR_CONF_LIMIT_SAMPLES:
831         case SR_CONF_LIMIT_MSEC:
832                 return sr_sw_limits_config_get(&devc->sw_limits, key, data);
833         case SR_CONF_CAPTURE_RATIO:
834                 *data = g_variant_new_uint64(devc->capture_ratio);
835                 break;
836 #if WITH_THRESHOLD_DEVCFG
837         case SR_CONF_VOLTAGE_THRESHOLD:
838                 voltage = threshold_voltage(sdi, NULL);
839                 *data = std_gvar_tuple_double(voltage, voltage);
840                 break;
841 #endif /* WITH_THRESHOLD_DEVCFG */
842         case SR_CONF_CONTINUOUS:
843                 *data = g_variant_new_boolean(devc->continuous);
844                 break;
845         default:
846                 return SR_ERR_NA;
847         }
848
849         return SR_OK;
850 }
851
852 static int config_set(uint32_t key, GVariant *data,
853         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
854 {
855         struct dev_context *devc;
856         int ret, cg_type;
857         size_t logic_idx, analog_idx;
858         struct pwm_setting *pwm;
859         double value_f;
860         int idx;
861         gboolean on;
862
863         devc = sdi->priv;
864
865         /* Check for types (and index) of channel groups. */
866         ret = get_cg_index(sdi, cg, &cg_type, &logic_idx, &analog_idx);
867         if (cg && ret != SR_OK)
868                 return SR_ERR_ARG;
869
870         /* Handle requests for the "Logic" channel group. */
871         if (cg && cg_type == SR_CHANNEL_LOGIC) {
872                 switch (key) {
873 #if !WITH_THRESHOLD_DEVCFG
874                 case SR_CONF_LOGIC_THRESHOLD:
875                         idx = std_double_tuple_idx(data,
876                                 ARRAY_AND_SIZE(threshold_ranges));
877                         if (idx < 0)
878                                 return SR_ERR_ARG;
879                         devc->threshold_voltage_idx = idx;
880                         break;
881 #endif /* WITH_THRESHOLD_DEVCFG */
882                 default:
883                         return SR_ERR_NA;
884                 }
885                 return SR_OK;
886         }
887
888         /* Handle requests for the "PWMx" channel groups. */
889         if (cg && cg_type == SR_CHANNEL_ANALOG) {
890                 pwm = &devc->pwm_setting[analog_idx];
891                 switch (key) {
892                 case SR_CONF_ENABLED:
893                         pwm->enabled = g_variant_get_boolean(data);
894                         ret = la2016_write_pwm_config(sdi, analog_idx);
895                         if (ret != SR_OK)
896                                 return ret;
897                         break;
898                 case SR_CONF_OUTPUT_FREQUENCY:
899                         value_f = g_variant_get_double(data);
900                         if (value_f <= 0.0 || value_f > MAX_PWM_FREQ)
901                                 return SR_ERR_ARG;
902                         pwm->freq = value_f;
903                         ret = la2016_write_pwm_config(sdi, analog_idx);
904                         if (ret != SR_OK)
905                                 return ret;
906                         break;
907                 case SR_CONF_DUTY_CYCLE:
908                         value_f = g_variant_get_double(data);
909                         if (value_f <= 0.0 || value_f > 100.0)
910                                 return SR_ERR_ARG;
911                         pwm->duty = value_f;
912                         ret = la2016_write_pwm_config(sdi, analog_idx);
913                         if (ret != SR_OK)
914                                 return ret;
915                         break;
916                 default:
917                         return SR_ERR_NA;
918                 }
919                 return SR_OK;
920         }
921
922         switch (key) {
923         case SR_CONF_SAMPLERATE:
924                 devc->samplerate = g_variant_get_uint64(data);
925                 break;
926         case SR_CONF_LIMIT_SAMPLES:
927         case SR_CONF_LIMIT_MSEC:
928                 return sr_sw_limits_config_set(&devc->sw_limits, key, data);
929         case SR_CONF_CAPTURE_RATIO:
930                 devc->capture_ratio = g_variant_get_uint64(data);
931                 break;
932 #if WITH_THRESHOLD_DEVCFG
933         case SR_CONF_VOLTAGE_THRESHOLD:
934                 idx = std_double_tuple_idx(data,
935                         ARRAY_AND_SIZE(threshold_ranges));
936                 if (idx < 0)
937                         return SR_ERR_ARG;
938                 devc->threshold_voltage_idx = idx;
939                 break;
940 #endif /* WITH_THRESHOLD_DEVCFG */
941         case SR_CONF_CONTINUOUS:
942                 on = g_variant_get_boolean(data);
943                 if (!devc->model->memory_bits && !on)
944                         return SR_ERR_ARG;
945                 devc->continuous = on;
946                 break;
947         default:
948                 return SR_ERR_NA;
949         }
950
951         return SR_OK;
952 }
953
954 static int config_list(uint32_t key, GVariant **data,
955         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
956 {
957         struct dev_context *devc;
958         int ret, cg_type;
959         size_t logic_idx, analog_idx;
960
961         devc = sdi ? sdi->priv : NULL;
962
963         /* Check for types (and index) of channel groups. */
964         ret = get_cg_index(sdi, cg, &cg_type, &logic_idx, &analog_idx);
965         if (cg && ret != SR_OK)
966                 return SR_ERR_ARG;
967
968         /* Handle requests for the "Logic" channel group. */
969         if (cg && cg_type == SR_CHANNEL_LOGIC) {
970                 switch (key) {
971                 case SR_CONF_DEVICE_OPTIONS:
972                         if (ARRAY_SIZE(devopts_cg_logic) == 0)
973                                 return SR_ERR_NA;
974                         *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
975                                 devopts_cg_logic, ARRAY_SIZE(devopts_cg_logic),
976                                 sizeof(devopts_cg_logic[0]));
977                         break;
978 #if !WITH_THRESHOLD_DEVCFG
979                 case SR_CONF_VOLTAGE_THRESHOLD:
980                         *data = std_gvar_thresholds(ARRAY_AND_SIZE(threshold_ranges));
981                         break;
982 #endif /* WITH_THRESHOLD_DEVCFG */
983                 default:
984                         return SR_ERR_NA;
985                 }
986                 return SR_OK;
987         }
988
989         /* Handle requests for the "PWMx" channel groups. */
990         if (cg && cg_type == SR_CHANNEL_ANALOG) {
991                 switch (key) {
992                 case SR_CONF_DEVICE_OPTIONS:
993                         *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
994                                 devopts_cg_pwm, ARRAY_SIZE(devopts_cg_pwm),
995                                 sizeof(devopts_cg_pwm[0]));
996                         break;
997                 default:
998                         return SR_ERR_NA;
999                 }
1000                 return SR_OK;
1001         }
1002
1003         switch (key) {
1004         case SR_CONF_SCAN_OPTIONS:
1005         case SR_CONF_DEVICE_OPTIONS:
1006                 return STD_CONFIG_LIST(key, data, sdi, cg,
1007                         scanopts, drvopts, devopts);
1008         case SR_CONF_SAMPLERATE:
1009                 if (!sdi)
1010                         return SR_ERR_ARG;
1011                 if (devc->model->samplerate == SR_MHZ(500))
1012                         *data = std_gvar_samplerates(ARRAY_AND_SIZE(rates_500mhz));
1013                 else if (devc->model->samplerate == SR_MHZ(200))
1014                         *data = std_gvar_samplerates(ARRAY_AND_SIZE(rates_200mhz));
1015                 else if (devc->model->samplerate == SR_MHZ(100))
1016                         *data = std_gvar_samplerates(ARRAY_AND_SIZE(rates_100mhz));
1017                 else
1018                         return SR_ERR_BUG;
1019                 break;
1020         case SR_CONF_LIMIT_SAMPLES:
1021                 *data = std_gvar_tuple_u64(0, LA2016_NUM_SAMPLES_MAX);
1022                 break;
1023 #if WITH_THRESHOLD_DEVCFG
1024         case SR_CONF_VOLTAGE_THRESHOLD:
1025                 *data = std_gvar_thresholds(ARRAY_AND_SIZE(threshold_ranges));
1026                 break;
1027 #endif /* WITH_THRESHOLD_DEVCFG */
1028         case SR_CONF_TRIGGER_MATCH:
1029                 *data = std_gvar_array_i32(ARRAY_AND_SIZE(trigger_matches));
1030                 break;
1031         default:
1032                 return SR_ERR_NA;
1033         }
1034
1035         return SR_OK;
1036 }
1037
1038 static int dev_acquisition_start(const struct sr_dev_inst *sdi)
1039 {
1040         struct sr_dev_driver *di;
1041         struct drv_context *drvc;
1042         struct sr_context *ctx;
1043         struct dev_context *devc;
1044         size_t unitsize, xfersize, repsize, seqsize;
1045         double voltage;
1046         int ret;
1047
1048         di = sdi->driver;
1049         drvc = di->context;
1050         ctx = drvc->sr_ctx;;
1051         devc = sdi->priv;
1052
1053         if (!devc->feed_queue) {
1054                 /*
1055                  * TODO
1056                  * Move this into protocol.c which concentrates the
1057                  * wire format. The api.c source should not bother.
1058                  */
1059                 if (devc->model->channel_count == 32) {
1060                         unitsize = sizeof(uint32_t);
1061                         repsize = sizeof(uint8_t);
1062                         seqsize = 2 * sizeof(uint8_t);
1063                         xfersize = 32;
1064                 } else if (devc->model->channel_count == 16) {
1065                         unitsize = sizeof(uint16_t);
1066                         repsize = sizeof(uint8_t);
1067                         seqsize = 1 * sizeof(uint8_t);
1068                         xfersize = 16;
1069                 } else {
1070                         return SR_ERR_ARG;
1071                 }
1072                 devc->feed_queue = feed_queue_logic_alloc(sdi,
1073                         LA2016_CONVBUFFER_SIZE, unitsize);
1074                 if (!devc->feed_queue) {
1075                         sr_err("Cannot allocate buffer for session feed.");
1076                         return SR_ERR_MALLOC;
1077                 }
1078                 devc->transfer_size = xfersize;
1079                 devc->sequence_size = seqsize;
1080                 devc->packets_per_chunk = xfersize;
1081                 devc->packets_per_chunk -= seqsize;
1082                 devc->packets_per_chunk /= unitsize + repsize;
1083         }
1084
1085         sr_sw_limits_acquisition_start(&devc->sw_limits);
1086
1087         voltage = threshold_voltage(sdi, NULL);
1088         ret = la2016_setup_acquisition(sdi, voltage);
1089         if (ret != SR_OK) {
1090                 feed_queue_logic_free(devc->feed_queue);
1091                 devc->feed_queue = NULL;
1092                 return ret;
1093         }
1094
1095         ret = la2016_start_acquisition(sdi);
1096         if (ret != SR_OK) {
1097                 la2016_abort_acquisition(sdi);
1098                 feed_queue_logic_free(devc->feed_queue);
1099                 devc->feed_queue = NULL;
1100                 return ret;
1101         }
1102
1103         devc->completion_seen = FALSE;
1104         usb_source_add(sdi->session, ctx, 50,
1105                 la2016_receive_data, (void *)sdi);
1106
1107         std_session_send_df_header(sdi);
1108
1109         return SR_OK;
1110 }
1111
1112 static int dev_acquisition_stop(struct sr_dev_inst *sdi)
1113 {
1114         int ret;
1115
1116         ret = la2016_abort_acquisition(sdi);
1117
1118         return ret;
1119 }
1120
1121 static struct sr_dev_driver kingst_la2016_driver_info = {
1122         .name = "kingst-la2016",
1123         .longname = "Kingst LA2016",
1124         .api_version = 1,
1125         .init = std_init,
1126         .cleanup = std_cleanup,
1127         .scan = scan,
1128         .dev_list = std_dev_list,
1129         .dev_clear = std_dev_clear,
1130         .config_get = config_get,
1131         .config_set = config_set,
1132         .config_list = config_list,
1133         .dev_open = dev_open,
1134         .dev_close = dev_close,
1135         .dev_acquisition_start = dev_acquisition_start,
1136         .dev_acquisition_stop = dev_acquisition_stop,
1137         .context = NULL,
1138 };
1139 SR_REGISTER_DEV_DRIVER(kingst_la2016_driver_info);