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