kingst-la2016: avoid filling the log file with redundant messages during long captures
[libsigrok.git] / src / hardware / kingst-la2016 / api.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2020 Florian Schmidt <schmidt_florian@gmx.de>
5  * Copyright (C) 2013 Marcus Comstedt <marcus@mc.pp.se>
6  * Copyright (C) 2013 Bert Vermeulen <bert@biot.com>
7  * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
8  *
9  * This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  */
22
23 /* mostly stolen from src/hardware/saleae-logic16/ */
24
25 #include <config.h>
26 #include <glib.h>
27 #include <libusb.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <math.h>
31 #include <libsigrok/libsigrok.h>
32 #include "libsigrok-internal.h"
33 #include "protocol.h"
34
35 static const uint32_t scanopts[] = {
36         SR_CONF_CONN,
37 };
38
39 static const uint32_t drvopts[] = {
40         SR_CONF_LOGIC_ANALYZER,
41 };
42
43 static const uint32_t devopts[] = {
44         /* TODO: SR_CONF_CONTINUOUS, */
45         SR_CONF_CONN | SR_CONF_GET,
46         SR_CONF_SAMPLERATE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
47         SR_CONF_LIMIT_SAMPLES | SR_CONF_SET | SR_CONF_GET | SR_CONF_LIST,
48         SR_CONF_VOLTAGE_THRESHOLD | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
49         SR_CONF_LOGIC_THRESHOLD | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
50         SR_CONF_LOGIC_THRESHOLD_CUSTOM | SR_CONF_GET | SR_CONF_SET,
51         SR_CONF_TRIGGER_MATCH | SR_CONF_LIST,
52         SR_CONF_CAPTURE_RATIO | SR_CONF_GET | SR_CONF_SET,
53 };
54
55 static const int32_t trigger_matches[] = {
56         SR_TRIGGER_ZERO,
57         SR_TRIGGER_ONE,
58         SR_TRIGGER_RISING,
59         SR_TRIGGER_FALLING,
60 };
61
62 static const char *channel_names[] = {
63         "0", "1", "2", "3", "4", "5", "6", "7",
64         "8", "9", "10", "11", "12", "13", "14", "15",
65 };
66
67 static const uint64_t samplerates[] = {
68         SR_KHZ(20),
69         SR_KHZ(50),
70         SR_KHZ(100),
71         SR_KHZ(200),
72         SR_KHZ(500),
73         SR_MHZ(1),
74         SR_MHZ(2),
75         SR_MHZ(4),
76         SR_MHZ(5),
77         SR_MHZ(8),
78         SR_MHZ(10),
79         SR_MHZ(20),
80         SR_MHZ(50),
81         SR_MHZ(100),
82         SR_MHZ(200),
83 };
84
85 static const float logic_threshold_value[] = {
86         1.58,
87         2.5,
88         1.165,
89         1.5,
90         1.25,
91         0.9,
92         0.75,
93         0.60,
94         0.45,
95 };
96
97 static const char *logic_threshold[] = {
98         "TTL 5V",
99         "CMOS 5V",
100         "CMOS 3.3V",
101         "CMOS 3.0V",
102         "CMOS 2.5V",
103         "CMOS 1.8V",
104         "CMOS 1.5V",
105         "CMOS 1.2V",
106         "CMOS 0.9V",
107         "USER",
108 };
109
110 #define MAX_NUM_LOGIC_THRESHOLD_ENTRIES ARRAY_SIZE(logic_threshold)
111
112 static GSList *scan(struct sr_dev_driver *di, GSList *options)
113 {
114         struct drv_context *drvc;
115         struct dev_context *devc;
116         struct sr_dev_inst *sdi;
117         struct sr_usb_dev_inst *usb;
118         struct sr_config *src;
119         GSList *l;
120         GSList *devices;
121         GSList *conn_devices;
122         struct libusb_device_descriptor des;
123         libusb_device **devlist;
124         unsigned int i, j;
125         const char *conn;
126         char connection_id[64];
127         int64_t fw_updated;
128         unsigned int dev_addr;
129
130         drvc = di->context;
131
132         conn = NULL;
133         for (l = options; l; l = l->next) {
134                 src = l->data;
135                 switch (src->key) {
136                 case SR_CONF_CONN:
137                         conn = g_variant_get_string(src->data, NULL);
138                         break;
139                 }
140         }
141         if (conn)
142                 conn_devices = sr_usb_find(drvc->sr_ctx->libusb_ctx, conn);
143         else
144                 conn_devices = NULL;
145
146         /* Find all LA2016 devices and upload firmware to them. */
147         devices = NULL;
148         libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
149         for (i = 0; devlist[i]; i++) {
150                 if (conn) {
151                         usb = NULL;
152                         for (l = conn_devices; l; l = l->next) {
153                                 usb = l->data;
154                                 if (usb->bus == libusb_get_bus_number(devlist[i]) &&
155                                     usb->address == libusb_get_device_address(devlist[i]))
156                                         break;
157                         }
158                         if (!l) {
159                                 /* This device matched none of the ones that
160                                  * matched the conn specification. */
161                                 continue;
162                         }
163                 }
164
165                 libusb_get_device_descriptor(devlist[i], &des);
166
167                 if (usb_get_port_path(devlist[i], connection_id, sizeof(connection_id)) < 0)
168                         continue;
169
170                 if (des.idVendor != LA2016_VID || des.idProduct != LA2016_PID)
171                         continue;
172
173                 /* Already has the firmware */
174                 sr_dbg("Found a LA2016 device.");
175                 sdi = g_malloc0(sizeof(struct sr_dev_inst));
176                 sdi->status = SR_ST_INITIALIZING;
177                 sdi->connection_id = g_strdup(connection_id);
178
179                 fw_updated = 0;
180                 dev_addr = libusb_get_device_address(devlist[i]);
181                 if (des.iProduct != 2) {
182                         sr_info("device at '%s' has no firmware loaded!", connection_id);
183
184                         if (la2016_upload_firmware(drvc->sr_ctx, devlist[i], des.idProduct) != SR_OK) {
185                                 sr_err("uC firmware upload failed!");
186                                 g_free(sdi->connection_id);
187                                 g_free(sdi);
188                                 continue;
189                         }
190                         fw_updated = g_get_monotonic_time();
191                         dev_addr = 0xff; /* to mark that we don't know address yet... ugly */
192                 }
193
194                 sdi->vendor = g_strdup("Kingst");
195                 sdi->model = g_strdup("LA2016");
196
197                 for (j = 0; j < ARRAY_SIZE(channel_names); j++)
198                         sr_channel_new(sdi, j, SR_CHANNEL_LOGIC, TRUE, channel_names[j]);
199
200                 devices = g_slist_append(devices, sdi);
201
202                 devc = g_malloc0(sizeof(struct dev_context));
203                 sdi->priv = devc;
204                 devc->fw_updated = fw_updated;
205                 devc->threshold_voltage_idx = 0;
206                 devc->threshold_voltage = logic_threshold_value[devc->threshold_voltage_idx];
207
208                 sdi->status = SR_ST_INACTIVE;
209                 sdi->inst_type = SR_INST_USB;
210
211                 sdi->conn = sr_usb_dev_inst_new(
212                         libusb_get_bus_number(devlist[i]),
213                         dev_addr, NULL);
214         }
215         libusb_free_device_list(devlist, 1);
216         g_slist_free_full(conn_devices, (GDestroyNotify)sr_usb_dev_inst_free);
217
218         return std_scan_complete(di, devices);
219 }
220
221 static int la2016_dev_open(struct sr_dev_inst *sdi)
222 {
223         struct sr_dev_driver *di;
224         libusb_device **devlist;
225         struct sr_usb_dev_inst *usb;
226         struct libusb_device_descriptor des;
227         struct drv_context *drvc;
228         int ret, i, device_count;
229         char connection_id[64];
230
231         di = sdi->driver;
232         drvc = di->context;
233         usb = sdi->conn;
234         ret = SR_ERR;
235
236         device_count = libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
237         if (device_count < 0) {
238                 sr_err("Failed to get device list: %s.", libusb_error_name(device_count));
239                 return SR_ERR;
240         }
241
242         for (i = 0; i < device_count; i++) {
243                 libusb_get_device_descriptor(devlist[i], &des);
244
245                 if (des.idVendor != LA2016_VID || des.idProduct != LA2016_PID || des.iProduct != 2)
246                         continue;
247
248                 if ((sdi->status == SR_ST_INITIALIZING) || (sdi->status == SR_ST_INACTIVE)) {
249                         /*
250                          * Check device by its physical USB bus/port address.
251                          */
252                         if (usb_get_port_path(devlist[i], connection_id, sizeof(connection_id)) < 0)
253                                 continue;
254
255                         if (strcmp(sdi->connection_id, connection_id))
256                                 /* This is not the one. */
257                                 continue;
258                 }
259
260                 if (!(ret = libusb_open(devlist[i], &usb->devhdl))) {
261                         if (usb->address == 0xff)
262                                 /*
263                                  * First time we touch this device after FW
264                                  * upload, so we don't know the address yet.
265                                  */
266                                 usb->address = libusb_get_device_address(devlist[i]);
267                 } else {
268                         sr_err("Failed to open device: %s.", libusb_error_name(ret));
269                         ret = SR_ERR;
270                         break;
271                 }
272
273                 ret = libusb_claim_interface(usb->devhdl, USB_INTERFACE);
274                 if (ret == LIBUSB_ERROR_BUSY) {
275                         sr_err("Unable to claim USB interface. Another "
276                                "program or driver has already claimed it.");
277                         ret = SR_ERR;
278                         break;
279                 } else if (ret == LIBUSB_ERROR_NO_DEVICE) {
280                         sr_err("Device has been disconnected.");
281                         ret = SR_ERR;
282                         break;
283                 } else if (ret != 0) {
284                         sr_err("Unable to claim interface: %s.", libusb_error_name(ret));
285                         ret = SR_ERR;
286                         break;
287                 }
288
289                 if ((ret = la2016_init_device(sdi)) != SR_OK) {
290                         sr_err("Failed to init device.");
291                         break;
292                 }
293
294                 sr_info("Opened device on %d.%d (logical) / %s (physical), interface %d.",
295                         usb->bus, usb->address, sdi->connection_id, USB_INTERFACE);
296
297                 ret = SR_OK;
298
299                 break;
300         }
301
302         libusb_free_device_list(devlist, 1);
303
304         if (ret != SR_OK) {
305                 if (usb->devhdl) {
306                         libusb_release_interface(usb->devhdl, USB_INTERFACE);
307                         libusb_close(usb->devhdl);
308                         usb->devhdl = NULL;
309                 }
310                 return SR_ERR;
311         }
312
313         return SR_OK;
314 }
315
316 static int dev_open(struct sr_dev_inst *sdi)
317 {
318         struct dev_context *devc;
319         int64_t timediff_us, timediff_ms;
320         uint64_t reset_done;
321         uint64_t now;
322         int ret;
323
324         devc = sdi->priv;
325
326         /*
327          * If the firmware was recently uploaded, wait up to MAX_RENUM_DELAY_MS
328          * milliseconds for the FX2 to renumerate.
329          */
330         ret = SR_ERR;
331         if (devc->fw_updated > 0) {
332                 sr_info("Waiting for device to reset after firmware upload.");
333                 /* Takes >= 2000ms for the uC to be gone from the USB bus. */
334                 reset_done = devc->fw_updated + 18 * (uint64_t)1e5; /* 1.8 seconds */
335                 now = g_get_monotonic_time();
336                 if (reset_done > now)
337                         g_usleep(reset_done - now);
338                 timediff_ms = 0;
339                 while (timediff_ms < MAX_RENUM_DELAY_MS) {
340                         g_usleep(200 * 1000);
341
342                         timediff_us = g_get_monotonic_time() - devc->fw_updated;
343                         timediff_ms = timediff_us / 1000;
344
345                         if ((ret = la2016_dev_open(sdi)) == SR_OK)
346                                 break;
347                         sr_spew("Waited %" PRIi64 "ms.", timediff_ms);
348                 }
349                 if (ret != SR_OK) {
350                         sr_err("Device failed to re-enumerate.");
351                         return SR_ERR;
352                 }
353                 sr_info("Device came back after %" PRIi64 "ms.", timediff_ms);
354         } else {
355                 ret = la2016_dev_open(sdi);
356         }
357
358         if (ret != SR_OK) {
359                 sr_err("Unable to open device.");
360                 return SR_ERR;
361         }
362
363         return SR_OK;
364 }
365
366 static int dev_close(struct sr_dev_inst *sdi)
367 {
368         struct sr_usb_dev_inst *usb;
369
370         usb = sdi->conn;
371
372         if (!usb->devhdl)
373                 return SR_ERR_BUG;
374
375         la2016_deinit_device(sdi);
376
377         sr_info("Closing device on %d.%d (logical) / %s (physical) interface %d.",
378                 usb->bus, usb->address, sdi->connection_id, USB_INTERFACE);
379         libusb_release_interface(usb->devhdl, USB_INTERFACE);
380         libusb_close(usb->devhdl);
381         usb->devhdl = NULL;
382
383         return SR_OK;
384 }
385
386 static int config_get(uint32_t key, GVariant **data,
387         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
388 {
389         struct dev_context *devc;
390         struct sr_usb_dev_inst *usb;
391         double rounded;
392
393         (void)cg;
394
395         if (!sdi)
396                 return SR_ERR_ARG;
397         devc = sdi->priv;
398
399         switch (key) {
400         case SR_CONF_CONN:
401                 if (!sdi->conn)
402                         return SR_ERR_ARG;
403                 usb = sdi->conn;
404                 if (usb->address == 255) {
405                         /* Device still needs to re-enumerate after firmware
406                          * upload, so we don't know its (future) address. */
407                         return SR_ERR;
408                 }
409                 *data = g_variant_new_printf("%d.%d", usb->bus, usb->address);
410                 break;
411         case SR_CONF_SAMPLERATE:
412                 *data = g_variant_new_uint64(devc->cur_samplerate);
413                 break;
414         case SR_CONF_LIMIT_SAMPLES:
415                 *data = g_variant_new_uint64(devc->limit_samples);
416                 break;
417         case SR_CONF_CAPTURE_RATIO:
418                 *data = g_variant_new_uint64(devc->capture_ratio);
419                 break;
420         case SR_CONF_VOLTAGE_THRESHOLD:
421                 rounded = (int)(devc->threshold_voltage / 0.1) * 0.1;
422                 *data = std_gvar_tuple_double(rounded, rounded + 0.1);
423                 return SR_OK;
424         case SR_CONF_LOGIC_THRESHOLD:
425                 *data = g_variant_new_string(logic_threshold[devc->threshold_voltage_idx]);
426                 break;
427         case SR_CONF_LOGIC_THRESHOLD_CUSTOM:
428                 *data = g_variant_new_double(devc->threshold_voltage);
429                 break;
430
431         default:
432                 return SR_ERR_NA;
433         }
434
435         return SR_OK;
436 }
437
438 static int config_set(uint32_t key, GVariant *data,
439         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
440 {
441         struct dev_context *devc;
442         double low, high;
443         int idx;
444
445         (void)cg;
446
447         devc = sdi->priv;
448
449         switch (key) {
450         case SR_CONF_SAMPLERATE:
451                 devc->cur_samplerate = g_variant_get_uint64(data);
452                 break;
453         case SR_CONF_LIMIT_SAMPLES:
454                 devc->limit_samples = g_variant_get_uint64(data);
455                 break;
456         case SR_CONF_CAPTURE_RATIO:
457                 devc->capture_ratio = g_variant_get_uint64(data);
458                 break;
459         case SR_CONF_VOLTAGE_THRESHOLD:
460                 g_variant_get(data, "(dd)", &low, &high);
461                 devc->threshold_voltage = (low + high) / 2.0;
462                 devc->threshold_voltage_idx = MAX_NUM_LOGIC_THRESHOLD_ENTRIES - 1; /* USER */
463                 break;
464         case SR_CONF_LOGIC_THRESHOLD: {
465                 if ((idx = std_str_idx(data, logic_threshold, MAX_NUM_LOGIC_THRESHOLD_ENTRIES)) < 0)
466                         return SR_ERR_ARG;
467                 if (idx == MAX_NUM_LOGIC_THRESHOLD_ENTRIES - 1) {
468                         /* user threshold */
469                 } else {
470                         devc->threshold_voltage = logic_threshold_value[idx];
471                 }
472                 devc->threshold_voltage_idx = idx;
473                 break;
474         }
475         case SR_CONF_LOGIC_THRESHOLD_CUSTOM:
476                 devc->threshold_voltage = g_variant_get_double(data);
477                 break;
478         default:
479                 return SR_ERR_NA;
480         }
481
482         return SR_OK;
483 }
484
485 static int config_list(uint32_t key, GVariant **data,
486         const struct sr_dev_inst *sdi, const struct sr_channel_group *cg)
487 {
488         switch (key) {
489         case SR_CONF_SCAN_OPTIONS:
490         case SR_CONF_DEVICE_OPTIONS:
491                 return STD_CONFIG_LIST(key, data, sdi, cg, scanopts, drvopts, devopts);
492         case SR_CONF_SAMPLERATE:
493                 *data = std_gvar_samplerates(ARRAY_AND_SIZE(samplerates));
494                 break;
495         case SR_CONF_LIMIT_SAMPLES:
496                 *data = std_gvar_tuple_u64(LA2016_NUM_SAMPLES_MIN, LA2016_NUM_SAMPLES_MAX);
497                 break;
498         case SR_CONF_VOLTAGE_THRESHOLD:
499                 *data = std_gvar_min_max_step_thresholds(
500                         LA2016_THR_VOLTAGE_MIN,
501                         LA2016_THR_VOLTAGE_MAX, 0.1);
502                 break;
503         case SR_CONF_TRIGGER_MATCH:
504                 *data = std_gvar_array_i32(ARRAY_AND_SIZE(trigger_matches));
505                 break;
506         case SR_CONF_LOGIC_THRESHOLD:
507                 *data = g_variant_new_strv(logic_threshold, MAX_NUM_LOGIC_THRESHOLD_ENTRIES);
508                 break;
509         default:
510                 return SR_ERR_NA;
511         }
512
513         return SR_OK;
514 }
515
516 static void send_chunk(struct sr_dev_inst *sdi,
517         const uint8_t *packets, unsigned int num_tfers)
518 {
519         struct dev_context *devc;
520         struct sr_datafeed_logic logic;
521         struct sr_datafeed_packet sr_packet;
522         unsigned int max_samples, n_samples, total_samples, free_n_samples;
523         unsigned int i, j, k;
524         int do_signal_trigger;
525         uint16_t *wp;
526         const uint8_t *rp;
527         uint16_t state;
528         uint8_t repetitions;
529
530         devc = sdi->priv;
531
532         logic.unitsize = 2;
533         logic.data = devc->convbuffer;
534
535         sr_packet.type = SR_DF_LOGIC;
536         sr_packet.payload = &logic;
537
538         max_samples = devc->convbuffer_size / 2;
539         n_samples = 0;
540         wp = (uint16_t *)devc->convbuffer;
541         total_samples = 0;
542         do_signal_trigger = 0;
543
544         if (devc->had_triggers_configured && devc->reading_behind_trigger == 0 && devc->info.n_rep_packets_before_trigger == 0) {
545                 std_session_send_df_trigger(sdi);
546                 devc->reading_behind_trigger = 1;
547         }
548
549         rp = packets;
550         for (i = 0; i < num_tfers; i++) {
551                 for (k = 0; k < NUM_PACKETS_IN_CHUNK; k++) {
552                         free_n_samples = max_samples - n_samples;
553                         if (free_n_samples < 256 || do_signal_trigger) {
554                                 logic.length = n_samples * 2;
555                                 sr_session_send(sdi, &sr_packet);
556                                 n_samples = 0;
557                                 wp = (uint16_t *)devc->convbuffer;
558                                 if (do_signal_trigger) {
559                                         std_session_send_df_trigger(sdi);
560                                         do_signal_trigger = 0;
561                                 }
562                         }
563
564                         state = read_u16le_inc(&rp);
565                         repetitions = read_u8_inc(&rp);
566                         for (j = 0; j < repetitions; j++)
567                                 *wp++ = state;
568
569                         n_samples += repetitions;
570                         total_samples += repetitions;
571                         devc->total_samples += repetitions;
572                         if (!devc->reading_behind_trigger) {
573                                 devc->n_reps_until_trigger--;
574                                 if (devc->n_reps_until_trigger == 0) {
575                                         devc->reading_behind_trigger = 1;
576                                         do_signal_trigger = 1;
577                                         sr_dbg("  here is trigger position after %" PRIu64 " samples, %.6fms",
578                                                devc->total_samples,
579                                                (double)devc->total_samples / devc->cur_samplerate * 1e3);
580                                 }
581                         }
582                 }
583                 (void)read_u8_inc(&rp); /* Skip sequence number. */
584         }
585         if (n_samples) {
586                 logic.length = n_samples * 2;
587                 sr_session_send(sdi, &sr_packet);
588                 if (do_signal_trigger) {
589                         std_session_send_df_trigger(sdi);
590                 }
591         }
592         sr_dbg("send_chunk done after %d samples", total_samples);
593 }
594
595 static void LIBUSB_CALL receive_transfer(struct libusb_transfer *transfer)
596 {
597         struct sr_dev_inst *sdi;
598         struct dev_context *devc;
599         struct sr_usb_dev_inst *usb;
600         int ret;
601
602         sdi = transfer->user_data;
603         devc = sdi->priv;
604         usb = sdi->conn;
605
606         sr_dbg("receive_transfer(): status %s received %d bytes.",
607                libusb_error_name(transfer->status), transfer->actual_length);
608
609         if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT) {
610                 sr_err("bulk transfer timeout!");
611                 devc->transfer_finished = 1;
612         }
613         send_chunk(sdi, transfer->buffer, transfer->actual_length / TRANSFER_PACKET_LENGTH);
614
615         devc->n_bytes_to_read -= transfer->actual_length;
616         if (devc->n_bytes_to_read) {
617                 uint32_t to_read = devc->n_bytes_to_read;
618                 if (to_read > LA2016_BULK_MAX)
619                         to_read = LA2016_BULK_MAX;
620                 libusb_fill_bulk_transfer(
621                         transfer, usb->devhdl,
622                         0x86, transfer->buffer, to_read,
623                         receive_transfer, (void *)sdi, DEFAULT_TIMEOUT_MS);
624
625                 if ((ret = libusb_submit_transfer(transfer)) == 0)
626                         return;
627                 sr_err("Failed to submit further transfer: %s.", libusb_error_name(ret));
628         }
629
630         g_free(transfer->buffer);
631         libusb_free_transfer(transfer);
632         devc->transfer_finished = 1;
633 }
634
635 static int handle_event(int fd, int revents, void *cb_data)
636 {
637         const struct sr_dev_inst *sdi;
638         struct dev_context *devc;
639         struct drv_context *drvc;
640         struct timeval tv;
641
642         (void)fd;
643         (void)revents;
644
645         sdi = cb_data;
646         devc = sdi->priv;
647         drvc = sdi->driver->context;
648
649         if (devc->have_trigger == 0) {
650                 if (la2016_has_triggered(sdi) == 0) {
651                         /*sr_dbg("not yet ready for download...");*/
652                         return TRUE;
653                 }
654                 devc->have_trigger = 1;
655                 devc->transfer_finished = 0;
656                 devc->reading_behind_trigger = 0;
657                 devc->total_samples = 0;
658                 /* we can start retrieving data! */
659                 if (la2016_start_retrieval(sdi, receive_transfer) != SR_OK) {
660                         sr_err("failed to start retrieval!");
661                         return FALSE;
662                 }
663                 sr_dbg("retrieval is started...");
664                 std_session_send_df_frame_begin(sdi);
665
666                 return TRUE;
667         }
668
669         tv.tv_sec = tv.tv_usec = 0;
670         libusb_handle_events_timeout(drvc->sr_ctx->libusb_ctx, &tv);
671
672         if (devc->transfer_finished) {
673                 sr_dbg("transfer is finished!");
674                 std_session_send_df_frame_end(sdi);
675
676                 usb_source_remove(sdi->session, drvc->sr_ctx);
677                 std_session_send_df_end(sdi);
678
679                 la2016_stop_acquisition(sdi);
680
681                 g_free(devc->convbuffer);
682                 devc->convbuffer = NULL;
683
684                 devc->transfer = NULL;
685
686                 sr_dbg("transfer is now finished");
687         }
688
689         return TRUE;
690 }
691
692 static void abort_acquisition(struct dev_context *devc)
693 {
694         if (devc->transfer)
695                 libusb_cancel_transfer(devc->transfer);
696 }
697
698 static int configure_channels(const struct sr_dev_inst *sdi)
699 {
700         struct dev_context *devc;
701
702         devc = sdi->priv;
703         devc->cur_channels = 0;
704         devc->num_channels = 0;
705
706         for (GSList *l = sdi->channels; l; l = l->next) {
707                 struct sr_channel *ch = (struct sr_channel*)l->data;
708                 if (ch->enabled == FALSE)
709                         continue;
710                 devc->cur_channels |= 1 << ch->index;
711                 devc->num_channels++;
712         }
713
714         return SR_OK;
715 }
716
717 static int dev_acquisition_start(const struct sr_dev_inst *sdi)
718 {
719         struct sr_dev_driver *di;
720         struct drv_context *drvc;
721         struct dev_context *devc;
722         int ret;
723
724         di = sdi->driver;
725         drvc = di->context;
726         devc = sdi->priv;
727
728         if (configure_channels(sdi) != SR_OK) {
729                 sr_err("Failed to configure channels.");
730                 return SR_ERR;
731         }
732
733         devc->convbuffer_size = 4 * 1024 * 1024;
734         if (!(devc->convbuffer = g_try_malloc(devc->convbuffer_size))) {
735                 sr_err("Conversion buffer malloc failed.");
736                 return SR_ERR_MALLOC;
737         }
738
739         if ((ret = la2016_setup_acquisition(sdi)) != SR_OK) {
740                 g_free(devc->convbuffer);
741                 devc->convbuffer = NULL;
742                 return ret;
743         }
744
745         devc->ctx = drvc->sr_ctx;
746
747         if ((ret = la2016_start_acquisition(sdi)) != SR_OK) {
748                 abort_acquisition(devc);
749                 return ret;
750         }
751
752         devc->have_trigger = 0;
753         usb_source_add(sdi->session, drvc->sr_ctx, 50, handle_event, (void *)sdi);
754
755         std_session_send_df_header(sdi);
756
757         return SR_OK;
758 }
759
760 static int dev_acquisition_stop(struct sr_dev_inst *sdi)
761 {
762         int ret;
763
764         ret = la2016_abort_acquisition(sdi);
765         abort_acquisition(sdi->priv);
766
767         return ret;
768 }
769
770 static struct sr_dev_driver kingst_la2016_driver_info = {
771         .name = "kingst-la2016",
772         .longname = "Kingst LA2016",
773         .api_version = 1,
774         .init = std_init,
775         .cleanup = std_cleanup,
776         .scan = scan,
777         .dev_list = std_dev_list,
778         .dev_clear = std_dev_clear,
779         .config_get = config_get,
780         .config_set = config_set,
781         .config_list = config_list,
782         .dev_open = dev_open,
783         .dev_close = dev_close,
784         .dev_acquisition_start = dev_acquisition_start,
785         .dev_acquisition_stop = dev_acquisition_stop,
786         .context = NULL,
787 };
788 SR_REGISTER_DEV_DRIVER(kingst_la2016_driver_info);