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