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