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