]> sigrok.org Git - libsigrok.git/blob - hardware/hantek-dso/api.c
hantek-dso: Adjust to GVariant-based sr_config_* functions
[libsigrok.git] / hardware / hantek-dso / api.c
1 /*
2  * This file is part of the sigrok project.
3  *
4  * Copyright (C) 2012 Bert Vermeulen <bert@biot.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 <stdio.h>
21 #include <stdint.h>
22 #include <stdlib.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <fcntl.h>
26 #include <unistd.h>
27 #include <string.h>
28 #include <sys/time.h>
29 #include <inttypes.h>
30 #include <glib.h>
31 #include <libusb.h>
32 #include "libsigrok.h"
33 #include "libsigrok-internal.h"
34 #include "dso.h"
35
36 /* Max time in ms before we want to check on USB events */
37 /* TODO tune this properly */
38 #define TICK 1
39
40 static const int32_t devopts[] = {
41         SR_CONF_OSCILLOSCOPE,
42         SR_CONF_LIMIT_FRAMES,
43         SR_CONF_CONTINUOUS,
44         SR_CONF_TIMEBASE,
45         SR_CONF_BUFFERSIZE,
46         SR_CONF_TRIGGER_SOURCE,
47         SR_CONF_TRIGGER_SLOPE,
48         SR_CONF_HORIZ_TRIGGERPOS,
49         SR_CONF_FILTER,
50         SR_CONF_VDIV,
51         SR_CONF_COUPLING,
52 };
53
54 static const char *probe_names[] = {
55         "CH1", "CH2",
56         NULL,
57 };
58
59 static const struct dso_profile dev_profiles[] = {
60         {       0x04b4, 0x2090, 0x04b5, 0x2090,
61                 "Hantek", "DSO-2090",
62                 FIRMWARE_DIR "/hantek-dso-2090.fw" },
63         {       0x04b4, 0x2150, 0x04b5, 0x2150,
64                 "Hantek", "DSO-2150",
65                 FIRMWARE_DIR "/hantek-dso-2150.fw" },
66         {       0x04b4, 0x2250, 0x04b5, 0x2250,
67                 "Hantek", "DSO-2250",
68                 FIRMWARE_DIR "/hantek-dso-2250.fw" },
69         {       0x04b4, 0x5200, 0x04b5, 0x5200,
70                 "Hantek", "DSO-5200",
71                 FIRMWARE_DIR "/hantek-dso-5200.fw" },
72         {       0x04b4, 0x520a, 0x04b5, 0x520a,
73                 "Hantek", "DSO-5200A",
74                 FIRMWARE_DIR "/hantek-dso-5200A.fw" },
75         { 0, 0, 0, 0, 0, 0, 0 },
76 };
77
78 static const uint64_t buffersizes[] = {
79         10240,
80         32768,
81         /* TODO: 65535 */
82 };
83
84 static const int32_t timebases[][2] = {
85         /* microseconds */
86         { 10, 1000000 },
87         { 20, 1000000 },
88         { 40, 1000000 },
89         { 100, 1000000 },
90         { 200, 1000000 },
91         { 400, 1000000 },
92         /* milliseconds */
93         { 1, 1000 },
94         { 2, 1000 },
95         { 4, 1000 },
96         { 10, 1000 },
97         { 20, 1000 },
98         { 40, 1000 },
99         { 100, 1000 },
100         { 200, 1000 },
101         { 400, 1000 },
102 };
103
104 static const int32_t vdivs[][2] = {
105         /* millivolts */
106         { 10, 1000 },
107         { 20, 1000 },
108         { 50, 1000 },
109         { 100, 1000 },
110         { 200, 1000 },
111         { 500, 1000 },
112         /* volts */
113         { 1, 1 },
114         { 2, 1 },
115         { 5, 1 },
116 };
117
118 static const char *trigger_sources[] = {
119         "CH1",
120         "CH2",
121         "EXT",
122         /* TODO: forced */
123 };
124
125 static const char *filter_targets[] = {
126         "CH1",
127         "CH2",
128         /* TODO: "TRIGGER", */
129 };
130
131 static const char *coupling[] = {
132         "AC",
133         "DC",
134         "GND",
135 };
136
137 SR_PRIV struct sr_dev_driver hantek_dso_driver_info;
138 static struct sr_dev_driver *di = &hantek_dso_driver_info;
139
140 static int hw_dev_acquisition_stop(struct sr_dev_inst *sdi, void *cb_data);
141
142 static struct sr_dev_inst *dso_dev_new(int index, const struct dso_profile *prof)
143 {
144         struct sr_dev_inst *sdi;
145         struct sr_probe *probe;
146         struct drv_context *drvc;
147         struct dev_context *devc;
148         int i;
149
150         sdi = sr_dev_inst_new(index, SR_ST_INITIALIZING,
151                 prof->vendor, prof->model, NULL);
152         if (!sdi)
153                 return NULL;
154         sdi->driver = di;
155
156         /*
157          * Add only the real probes -- EXT isn't a source of data, only
158          * a trigger source internal to the device.
159          */
160         for (i = 0; probe_names[i]; i++) {
161                 if (!(probe = sr_probe_new(i, SR_PROBE_ANALOG, TRUE,
162                                 probe_names[i])))
163                         return NULL;
164                 sdi->probes = g_slist_append(sdi->probes, probe);
165         }
166
167         if (!(devc = g_try_malloc0(sizeof(struct dev_context)))) {
168                 sr_err("Device context malloc failed.");
169                 return NULL;
170         }
171
172         devc->profile = prof;
173         devc->dev_state = IDLE;
174         devc->timebase = DEFAULT_TIMEBASE;
175         devc->ch1_enabled = TRUE;
176         devc->ch2_enabled = TRUE;
177         devc->voltage_ch1 = DEFAULT_VOLTAGE;
178         devc->voltage_ch2 = DEFAULT_VOLTAGE;
179         devc->coupling_ch1 = DEFAULT_COUPLING;
180         devc->coupling_ch2 = DEFAULT_COUPLING;
181         devc->voffset_ch1 = DEFAULT_VERT_OFFSET;
182         devc->voffset_ch2 = DEFAULT_VERT_OFFSET;
183         devc->voffset_trigger = DEFAULT_VERT_TRIGGERPOS;
184         devc->framesize = DEFAULT_FRAMESIZE;
185         devc->triggerslope = SLOPE_POSITIVE;
186         devc->triggersource = g_strdup(DEFAULT_TRIGGER_SOURCE);
187         devc->triggerposition = DEFAULT_HORIZ_TRIGGERPOS;
188         sdi->priv = devc;
189         drvc = di->priv;
190         drvc->instances = g_slist_append(drvc->instances, sdi);
191
192         return sdi;
193 }
194
195 static int configure_probes(const struct sr_dev_inst *sdi)
196 {
197         struct dev_context *devc;
198         struct sr_probe *probe;
199         const GSList *l;
200         int p;
201
202         devc = sdi->priv;
203
204         g_slist_free(devc->enabled_probes);
205         devc->ch1_enabled = devc->ch2_enabled = FALSE;
206         for (l = sdi->probes, p = 0; l; l = l->next, p++) {
207                 probe = l->data;
208                 if (p == 0)
209                         devc->ch1_enabled = probe->enabled;
210                 else
211                         devc->ch2_enabled = probe->enabled;
212                 if (probe->enabled)
213                         devc->enabled_probes = g_slist_append(devc->enabled_probes, probe);
214         }
215
216         return SR_OK;
217 }
218
219 /* Properly close and free all devices. */
220 static int clear_instances(void)
221 {
222         struct sr_dev_inst *sdi;
223         struct drv_context *drvc;
224         struct dev_context *devc;
225         GSList *l;
226
227         drvc = di->priv;
228         for (l = drvc->instances; l; l = l->next) {
229                 if (!(sdi = l->data)) {
230                         /* Log error, but continue cleaning up the rest. */
231                         sr_err("%s: sdi was NULL, continuing", __func__);
232                         continue;
233                 }
234                 if (!(devc = sdi->priv)) {
235                         /* Log error, but continue cleaning up the rest. */
236                         sr_err("%s: sdi->priv was NULL, continuing", __func__);
237                         continue;
238                 }
239                 dso_close(sdi);
240                 sr_usb_dev_inst_free(devc->usb);
241                 g_free(devc->triggersource);
242                 g_slist_free(devc->enabled_probes);
243
244                 sr_dev_inst_free(sdi);
245         }
246
247         g_slist_free(drvc->instances);
248         drvc->instances = NULL;
249
250         return SR_OK;
251 }
252
253 static int hw_init(struct sr_context *sr_ctx)
254 {
255         return std_hw_init(sr_ctx, di, DRIVER_LOG_DOMAIN);
256 }
257
258 static GSList *hw_scan(GSList *options)
259 {
260         struct sr_dev_inst *sdi;
261         const struct dso_profile *prof;
262         struct drv_context *drvc;
263         struct dev_context *devc;
264         GSList *devices;
265         struct libusb_device_descriptor des;
266         libusb_device **devlist;
267         int devcnt, ret, i, j;
268
269         (void)options;
270
271         drvc = di->priv;
272         drvc->instances = NULL;
273
274         devcnt = 0;
275         devices = 0;
276
277         clear_instances();
278
279         /* Find all Hantek DSO devices and upload firmware to all of them. */
280         libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
281         for (i = 0; devlist[i]; i++) {
282                 if ((ret = libusb_get_device_descriptor(devlist[i], &des))) {
283                         sr_err("Failed to get device descriptor: %s.",
284                                libusb_error_name(ret));
285                         continue;
286                 }
287
288                 prof = NULL;
289                 for (j = 0; dev_profiles[j].orig_vid; j++) {
290                         if (des.idVendor == dev_profiles[j].orig_vid
291                                 && des.idProduct == dev_profiles[j].orig_pid) {
292                                 /* Device matches the pre-firmware profile. */
293                                 prof = &dev_profiles[j];
294                                 sr_dbg("Found a %s %s.", prof->vendor, prof->model);
295                                 sdi = dso_dev_new(devcnt, prof);
296                                 devices = g_slist_append(devices, sdi);
297                                 devc = sdi->priv;
298                                 if (ezusb_upload_firmware(devlist[i], USB_CONFIGURATION,
299                                                 prof->firmware) == SR_OK)
300                                         /* Remember when the firmware on this device was updated */
301                                         devc->fw_updated = g_get_monotonic_time();
302                                 else
303                                         sr_err("Firmware upload failed for "
304                                                "device %d.", devcnt);
305                                 /* Dummy USB address of 0xff will get overwritten later. */
306                                 devc->usb = sr_usb_dev_inst_new(
307                                                 libusb_get_bus_number(devlist[i]), 0xff, NULL);
308                                 devcnt++;
309                                 break;
310                         } else if (des.idVendor == dev_profiles[j].fw_vid
311                                 && des.idProduct == dev_profiles[j].fw_pid) {
312                                 /* Device matches the post-firmware profile. */
313                                 prof = &dev_profiles[j];
314                                 sr_dbg("Found a %s %s.", prof->vendor, prof->model);
315                                 sdi = dso_dev_new(devcnt, prof);
316                                 sdi->status = SR_ST_INACTIVE;
317                                 devices = g_slist_append(devices, sdi);
318                                 devc = sdi->priv;
319                                 devc->usb = sr_usb_dev_inst_new(
320                                                 libusb_get_bus_number(devlist[i]),
321                                                 libusb_get_device_address(devlist[i]), NULL);
322                                 devcnt++;
323                                 break;
324                         }
325                 }
326                 if (!prof)
327                         /* not a supported VID/PID */
328                         continue;
329         }
330         libusb_free_device_list(devlist, 1);
331
332         return devices;
333 }
334
335 static GSList *hw_dev_list(void)
336 {
337         return ((struct drv_context *)(di->priv))->instances;
338 }
339
340 static int hw_dev_open(struct sr_dev_inst *sdi)
341 {
342         struct dev_context *devc;
343         int64_t timediff_us, timediff_ms;
344         int err;
345
346         devc = sdi->priv;
347
348         /*
349          * If the firmware was recently uploaded, wait up to MAX_RENUM_DELAY_MS
350          * for the FX2 to renumerate.
351          */
352         err = SR_ERR;
353         if (devc->fw_updated > 0) {
354                 sr_info("Waiting for device to reset.");
355                 /* Takes >= 300ms for the FX2 to be gone from the USB bus. */
356                 g_usleep(300 * 1000);
357                 timediff_ms = 0;
358                 while (timediff_ms < MAX_RENUM_DELAY_MS) {
359                         if ((err = dso_open(sdi)) == SR_OK)
360                                 break;
361                         g_usleep(100 * 1000);
362                         timediff_us = g_get_monotonic_time() - devc->fw_updated;
363                         timediff_ms = timediff_us / 1000;
364                         sr_spew("Waited %" PRIi64 " ms.", timediff_ms);
365                 }
366                 sr_info("Device came back after %d ms.", timediff_ms);
367         } else {
368                 err = dso_open(sdi);
369         }
370
371         if (err != SR_OK) {
372                 sr_err("Unable to open device.");
373                 return SR_ERR;
374         }
375
376         err = libusb_claim_interface(devc->usb->devhdl, USB_INTERFACE);
377         if (err != 0) {
378                 sr_err("Unable to claim interface: %s.",
379                        libusb_error_name(err));
380                 return SR_ERR;
381         }
382
383         return SR_OK;
384 }
385
386 static int hw_dev_close(struct sr_dev_inst *sdi)
387 {
388         dso_close(sdi);
389
390         return SR_OK;
391 }
392
393 static int hw_cleanup(void)
394 {
395         struct drv_context *drvc;
396
397         if (!(drvc = di->priv))
398                 return SR_OK;
399
400         clear_instances();
401
402         return SR_OK;
403 }
404
405 static int config_set(int id, GVariant *data, const struct sr_dev_inst *sdi)
406 {
407         struct dev_context *devc;
408         double tmp_double;
409         uint64_t tmp_u64;
410         int32_t p, q;
411         int tmp_int, ret;
412         unsigned int i;
413         const char *tmp_str;
414         char **targets;
415
416         if (sdi->status != SR_ST_ACTIVE)
417                 return SR_ERR;
418
419         ret = SR_OK;
420         devc = sdi->priv;
421         switch (id) {
422         case SR_CONF_LIMIT_FRAMES:
423                 devc->limit_frames = g_variant_get_uint64(data);
424                 break;
425         case SR_CONF_TRIGGER_SLOPE:
426                 tmp_u64 = g_variant_get_uint64(data);
427                 if (tmp_u64 != SLOPE_NEGATIVE && tmp_u64 != SLOPE_POSITIVE)
428                         ret = SR_ERR_ARG;
429                 devc->triggerslope = tmp_u64;
430                 break;
431         case SR_CONF_HORIZ_TRIGGERPOS:
432                 tmp_double = g_variant_get_double(data);
433                 if (tmp_double < 0.0 || tmp_double > 1.0) {
434                         sr_err("Trigger position should be between 0.0 and 1.0.");
435                         ret = SR_ERR_ARG;
436                 } else
437                         devc->triggerposition = tmp_double;
438                 break;
439         case SR_CONF_BUFFERSIZE:
440                 tmp_u64 = g_variant_get_uint64(data);
441                 for (i = 0; buffersizes[i]; i++) {
442                         if (buffersizes[i] == tmp_u64) {
443                                 devc->framesize = tmp_u64;
444                                 break;
445                         }
446                 }
447                 if (buffersizes[i] == 0)
448                         ret = SR_ERR_ARG;
449                 break;
450         case SR_CONF_TIMEBASE:
451                 g_variant_get(data, "(ii)", &p, &q);
452                 tmp_int = -1;
453                 for (i = 0; i < ARRAY_SIZE(timebases); i++) {
454                         if (timebases[i][0] == p && timebases[i][1] == q) {
455                                 tmp_int = i;
456                                 break;
457                         }
458                 }
459                 if (tmp_int >= 0)
460                         devc->timebase = tmp_int;
461                 else
462                         ret = SR_ERR_ARG;
463                 break;
464         case SR_CONF_TRIGGER_SOURCE:
465                 tmp_str = g_variant_get_string(data, NULL);
466                 for (i = 0; trigger_sources[i]; i++) {
467                         if (!strcmp(tmp_str, trigger_sources[i])) {
468                                 devc->triggersource = g_strdup(tmp_str);
469                                 break;
470                         }
471                 }
472                 if (trigger_sources[i] == 0)
473                         ret = SR_ERR_ARG;
474                 break;
475         case SR_CONF_FILTER:
476                 tmp_str = g_variant_get_string(data, NULL);
477                 devc->filter_ch1 = devc->filter_ch2 = devc->filter_trigger = 0;
478                 targets = g_strsplit(tmp_str, ",", 0);
479                 for (i = 0; targets[i]; i++) {
480                         if (targets[i] == '\0')
481                                 /* Empty filter string can be used to clear them all. */
482                                 ;
483                         else if (!strcmp(targets[i], "CH1"))
484                                 devc->filter_ch1 = TRUE;
485                         else if (!strcmp(targets[i], "CH2"))
486                                 devc->filter_ch2 = TRUE;
487                         else if (!strcmp(targets[i], "TRIGGER"))
488                                 devc->filter_trigger = TRUE;
489                         else {
490                                 sr_err("Invalid filter target %s.", targets[i]);
491                                 ret = SR_ERR_ARG;
492                         }
493                 }
494                 g_strfreev(targets);
495                 break;
496         case SR_CONF_VDIV:
497                 /* TODO: Not supporting vdiv per channel yet. */
498                 g_variant_get(data, "(ii)", &p, &q);
499                 tmp_int = -1;
500                 for (i = 0; i < ARRAY_SIZE(vdivs); i++) {
501                         if (vdivs[i][0] == p && vdivs[i][1] == q) {
502                                 tmp_int = i;
503                                 break;
504                         }
505                 }
506                 if (tmp_int >= 0) {
507                         devc->voltage_ch1 = tmp_int;
508                         devc->voltage_ch2 = tmp_int;
509                 } else
510                         ret = SR_ERR_ARG;
511                 break;
512         case SR_CONF_COUPLING:
513                 tmp_str = g_variant_get_string(data, NULL);
514                 /* TODO: Not supporting coupling per channel yet. */
515                 for (i = 0; coupling[i]; i++) {
516                         if (!strcmp(tmp_str, coupling[i])) {
517                                 devc->coupling_ch1 = i;
518                                 devc->coupling_ch2 = i;
519                                 break;
520                         }
521                 }
522                 if (coupling[i] == 0)
523                         ret = SR_ERR_ARG;
524                 break;
525         default:
526                 ret = SR_ERR_ARG;
527                 break;
528         }
529
530         return ret;
531 }
532
533 static int config_list(int key, GVariant **data, const struct sr_dev_inst *sdi)
534 {
535
536         (void)sdi;
537
538         switch (key) {
539         case SR_CONF_DEVICE_OPTIONS:
540                 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_INT32,
541                                 devopts, ARRAY_SIZE(devopts), sizeof(int32_t));
542                 break;
543         case SR_CONF_BUFFERSIZE:
544                 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT64,
545                                 buffersizes, ARRAY_SIZE(buffersizes), sizeof(uint64_t));
546                 break;
547         case SR_CONF_COUPLING:
548                 *data = g_variant_new_strv(coupling, ARRAY_SIZE(coupling));
549                 break;
550         case SR_CONF_VDIV:
551                 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_INT32,
552                                 vdivs, ARRAY_SIZE(vdivs) * 2, sizeof(int32_t));
553                 break;
554         case SR_CONF_FILTER:
555                 *data = g_variant_new_strv(filter_targets,
556                                 ARRAY_SIZE(filter_targets));
557                 break;
558         case SR_CONF_TIMEBASE:
559                 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_INT32,
560                                 timebases, ARRAY_SIZE(timebases) * 2, sizeof(int32_t));
561                 break;
562         case SR_CONF_TRIGGER_SOURCE:
563                 *data = g_variant_new_strv(trigger_sources,
564                                 ARRAY_SIZE(trigger_sources));
565                 break;
566         default:
567                 return SR_ERR_ARG;
568         }
569
570         return SR_OK;
571 }
572
573 static void send_chunk(struct sr_dev_inst *sdi, unsigned char *buf,
574                 int num_samples)
575 {
576         struct sr_datafeed_packet packet;
577         struct sr_datafeed_analog analog;
578         struct dev_context *devc;
579         float ch1, ch2, range;
580         int num_probes, data_offset, i;
581
582         devc = sdi->priv;
583         num_probes = (devc->ch1_enabled && devc->ch2_enabled) ? 2 : 1;
584         packet.type = SR_DF_ANALOG;
585         packet.payload = &analog;
586         /* TODO: support for 5xxx series 9-bit samples */
587         analog.probes = devc->enabled_probes;
588         analog.num_samples = num_samples;
589         analog.mq = SR_MQ_VOLTAGE;
590         analog.unit = SR_UNIT_VOLT;
591         /* TODO: Check malloc return value. */
592         analog.data = g_try_malloc(analog.num_samples * sizeof(float) * num_probes);
593         data_offset = 0;
594         for (i = 0; i < analog.num_samples; i++) {
595                 /*
596                  * The device always sends data for both channels. If a channel
597                  * is disabled, it contains a copy of the enabled channel's
598                  * data. However, we only send the requested channels to
599                  * the bus.
600                  *
601                  * Voltage values are encoded as a value 0-255 (0-512 on the
602                  * DSO-5200*), where the value is a point in the range
603                  * represented by the vdiv setting. There are 8 vertical divs,
604                  * so e.g. 500mV/div represents 4V peak-to-peak where 0 = -2V
605                  * and 255 = +2V.
606                  */
607                 /* TODO: Support for DSO-5xxx series 9-bit samples. */
608                 if (devc->ch1_enabled) {
609                         range = ((float)vdivs[devc->voltage_ch1][0] / vdivs[devc->voltage_ch1][1]) * 8;
610                         ch1 = range / 255 * *(buf + i * 2 + 1);
611                         /* Value is centered around 0V. */
612                         ch1 -= range / 2;
613                         analog.data[data_offset++] = ch1;
614                 }
615                 if (devc->ch2_enabled) {
616                         range = ((float)vdivs[devc->voltage_ch2][0] / vdivs[devc->voltage_ch2][1]) * 8;
617                         ch2 = range / 255 * *(buf + i * 2);
618                         ch2 -= range / 2;
619                         analog.data[data_offset++] = ch2;
620                 }
621         }
622         sr_session_send(devc->cb_data, &packet);
623 }
624
625 /*
626  * Called by libusb (as triggered by handle_event()) when a transfer comes in.
627  * Only channel data comes in asynchronously, and all transfers for this are
628  * queued up beforehand, so this just needs to chuck the incoming data onto
629  * the libsigrok session bus.
630  */
631 static void receive_transfer(struct libusb_transfer *transfer)
632 {
633         struct sr_datafeed_packet packet;
634         struct sr_dev_inst *sdi;
635         struct dev_context *devc;
636         int num_samples, pre;
637
638         sdi = transfer->user_data;
639         devc = sdi->priv;
640         sr_dbg("receive_transfer(): status %d received %d bytes.",
641                transfer->status, transfer->actual_length);
642
643         if (transfer->actual_length == 0)
644                 /* Nothing to send to the bus. */
645                 return;
646
647         num_samples = transfer->actual_length / 2;
648
649         sr_dbg("Got %d-%d/%d samples in frame.", devc->samp_received + 1,
650                devc->samp_received + num_samples, devc->framesize);
651
652         /*
653          * The device always sends a full frame, but the beginning of the frame
654          * doesn't represent the trigger point. The offset at which the trigger
655          * happened came in with the capture state, so we need to start sending
656          * from there up the session bus. The samples in the frame buffer
657          * before that trigger point came after the end of the device's frame
658          * buffer was reached, and it wrapped around to overwrite up until the
659          * trigger point.
660          */
661         if (devc->samp_received < devc->trigger_offset) {
662                 /* Trigger point not yet reached. */
663                 if (devc->samp_received + num_samples < devc->trigger_offset) {
664                         /* The entire chunk is before the trigger point. */
665                         memcpy(devc->framebuf + devc->samp_buffered * 2,
666                                         transfer->buffer, num_samples * 2);
667                         devc->samp_buffered += num_samples;
668                 } else {
669                         /*
670                          * This chunk hits or overruns the trigger point.
671                          * Store the part before the trigger fired, and
672                          * send the rest up to the session bus.
673                          */
674                         pre = devc->trigger_offset - devc->samp_received;
675                         memcpy(devc->framebuf + devc->samp_buffered * 2,
676                                         transfer->buffer, pre * 2);
677                         devc->samp_buffered += pre;
678
679                         /* The rest of this chunk starts with the trigger point. */
680                         sr_dbg("Reached trigger point, %d samples buffered.",
681                                devc->samp_buffered);
682
683                         /* Avoid the corner case where the chunk ended at
684                          * exactly the trigger point. */
685                         if (num_samples > pre)
686                                 send_chunk(sdi, transfer->buffer + pre * 2,
687                                                 num_samples - pre);
688                 }
689         } else {
690                 /* Already past the trigger point, just send it all out. */
691                 send_chunk(sdi, transfer->buffer,
692                                 num_samples);
693         }
694
695         devc->samp_received += num_samples;
696
697         /* Everything in this transfer was either copied to the buffer or
698          * sent to the session bus. */
699         g_free(transfer->buffer);
700         libusb_free_transfer(transfer);
701
702         if (devc->samp_received >= devc->framesize) {
703                 /* That was the last chunk in this frame. Send the buffered
704                  * pre-trigger samples out now, in one big chunk. */
705                 sr_dbg("End of frame, sending %d pre-trigger buffered samples.",
706                        devc->samp_buffered);
707                 send_chunk(sdi, devc->framebuf, devc->samp_buffered);
708
709                 /* Mark the end of this frame. */
710                 packet.type = SR_DF_FRAME_END;
711                 sr_session_send(devc->cb_data, &packet);
712
713                 if (devc->limit_frames && ++devc->num_frames == devc->limit_frames) {
714                         /* Terminate session */
715                         devc->dev_state = STOPPING;
716                 } else {
717                         devc->dev_state = NEW_CAPTURE;
718                 }
719         }
720 }
721
722 static int handle_event(int fd, int revents, void *cb_data)
723 {
724         const struct sr_dev_inst *sdi;
725         struct sr_datafeed_packet packet;
726         struct timeval tv;
727         struct dev_context *devc;
728         struct drv_context *drvc = di->priv;
729         const struct libusb_pollfd **lupfd;
730         int num_probes, i;
731         uint32_t trigger_offset;
732         uint8_t capturestate;
733
734         (void)fd;
735         (void)revents;
736
737         sdi = cb_data;
738         devc = sdi->priv;
739         if (devc->dev_state == STOPPING) {
740                 /* We've been told to wind up the acquisition. */
741                 sr_dbg("Stopping acquisition.");
742                 /*
743                  * TODO: Doesn't really cancel pending transfers so they might
744                  * come in after SR_DF_END is sent.
745                  */
746                 lupfd = libusb_get_pollfds(drvc->sr_ctx->libusb_ctx);
747                 for (i = 0; lupfd[i]; i++)
748                         sr_source_remove(lupfd[i]->fd);
749                 free(lupfd);
750
751                 packet.type = SR_DF_END;
752                 sr_session_send(sdi, &packet);
753
754                 devc->dev_state = IDLE;
755
756                 return TRUE;
757         }
758
759         /* Always handle pending libusb events. */
760         tv.tv_sec = tv.tv_usec = 0;
761         libusb_handle_events_timeout(drvc->sr_ctx->libusb_ctx, &tv);
762
763         /* TODO: ugh */
764         if (devc->dev_state == NEW_CAPTURE) {
765                 if (dso_capture_start(devc) != SR_OK)
766                         return TRUE;
767                 if (dso_enable_trigger(devc) != SR_OK)
768                         return TRUE;
769 //              if (dso_force_trigger(devc) != SR_OK)
770 //                      return TRUE;
771                 sr_dbg("Successfully requested next chunk.");
772                 devc->dev_state = CAPTURE;
773                 return TRUE;
774         }
775         if (devc->dev_state != CAPTURE)
776                 return TRUE;
777
778         if ((dso_get_capturestate(devc, &capturestate, &trigger_offset)) != SR_OK)
779                 return TRUE;
780
781         sr_dbg("Capturestate %d.", capturestate);
782         sr_dbg("Trigger offset 0x%.6x.", trigger_offset);
783         switch (capturestate) {
784         case CAPTURE_EMPTY:
785                 if (++devc->capture_empty_count >= MAX_CAPTURE_EMPTY) {
786                         devc->capture_empty_count = 0;
787                         if (dso_capture_start(devc) != SR_OK)
788                                 break;
789                         if (dso_enable_trigger(devc) != SR_OK)
790                                 break;
791 //                      if (dso_force_trigger(devc) != SR_OK)
792 //                              break;
793                         sr_dbg("Successfully requested next chunk.");
794                 }
795                 break;
796         case CAPTURE_FILLING:
797                 /* No data yet. */
798                 break;
799         case CAPTURE_READY_8BIT:
800                 /* Remember where in the captured frame the trigger is. */
801                 devc->trigger_offset = trigger_offset;
802
803                 num_probes = (devc->ch1_enabled && devc->ch2_enabled) ? 2 : 1;
804                 /* TODO: Check malloc return value. */
805                 devc->framebuf = g_try_malloc(devc->framesize * num_probes * 2);
806                 devc->samp_buffered = devc->samp_received = 0;
807
808                 /* Tell the scope to send us the first frame. */
809                 if (dso_get_channeldata(sdi, receive_transfer) != SR_OK)
810                         break;
811
812                 /*
813                  * Don't hit the state machine again until we're done fetching
814                  * the data we just told the scope to send.
815                  */
816                 devc->dev_state = FETCH_DATA;
817
818                 /* Tell the frontend a new frame is on the way. */
819                 packet.type = SR_DF_FRAME_BEGIN;
820                 sr_session_send(sdi, &packet);
821                 break;
822         case CAPTURE_READY_9BIT:
823                 /* TODO */
824                 sr_err("Not yet supported.");
825                 break;
826         case CAPTURE_TIMEOUT:
827                 /* Doesn't matter, we'll try again next time. */
828                 break;
829         default:
830                 sr_dbg("Unknown capture state: %d.", capturestate);
831                 break;
832         }
833
834         return TRUE;
835 }
836
837 static int hw_dev_acquisition_start(const struct sr_dev_inst *sdi,
838                                     void *cb_data)
839 {
840         const struct libusb_pollfd **lupfd;
841         struct dev_context *devc;
842         struct drv_context *drvc = di->priv;
843         int i;
844
845         if (sdi->status != SR_ST_ACTIVE)
846                 return SR_ERR;
847
848         devc = sdi->priv;
849         devc->cb_data = cb_data;
850
851         if (configure_probes(sdi) != SR_OK) {
852                 sr_err("Failed to configure probes.");
853                 return SR_ERR;
854         }
855
856         if (dso_init(devc) != SR_OK)
857                 return SR_ERR;
858
859         if (dso_capture_start(devc) != SR_OK)
860                 return SR_ERR;
861
862         devc->dev_state = CAPTURE;
863         lupfd = libusb_get_pollfds(drvc->sr_ctx->libusb_ctx);
864         for (i = 0; lupfd[i]; i++)
865                 sr_source_add(lupfd[i]->fd, lupfd[i]->events, TICK,
866                               handle_event, (void *)sdi);
867         free(lupfd);
868
869         /* Send header packet to the session bus. */
870         std_session_send_df_header(cb_data, DRIVER_LOG_DOMAIN);
871
872         return SR_OK;
873 }
874
875 static int hw_dev_acquisition_stop(struct sr_dev_inst *sdi, void *cb_data)
876 {
877         struct dev_context *devc;
878
879         (void)cb_data;
880
881         if (sdi->status != SR_ST_ACTIVE)
882                 return SR_ERR;
883
884         devc = sdi->priv;
885         devc->dev_state = STOPPING;
886
887         return SR_OK;
888 }
889
890 SR_PRIV struct sr_dev_driver hantek_dso_driver_info = {
891         .name = "hantek-dso",
892         .longname = "Hantek DSO",
893         .api_version = 1,
894         .init = hw_init,
895         .cleanup = hw_cleanup,
896         .scan = hw_scan,
897         .dev_list = hw_dev_list,
898         .dev_clear = clear_instances,
899         .config_get = NULL,
900         .config_set = config_set,
901         .config_list = config_list,
902         .dev_open = hw_dev_open,
903         .dev_close = hw_dev_close,
904         .dev_acquisition_start = hw_dev_acquisition_start,
905         .dev_acquisition_stop = hw_dev_acquisition_stop,
906         .priv = NULL,
907 };