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