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