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