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