]> sigrok.org Git - libsigrok.git/blob - src/hardware/hantek-6xxx/api.c
drivers: Factor out std_gvar_samplerates{,_steps}().
[libsigrok.git] / src / hardware / hantek-6xxx / api.c
1 /*
2  * This file is part of the libsigrok project.
3  *
4  * Copyright (C) 2015 Christer Ekholm <christerekholm@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 <math.h>
22 #include "protocol.h"
23
24 /* Max time in ms before we want to check on USB events */
25 #define TICK 200
26
27 #define RANGE(ch) (((float)vdivs[devc->voltage[ch]][0] / vdivs[devc->voltage[ch]][1]) * VDIV_MULTIPLIER)
28
29 static const uint32_t scanopts[] = {
30         SR_CONF_CONN,
31 };
32
33 static const uint32_t drvopts[] = {
34         SR_CONF_OSCILLOSCOPE,
35 };
36
37 static const uint32_t devopts[] = {
38         SR_CONF_CONN | SR_CONF_GET,
39         SR_CONF_LIMIT_SAMPLES | SR_CONF_GET | SR_CONF_SET,
40         SR_CONF_LIMIT_MSEC | SR_CONF_GET | SR_CONF_SET,
41         SR_CONF_SAMPLERATE | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
42         SR_CONF_NUM_VDIV | SR_CONF_GET,
43 };
44
45 static const uint32_t devopts_cg[] = {
46         SR_CONF_VDIV | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
47         SR_CONF_COUPLING | SR_CONF_GET | SR_CONF_SET | SR_CONF_LIST,
48 };
49
50 static const char *channel_names[] = {
51         "CH1", "CH2",
52 };
53
54 static const char *dc_coupling[] = {
55         "DC",
56 };
57
58 static const char *acdc_coupling[] = {
59         "AC", "DC",
60 };
61
62 static const struct hantek_6xxx_profile dev_profiles[] = {
63         {
64                 0x04b4, 0x6022, 0x1d50, 0x608e, 0x0001,
65                 "Hantek", "6022BE", "fx2lafw-hantek-6022be.fw",
66                 dc_coupling, ARRAY_SIZE(dc_coupling), FALSE,
67         },
68         {
69                 0x8102, 0x8102, 0x1d50, 0x608e, 0x0002,
70                 "Sainsmart", "DDS120", "fx2lafw-sainsmart-dds120.fw",
71                 acdc_coupling, ARRAY_SIZE(acdc_coupling), TRUE,
72         },
73         {
74                 0x04b4, 0x602a, 0x1d50, 0x608e, 0x0003,
75                 "Hantek", "6022BL", "fx2lafw-hantek-6022bl.fw",
76                 dc_coupling, ARRAY_SIZE(dc_coupling), FALSE,
77         },
78         ALL_ZERO
79 };
80
81 static const uint64_t samplerates[] = {
82         SAMPLERATE_VALUES
83 };
84
85 static const uint64_t vdivs[][2] = {
86         VDIV_VALUES
87 };
88
89 static int read_channel(const struct sr_dev_inst *sdi, uint32_t amount);
90
91 static struct sr_dev_inst *hantek_6xxx_dev_new(const struct hantek_6xxx_profile *prof)
92 {
93         struct sr_dev_inst *sdi;
94         struct sr_channel *ch;
95         struct sr_channel_group *cg;
96         struct dev_context *devc;
97         unsigned int i;
98
99         sdi = g_malloc0(sizeof(struct sr_dev_inst));
100         sdi->status = SR_ST_INITIALIZING;
101         sdi->vendor = g_strdup(prof->vendor);
102         sdi->model = g_strdup(prof->model);
103
104         for (i = 0; i < ARRAY_SIZE(channel_names); i++) {
105                 ch = sr_channel_new(sdi, i, SR_CHANNEL_ANALOG, TRUE, channel_names[i]);
106                 cg = g_malloc0(sizeof(struct sr_channel_group));
107                 cg->name = g_strdup(channel_names[i]);
108                 cg->channels = g_slist_append(cg->channels, ch);
109                 sdi->channel_groups = g_slist_append(sdi->channel_groups, cg);
110         }
111
112         devc = g_malloc0(sizeof(struct dev_context));
113
114         for (i = 0; i < NUM_CHANNELS; i++) {
115                 devc->ch_enabled[i] = TRUE;
116                 devc->voltage[i] = DEFAULT_VOLTAGE;
117                 devc->coupling[i] = DEFAULT_COUPLING;
118         }
119         devc->coupling_vals = prof->coupling_vals;
120         devc->coupling_tab_size = prof->coupling_tab_size;
121         devc->has_coupling = prof->has_coupling;
122
123         devc->sample_buf = NULL;
124         devc->sample_buf_write = 0;
125         devc->sample_buf_size = 0;
126
127         devc->profile = prof;
128         devc->dev_state = IDLE;
129         devc->samplerate = DEFAULT_SAMPLERATE;
130
131         sdi->priv = devc;
132
133         return sdi;
134 }
135
136 static int configure_channels(const struct sr_dev_inst *sdi)
137 {
138         struct dev_context *devc;
139         const GSList *l;
140         int p;
141         struct sr_channel *ch;
142         devc = sdi->priv;
143
144         g_slist_free(devc->enabled_channels);
145         devc->enabled_channels = NULL;
146         memset(devc->ch_enabled, 0, sizeof(devc->ch_enabled));
147
148         for (l = sdi->channels, p = 0; l; l = l->next, p++) {
149                 ch = l->data;
150                 if (p < NUM_CHANNELS) {
151                         devc->ch_enabled[p] = ch->enabled;
152                         devc->enabled_channels = g_slist_append(devc->enabled_channels, ch);
153                 }
154         }
155
156         return SR_OK;
157 }
158
159 static void clear_helper(struct dev_context *devc)
160 {
161         g_slist_free(devc->enabled_channels);
162 }
163
164 static int dev_clear(const struct sr_dev_driver *di)
165 {
166         return std_dev_clear_with_callback(di, (std_dev_clear_callback)clear_helper);
167 }
168
169 static GSList *scan(struct sr_dev_driver *di, GSList *options)
170 {
171         struct drv_context *drvc;
172         struct dev_context *devc;
173         struct sr_dev_inst *sdi;
174         struct sr_usb_dev_inst *usb;
175         struct sr_config *src;
176         const struct hantek_6xxx_profile *prof;
177         GSList *l, *devices, *conn_devices;
178         struct libusb_device_descriptor des;
179         libusb_device **devlist;
180         int i, j;
181         const char *conn;
182         char connection_id[64];
183
184         drvc = di->context;
185
186         devices = 0;
187
188         conn = NULL;
189         for (l = options; l; l = l->next) {
190                 src = l->data;
191                 if (src->key == SR_CONF_CONN) {
192                         conn = g_variant_get_string(src->data, NULL);
193                         break;
194                 }
195         }
196         if (conn)
197                 conn_devices = sr_usb_find(drvc->sr_ctx->libusb_ctx, conn);
198         else
199                 conn_devices = NULL;
200
201         /* Find all Hantek 60xx devices and upload firmware to all of them. */
202         libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
203         for (i = 0; devlist[i]; i++) {
204                 if (conn) {
205                         usb = NULL;
206                         for (l = conn_devices; l; l = l->next) {
207                                 usb = l->data;
208                                 if (usb->bus == libusb_get_bus_number(devlist[i])
209                                         && usb->address == libusb_get_device_address(devlist[i]))
210                                         break;
211                         }
212                         if (!l)
213                                 /* This device matched none of the ones that
214                                  * matched the conn specification. */
215                                 continue;
216                 }
217
218                 libusb_get_device_descriptor(devlist[i], &des);
219
220                 usb_get_port_path(devlist[i], connection_id, sizeof(connection_id));
221
222                 prof = NULL;
223                 for (j = 0; dev_profiles[j].orig_vid; j++) {
224                         if (des.idVendor == dev_profiles[j].orig_vid
225                                 && des.idProduct == dev_profiles[j].orig_pid) {
226                                 /* Device matches the pre-firmware profile. */
227                                 prof = &dev_profiles[j];
228                                 sr_dbg("Found a %s %s.", prof->vendor, prof->model);
229                                 sdi = hantek_6xxx_dev_new(prof);
230                                 sdi->connection_id = g_strdup(connection_id);
231                                 devices = g_slist_append(devices, sdi);
232                                 devc = sdi->priv;
233                                 if (ezusb_upload_firmware(drvc->sr_ctx, devlist[i],
234                                                 USB_CONFIGURATION, prof->firmware) == SR_OK)
235                                         /* Remember when the firmware on this device was updated. */
236                                         devc->fw_updated = g_get_monotonic_time();
237                                 else
238                                         sr_err("Firmware upload failed.");
239                                 /* Dummy USB address of 0xff will get overwritten later. */
240                                 sdi->conn = sr_usb_dev_inst_new(
241                                                 libusb_get_bus_number(devlist[i]), 0xff, NULL);
242                                 break;
243                         } else if (des.idVendor == dev_profiles[j].fw_vid
244                                 && des.idProduct == dev_profiles[j].fw_pid
245                                 && des.bcdDevice == dev_profiles[j].fw_prod_ver) {
246                                 /* Device matches the post-firmware profile. */
247                                 prof = &dev_profiles[j];
248                                 sr_dbg("Found a %s %s.", prof->vendor, prof->model);
249                                 sdi = hantek_6xxx_dev_new(prof);
250                                 sdi->connection_id = g_strdup(connection_id);
251                                 sdi->status = SR_ST_INACTIVE;
252                                 devices = g_slist_append(devices, sdi);
253                                 sdi->inst_type = SR_INST_USB;
254                                 sdi->conn = sr_usb_dev_inst_new(
255                                                 libusb_get_bus_number(devlist[i]),
256                                                 libusb_get_device_address(devlist[i]), NULL);
257                                 break;
258                         }
259                 }
260                 if (!prof)
261                         /* Not a supported VID/PID. */
262                         continue;
263         }
264         libusb_free_device_list(devlist, 1);
265
266         return std_scan_complete(di, devices);
267 }
268
269 static int dev_open(struct sr_dev_inst *sdi)
270 {
271         struct dev_context *devc;
272         struct sr_usb_dev_inst *usb;
273         int64_t timediff_us, timediff_ms;
274         int err;
275
276         devc = sdi->priv;
277         usb = sdi->conn;
278
279         /*
280          * If the firmware was recently uploaded, wait up to MAX_RENUM_DELAY_MS
281          * for the FX2 to renumerate.
282          */
283         err = SR_ERR;
284         if (devc->fw_updated > 0) {
285                 sr_info("Waiting for device to reset.");
286                 /* Takes >= 300ms for the FX2 to be gone from the USB bus. */
287                 g_usleep(300 * 1000);
288                 timediff_ms = 0;
289                 while (timediff_ms < MAX_RENUM_DELAY_MS) {
290                         if ((err = hantek_6xxx_open(sdi)) == SR_OK)
291                                 break;
292                         g_usleep(100 * 1000);
293                         timediff_us = g_get_monotonic_time() - devc->fw_updated;
294                         timediff_ms = timediff_us / 1000;
295                         sr_spew("Waited %" PRIi64 " ms.", timediff_ms);
296                 }
297                 if (timediff_ms < MAX_RENUM_DELAY_MS)
298                         sr_info("Device came back after %"PRIu64" ms.", timediff_ms);
299         } else {
300                 err = hantek_6xxx_open(sdi);
301         }
302
303         if (err != SR_OK) {
304                 sr_err("Unable to open device.");
305                 return SR_ERR;
306         }
307
308         err = libusb_claim_interface(usb->devhdl, USB_INTERFACE);
309         if (err != 0) {
310                 sr_err("Unable to claim interface: %s.",
311                         libusb_error_name(err));
312                 return SR_ERR;
313         }
314
315         return SR_OK;
316 }
317
318 static int dev_close(struct sr_dev_inst *sdi)
319 {
320         hantek_6xxx_close(sdi);
321
322         return SR_OK;
323 }
324
325 static int config_get(uint32_t key, GVariant **data, const struct sr_dev_inst *sdi,
326                 const struct sr_channel_group *cg)
327 {
328         struct dev_context *devc;
329         struct sr_usb_dev_inst *usb;
330         char str[128];
331         const uint64_t *vdiv;
332         int ch_idx;
333
334         switch (key) {
335         case SR_CONF_NUM_VDIV:
336                 *data = g_variant_new_int32(ARRAY_SIZE(vdivs));
337                 break;
338         }
339
340         if (!sdi)
341                 return SR_ERR_ARG;
342
343         devc = sdi->priv;
344         if (!cg) {
345                 switch (key) {
346                 case SR_CONF_SAMPLERATE:
347                         *data = g_variant_new_uint64(devc->samplerate);
348                         break;
349                 case SR_CONF_LIMIT_MSEC:
350                         *data = g_variant_new_uint64(devc->limit_msec);
351                         break;
352                 case SR_CONF_LIMIT_SAMPLES:
353                         *data = g_variant_new_uint64(devc->limit_samples);
354                         break;
355                 case SR_CONF_CONN:
356                         if (!sdi->conn)
357                                 return SR_ERR_ARG;
358                         usb = sdi->conn;
359                         if (usb->address == 255)
360                                 /* Device still needs to re-enumerate after firmware
361                                  * upload, so we don't know its (future) address. */
362                                 return SR_ERR;
363                         snprintf(str, 128, "%d.%d", usb->bus, usb->address);
364                         *data = g_variant_new_string(str);
365                         break;
366                 default:
367                         return SR_ERR_NA;
368                 }
369         } else {
370                 if (sdi->channel_groups->data == cg)
371                         ch_idx = 0;
372                 else if (sdi->channel_groups->next->data == cg)
373                         ch_idx = 1;
374                 else
375                         return SR_ERR_ARG;
376                 switch (key) {
377                 case SR_CONF_VDIV:
378                         vdiv = vdivs[devc->voltage[ch_idx]];
379                         *data = g_variant_new("(tt)", vdiv[0], vdiv[1]);
380                         break;
381                 case SR_CONF_COUPLING:
382                         *data = g_variant_new_string((devc->coupling[ch_idx] \
383                                         == COUPLING_DC) ? "DC" : "AC");
384                         break;
385                 }
386         }
387
388         return SR_OK;
389 }
390
391 static int config_set(uint32_t key, GVariant *data, const struct sr_dev_inst *sdi,
392                 const struct sr_channel_group *cg)
393 {
394         struct dev_context *devc;
395         uint64_t p, q;
396         int tmp_int, ch_idx;
397         unsigned int i;
398         const char *tmp_str;
399
400         devc = sdi->priv;
401         if (!cg) {
402                 switch (key) {
403                 case SR_CONF_SAMPLERATE:
404                         devc->samplerate = g_variant_get_uint64(data);
405                         hantek_6xxx_update_samplerate(sdi);
406                         break;
407                 case SR_CONF_LIMIT_MSEC:
408                         devc->limit_msec = g_variant_get_uint64(data);
409                         break;
410                 case SR_CONF_LIMIT_SAMPLES:
411                         devc->limit_samples = g_variant_get_uint64(data);
412                         break;
413                 default:
414                         return SR_ERR_NA;
415                 }
416         } else {
417                 if (sdi->channel_groups->data == cg)
418                         ch_idx = 0;
419                 else if (sdi->channel_groups->next->data == cg)
420                         ch_idx = 1;
421                 else
422                         return SR_ERR_ARG;
423                 switch (key) {
424                 case SR_CONF_VDIV:
425                         g_variant_get(data, "(tt)", &p, &q);
426                         tmp_int = -1;
427                         for (i = 0; i < ARRAY_SIZE(vdivs); i++) {
428                                 if (vdivs[i][0] == p && vdivs[i][1] == q) {
429                                         tmp_int = i;
430                                         break;
431                                 }
432                         }
433                         if (tmp_int >= 0) {
434                                 devc->voltage[ch_idx] = tmp_int;
435                                 hantek_6xxx_update_vdiv(sdi);
436                         } else
437                                 return SR_ERR_ARG;
438                         break;
439                 case SR_CONF_COUPLING:
440                         tmp_str = g_variant_get_string(data, NULL);
441                         for (i = 0; i < devc->coupling_tab_size; i++) {
442                                 if (!strcmp(tmp_str, devc->coupling_vals[i])) {
443                                         devc->coupling[ch_idx] = i;
444                                         break;
445                                 }
446                         }
447                         if (i == devc->coupling_tab_size)
448                                 return SR_ERR_ARG;
449                         break;
450                 default:
451                         return SR_ERR_NA;
452                 }
453         }
454
455         return SR_OK;
456 }
457
458 static int config_list(uint32_t key, GVariant **data, const struct sr_dev_inst *sdi,
459                 const struct sr_channel_group *cg)
460 {
461         struct dev_context *devc;
462
463         devc = (sdi) ? sdi->priv : NULL;
464
465         if (!cg) {
466                 switch (key) {
467                 case SR_CONF_SCAN_OPTIONS:
468                 case SR_CONF_DEVICE_OPTIONS:
469                         return STD_CONFIG_LIST(key, data, sdi, cg, scanopts, drvopts, devopts);
470                 case SR_CONF_SAMPLERATE:
471                         *data = std_gvar_samplerates(samplerates, ARRAY_SIZE(samplerates));
472                         break;
473                 default:
474                         return SR_ERR_NA;
475                 }
476         } else {
477                 switch (key) {
478                 case SR_CONF_DEVICE_OPTIONS:
479                         *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32,
480                                 devopts_cg, ARRAY_SIZE(devopts_cg), sizeof(uint32_t));
481                         break;
482                 case SR_CONF_COUPLING:
483                         *data = g_variant_new_strv(devc->coupling_vals, devc->coupling_tab_size);
484                         break;
485                 case SR_CONF_VDIV:
486                         *data = std_gvar_tuple_array(&vdivs, ARRAY_SIZE(vdivs));
487                         break;
488                 default:
489                         return SR_ERR_NA;
490                 }
491         }
492
493         return SR_OK;
494 }
495
496 /* Minimise data amount for limit_samples and limit_msec limits. */
497 static uint32_t data_amount(const struct sr_dev_inst *sdi)
498 {
499         struct dev_context *devc = sdi->priv;
500         uint32_t data_left, data_left_2, i;
501         int32_t time_left;
502
503         if (devc->limit_msec) {
504                 time_left = devc->limit_msec - (g_get_monotonic_time() - devc->aq_started) / 1000;
505                 data_left = devc->samplerate * MAX(time_left, 0) * NUM_CHANNELS / 1000;
506         } else if (devc->limit_samples) {
507                 data_left = (devc->limit_samples - devc->samp_received) * NUM_CHANNELS;
508         } else {
509                 data_left = devc->samplerate * NUM_CHANNELS;
510         }
511
512         /* Round up to nearest power of two. */
513         for (i = MIN_PACKET_SIZE; i < data_left; i *= 2)
514                 ;
515         data_left_2 = i;
516
517         sr_spew("data_amount: %u (rounded to power of 2: %u)", data_left, data_left_2);
518
519         return data_left_2;
520 }
521
522 static void send_chunk(struct sr_dev_inst *sdi, unsigned char *buf,
523                 int num_samples)
524 {
525         struct sr_datafeed_packet packet;
526         struct sr_datafeed_analog analog;
527         struct sr_analog_encoding encoding;
528         struct sr_analog_meaning meaning;
529         struct sr_analog_spec spec;
530         struct dev_context *devc = sdi->priv;
531         GSList *channels = devc->enabled_channels;
532
533         const float ch_bit[] = { RANGE(0) / 255, RANGE(1) / 255 };
534         const float ch_center[] = { RANGE(0) / 2, RANGE(1) / 2 };
535
536         sr_analog_init(&analog, &encoding, &meaning, &spec, 0);
537
538         packet.type = SR_DF_ANALOG;
539         packet.payload = &analog;
540
541         analog.num_samples = num_samples;
542         analog.meaning->mq = SR_MQ_VOLTAGE;
543         analog.meaning->unit = SR_UNIT_VOLT;
544         analog.meaning->mqflags = 0;
545
546         analog.data = g_try_malloc(num_samples * sizeof(float));
547         if (!analog.data) {
548                 sr_err("Analog data buffer malloc failed.");
549                 devc->dev_state = STOPPING;
550                 return;
551         }
552
553         for (int ch = 0; ch < 2; ch++) {
554                 if (!devc->ch_enabled[ch])
555                         continue;
556
557                 float vdivlog = log10f(ch_bit[ch]);
558                 int digits = -(int)vdivlog + (vdivlog < 0.0);
559                 analog.encoding->digits = digits;
560                 analog.spec->spec_digits = digits;
561                 analog.meaning->channels = g_slist_append(NULL, channels->data);
562
563                 for (int i = 0; i < num_samples; i++) {
564                         /*
565                          * The device always sends data for both channels. If a channel
566                          * is disabled, it contains a copy of the enabled channel's
567                          * data. However, we only send the requested channels to
568                          * the bus.
569                          *
570                          * Voltage values are encoded as a value 0-255, where the
571                          * value is a point in the range represented by the vdiv
572                          * setting. There are 10 vertical divs, so e.g. 500mV/div
573                          * represents 5V peak-to-peak where 0 = -2.5V and 255 = +2.5V.
574                          */
575                         ((float *)analog.data)[i] = ch_bit[ch] * *(buf + i * 2 + ch) - ch_center[ch];
576                 }
577
578                 sr_session_send(sdi, &packet);
579                 g_slist_free(analog.meaning->channels);
580
581                 channels = channels->next;
582         }
583         g_free(analog.data);
584 }
585
586 static void send_data(struct sr_dev_inst *sdi, struct libusb_transfer *buf[], uint64_t samples)
587 {
588         int i = 0;
589         uint64_t send = 0;
590         uint32_t chunk;
591
592         while (send < samples) {
593                 chunk = MIN(samples - send, (uint64_t)(buf[i]->actual_length / NUM_CHANNELS));
594                 send += chunk;
595                 send_chunk(sdi, buf[i]->buffer, chunk);
596
597                 /*
598                  * Everything in this transfer was either copied to the buffer
599                  * or sent to the session bus.
600                  */
601                 g_free(buf[i]->buffer);
602                 libusb_free_transfer(buf[i]);
603                 i++;
604         }
605 }
606
607 /*
608  * Called by libusb (as triggered by handle_event()) when a transfer comes in.
609  * Only channel data comes in asynchronously, and all transfers for this are
610  * queued up beforehand, so this just needs to chuck the incoming data onto
611  * the libsigrok session bus.
612  */
613 static void LIBUSB_CALL receive_transfer(struct libusb_transfer *transfer)
614 {
615         struct sr_dev_inst *sdi;
616         struct dev_context *devc;
617
618         sdi = transfer->user_data;
619         devc = sdi->priv;
620
621         if (devc->dev_state == FLUSH) {
622                 g_free(transfer->buffer);
623                 libusb_free_transfer(transfer);
624                 devc->dev_state = CAPTURE;
625                 devc->aq_started = g_get_monotonic_time();
626                 read_channel(sdi, data_amount(sdi));
627                 return;
628         }
629
630         if (devc->dev_state != CAPTURE)
631                 return;
632
633         if (!devc->sample_buf) {
634                 devc->sample_buf_size = 10;
635                 devc->sample_buf = g_try_malloc(devc->sample_buf_size * sizeof(transfer));
636                 devc->sample_buf_write = 0;
637         }
638
639         if (devc->sample_buf_write >= devc->sample_buf_size) {
640                 devc->sample_buf_size += 10;
641                 devc->sample_buf = g_try_realloc(devc->sample_buf,
642                                 devc->sample_buf_size * sizeof(transfer));
643                 if (!devc->sample_buf) {
644                         sr_err("Sample buffer malloc failed.");
645                         devc->dev_state = STOPPING;
646                         return;
647                 }
648         }
649
650         devc->sample_buf[devc->sample_buf_write++] = transfer;
651         devc->samp_received += transfer->actual_length / NUM_CHANNELS;
652
653         sr_spew("receive_transfer(): calculated samplerate == %" PRIu64 "ks/s",
654                 (uint64_t)(transfer->actual_length * 1000 /
655                 (g_get_monotonic_time() - devc->read_start_ts + 1) /
656                 NUM_CHANNELS));
657
658         sr_spew("receive_transfer(): status %s received %d bytes.",
659                 libusb_error_name(transfer->status), transfer->actual_length);
660
661         if (transfer->actual_length == 0)
662                 /* Nothing to send to the bus. */
663                 return;
664
665         if (devc->limit_samples && devc->samp_received >= devc->limit_samples) {
666                 sr_info("Requested number of samples reached, stopping. %"
667                         PRIu64 " <= %" PRIu64, devc->limit_samples,
668                         devc->samp_received);
669                 send_data(sdi, devc->sample_buf, devc->limit_samples);
670                 sr_dev_acquisition_stop(sdi);
671         } else if (devc->limit_msec && (g_get_monotonic_time() -
672                         devc->aq_started) / 1000 >= devc->limit_msec) {
673                 sr_info("Requested time limit reached, stopping. %d <= %d",
674                         (uint32_t)devc->limit_msec,
675                         (uint32_t)(g_get_monotonic_time() - devc->aq_started) / 1000);
676                 send_data(sdi, devc->sample_buf, devc->samp_received);
677                 g_free(devc->sample_buf);
678                 devc->sample_buf = NULL;
679                 sr_dev_acquisition_stop(sdi);
680         } else {
681                 read_channel(sdi, data_amount(sdi));
682         }
683 }
684
685 static int read_channel(const struct sr_dev_inst *sdi, uint32_t amount)
686 {
687         int ret;
688         struct dev_context *devc;
689
690         devc = sdi->priv;
691
692         amount = MIN(amount, MAX_PACKET_SIZE);
693         ret = hantek_6xxx_get_channeldata(sdi, receive_transfer, amount);
694         devc->read_start_ts = g_get_monotonic_time();
695         devc->read_data_amount = amount;
696
697         return ret;
698 }
699
700 static int handle_event(int fd, int revents, void *cb_data)
701 {
702         const struct sr_dev_inst *sdi;
703         struct timeval tv;
704         struct sr_dev_driver *di;
705         struct dev_context *devc;
706         struct drv_context *drvc;
707
708         (void)fd;
709         (void)revents;
710
711         sdi = cb_data;
712         di = sdi->driver;
713         drvc = di->context;
714         devc = sdi->priv;
715
716         /* Always handle pending libusb events. */
717         tv.tv_sec = tv.tv_usec = 0;
718         libusb_handle_events_timeout(drvc->sr_ctx->libusb_ctx, &tv);
719
720         if (devc->dev_state == STOPPING) {
721                 /* We've been told to wind up the acquisition. */
722                 sr_dbg("Stopping acquisition.");
723
724                 hantek_6xxx_stop_data_collecting(sdi);
725                 /*
726                  * TODO: Doesn't really cancel pending transfers so they might
727                  * come in after SR_DF_END is sent.
728                  */
729                 usb_source_remove(sdi->session, drvc->sr_ctx);
730
731                 std_session_send_df_end(sdi);
732
733                 devc->dev_state = IDLE;
734
735                 return TRUE;
736         }
737
738         return TRUE;
739 }
740
741 static int dev_acquisition_start(const struct sr_dev_inst *sdi)
742 {
743         struct dev_context *devc;
744         struct sr_dev_driver *di = sdi->driver;
745         struct drv_context *drvc = di->context;
746
747         devc = sdi->priv;
748
749         if (configure_channels(sdi) != SR_OK) {
750                 sr_err("Failed to configure channels.");
751                 return SR_ERR;
752         }
753
754         if (hantek_6xxx_init(sdi) != SR_OK)
755                 return SR_ERR;
756
757         std_session_send_df_header(sdi);
758
759         devc->samp_received = 0;
760         devc->dev_state = FLUSH;
761
762         usb_source_add(sdi->session, drvc->sr_ctx, TICK,
763                        handle_event, (void *)sdi);
764
765         hantek_6xxx_start_data_collecting(sdi);
766
767         read_channel(sdi, FLUSH_PACKET_SIZE);
768
769         return SR_OK;
770 }
771
772 static int dev_acquisition_stop(struct sr_dev_inst *sdi)
773 {
774         struct dev_context *devc;
775
776         devc = sdi->priv;
777         devc->dev_state = STOPPING;
778
779         g_free(devc->sample_buf);
780         devc->sample_buf = NULL;
781
782         return SR_OK;
783 }
784
785 static struct sr_dev_driver hantek_6xxx_driver_info = {
786         .name = "hantek-6xxx",
787         .longname = "Hantek 6xxx",
788         .api_version = 1,
789         .init = std_init,
790         .cleanup = std_cleanup,
791         .scan = scan,
792         .dev_list = std_dev_list,
793         .dev_clear = dev_clear,
794         .config_get = config_get,
795         .config_set = config_set,
796         .config_list = config_list,
797         .dev_open = dev_open,
798         .dev_close = dev_close,
799         .dev_acquisition_start = dev_acquisition_start,
800         .dev_acquisition_stop = dev_acquisition_stop,
801         .context = NULL,
802 };
803 SR_REGISTER_DEV_DRIVER(hantek_6xxx_driver_info);