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