2 * This file is part of the sigrok project.
4 * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
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.
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.
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/>.
23 #include <sys/types.h>
33 #include "sigrok-internal.h"
38 /* Max time in ms before we want to check on USB events */
39 /* TODO tune this properly */
42 static const int hwcaps[] = {
43 SR_HWCAP_OSCILLOSCOPE,
44 SR_HWCAP_LIMIT_SAMPLES,
48 SR_HWCAP_TRIGGER_SOURCE,
49 SR_HWCAP_TRIGGER_SLOPE,
50 SR_HWCAP_HORIZ_TRIGGERPOS,
57 static const char *probe_names[] = {
63 static const struct dso_profile dev_profiles[] = {
68 FIRMWARE_DIR "/hantek-dso-2090.fw" },
69 { 0, 0, 0, 0, 0, 0, 0, 0, 0 },
72 static const uint64_t buffersizes[] = {
79 static const struct sr_rational timebases[] = {
100 static const struct sr_rational vdivs[] = {
115 static const char *trigger_sources[] = {
122 static const char *filter_targets[] = {
125 /* TODO: "TRIGGER", */
129 static const char *coupling[] = {
136 SR_PRIV libusb_context *usb_context = NULL;
137 SR_PRIV GSList *dev_insts = NULL;
139 static struct sr_dev_inst *dso_dev_new(int index, const struct dso_profile *prof)
141 struct sr_dev_inst *sdi;
144 sdi = sr_dev_inst_new(index, SR_ST_INITIALIZING,
145 prof->vendor, prof->model, prof->model_version);
149 if (!(ctx = g_try_malloc0(sizeof(struct context)))) {
150 sr_err("hantek-dso: ctx malloc failed");
154 ctx->dev_state = IDLE;
155 ctx->timebase = DEFAULT_TIMEBASE;
156 ctx->ch1_enabled = TRUE;
157 ctx->ch2_enabled = TRUE;
158 ctx->voltage_ch1 = DEFAULT_VOLTAGE;
159 ctx->voltage_ch2 = DEFAULT_VOLTAGE;
160 ctx->coupling_ch1 = DEFAULT_COUPLING;
161 ctx->coupling_ch2 = DEFAULT_COUPLING;
162 ctx->voffset_ch1 = DEFAULT_VERT_OFFSET;
163 ctx->voffset_ch2 = DEFAULT_VERT_OFFSET;
164 ctx->voffset_trigger = DEFAULT_VERT_TRIGGERPOS;
165 ctx->framesize = DEFAULT_FRAMESIZE;
166 ctx->triggerslope = SLOPE_POSITIVE;
167 ctx->triggersource = g_strdup(DEFAULT_TRIGGER_SOURCE);
168 ctx->triggerposition = DEFAULT_HORIZ_TRIGGERPOS;
170 dev_insts = g_slist_append(dev_insts, sdi);
175 static int configure_probes(struct context *ctx, const GSList *probes)
177 const struct sr_probe *probe;
180 ctx->ch1_enabled = ctx->ch2_enabled = FALSE;
181 for (l = probes; l; l = l->next) {
182 probe = (struct sr_probe *)l->data;
183 if (probe->index == 1)
184 ctx->ch1_enabled = probe->enabled;
185 else if (probe->index == 2)
186 ctx->ch2_enabled = probe->enabled;
192 static int hw_init(const char *devinfo)
194 struct sr_dev_inst *sdi;
195 struct libusb_device_descriptor des;
196 const struct dso_profile *prof;
198 libusb_device **devlist;
199 int err, devcnt, i, j;
201 /* Avoid compiler warnings. */
204 if (libusb_init(&usb_context) != 0) {
205 sr_err("hantek-dso: Failed to initialize USB.");
209 /* Find all Hantek DSO devices and upload firmware to all of them. */
211 libusb_get_device_list(usb_context, &devlist);
212 for (i = 0; devlist[i]; i++) {
213 if ((err = libusb_get_device_descriptor(devlist[i], &des))) {
214 sr_err("hantek-dso: failed to get device descriptor: %d", err);
219 for (j = 0; dev_profiles[j].orig_vid; j++) {
220 if (des.idVendor == dev_profiles[j].orig_vid
221 && des.idProduct == dev_profiles[j].orig_pid) {
222 /* Device matches the pre-firmware profile. */
223 prof = &dev_profiles[j];
224 sr_dbg("hantek-dso: Found a %s %s.", prof->vendor, prof->model);
225 sdi = dso_dev_new(devcnt, prof);
227 if (ezusb_upload_firmware(devlist[i], USB_CONFIGURATION,
228 prof->firmware) == SR_OK)
229 /* Remember when the firmware on this device was updated */
230 ctx->fw_updated = g_get_monotonic_time();
232 sr_err("hantek-dso: firmware upload failed for "
233 "device %d", devcnt);
234 /* Dummy USB address of 0xff will get overwritten later. */
235 ctx->usb = sr_usb_dev_inst_new(
236 libusb_get_bus_number(devlist[i]), 0xff, NULL);
239 } else if (des.idVendor == dev_profiles[j].fw_vid
240 && des.idProduct == dev_profiles[j].fw_pid) {
241 /* Device matches the post-firmware profile. */
242 prof = &dev_profiles[j];
243 sr_dbg("hantek-dso: Found a %s %s.", prof->vendor, prof->model);
244 sdi = dso_dev_new(devcnt, prof);
245 sdi->status = SR_ST_INACTIVE;
247 ctx->usb = sr_usb_dev_inst_new(
248 libusb_get_bus_number(devlist[i]),
249 libusb_get_device_address(devlist[i]), NULL);
255 /* not a supported VID/PID */
258 libusb_free_device_list(devlist, 1);
263 static int hw_dev_open(int dev_index)
265 struct sr_dev_inst *sdi;
267 int64_t timediff_us, timediff_ms;
270 if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
275 * if the firmware was recently uploaded, wait up to MAX_RENUM_DELAY_MS
276 * for the FX2 to renumerate
279 if (ctx->fw_updated > 0) {
280 sr_info("hantek-dso: waiting for device to reset");
281 /* takes at least 300ms for the FX2 to be gone from the USB bus */
282 g_usleep(300 * 1000);
284 while (timediff_ms < MAX_RENUM_DELAY_MS) {
285 if ((err = dso_open(dev_index)) == SR_OK)
287 g_usleep(100 * 1000);
288 timediff_us = g_get_monotonic_time() - ctx->fw_updated;
289 timediff_ms = timediff_us / 1000;
290 sr_spew("fx2lafw: waited %" PRIi64 " ms", timediff_ms);
292 sr_info("hantek-dso: device came back after %d ms", timediff_ms);
294 err = dso_open(dev_index);
298 sr_err("hantek-dso: unable to open device");
302 err = libusb_claim_interface(ctx->usb->devhdl, USB_INTERFACE);
304 sr_err("hantek-dso: Unable to claim interface: %d", err);
311 static int hw_dev_close(int dev_index)
313 struct sr_dev_inst *sdi;
315 if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
323 static int hw_cleanup(void)
326 struct sr_dev_inst *sdi;
329 /* Properly close and free all devices. */
330 for (l = dev_insts; l; l = l->next) {
331 if (!(sdi = l->data)) {
332 /* Log error, but continue cleaning up the rest. */
333 sr_err("hantek-dso: %s: sdi was NULL, continuing", __func__);
336 if (!(ctx = sdi->priv)) {
337 /* Log error, but continue cleaning up the rest. */
338 sr_err("hantek-dso: %s: sdi->priv was NULL, continuing", __func__);
342 sr_usb_dev_inst_free(ctx->usb);
343 g_free(ctx->triggersource);
345 sr_dev_inst_free(sdi);
348 g_slist_free(dev_insts);
352 libusb_exit(usb_context);
358 static const void *hw_dev_info_get(int dev_index, int dev_info_id)
360 struct sr_dev_inst *sdi;
365 if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
370 switch (dev_info_id) {
374 case SR_DI_NUM_PROBES:
375 info = GINT_TO_POINTER(ctx->profile->num_probes);
377 case SR_DI_PROBE_NAMES:
380 case SR_DI_BUFFERSIZES:
383 case SR_DI_TIMEBASES:
386 case SR_DI_TRIGGER_SOURCES:
387 info = trigger_sources;
390 info = filter_targets;
398 /* TODO remove this */
399 case SR_DI_CUR_SAMPLERATE:
407 static int hw_dev_status_get(int dev_index)
409 struct sr_dev_inst *sdi;
411 if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
412 return SR_ST_NOT_FOUND;
417 static const int *hw_hwcap_get_all(void)
422 static int hw_dev_config_set(int dev_index, int hwcap, const void *value)
424 struct sr_dev_inst *sdi;
426 struct sr_rational tmp_rat;
432 if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
435 if (sdi->status != SR_ST_ACTIVE)
441 case SR_HWCAP_LIMIT_FRAMES:
442 ctx->limit_frames = *(const uint64_t *)value;
444 case SR_HWCAP_PROBECONFIG:
445 ret = configure_probes(ctx, (const GSList *)value);
447 case SR_HWCAP_TRIGGER_SLOPE:
448 tmp_u64 = *(const int *)value;
449 if (tmp_u64 != SLOPE_NEGATIVE && tmp_u64 != SLOPE_POSITIVE)
451 ctx->triggerslope = tmp_u64;
453 case SR_HWCAP_HORIZ_TRIGGERPOS:
454 tmp_float = *(const float *)value;
455 if (tmp_float < 0.0 || tmp_float > 1.0) {
456 sr_err("hantek-dso: trigger position should be between 0.0 and 1.0");
459 ctx->triggerposition = tmp_float;
461 case SR_HWCAP_BUFFERSIZE:
462 tmp_u64 = *(const int *)value;
463 for (i = 0; buffersizes[i]; i++) {
464 if (buffersizes[i] == tmp_u64) {
465 ctx->framesize = tmp_u64;
469 if (buffersizes[i] == 0)
472 case SR_HWCAP_TIMEBASE:
473 tmp_rat = *(const struct sr_rational *)value;
474 for (i = 0; timebases[i].p && timebases[i].q; i++) {
475 if (timebases[i].p == tmp_rat.p
476 && timebases[i].q == tmp_rat.q) {
481 if (timebases[i].p == 0 && timebases[i].q == 0)
484 case SR_HWCAP_TRIGGER_SOURCE:
485 for (i = 0; trigger_sources[i]; i++) {
486 if (!strcmp(value, trigger_sources[i])) {
487 ctx->triggersource = g_strdup(value);
491 if (trigger_sources[i] == 0)
494 case SR_HWCAP_FILTER:
495 ctx->filter_ch1 = ctx->filter_ch2 = ctx->filter_trigger = 0;
496 targets = g_strsplit(value, ",", 0);
497 for (i = 0; targets[i]; i++) {
498 if (targets[i] == '\0')
499 /* Empty filter string can be used to clear them all. */
501 else if (!strcmp(targets[i], "CH1"))
502 ctx->filter_ch1 = TRUE;
503 else if (!strcmp(targets[i], "CH2"))
504 ctx->filter_ch2 = TRUE;
505 else if (!strcmp(targets[i], "TRIGGER"))
506 ctx->filter_trigger = TRUE;
508 sr_err("invalid filter target %s", targets[i]);
515 /* TODO not supporting vdiv per channel yet */
516 tmp_rat = *(const struct sr_rational *)value;
517 for (i = 0; vdivs[i].p && vdivs[i].q; i++) {
518 if (vdivs[i].p == tmp_rat.p
519 && vdivs[i].q == tmp_rat.q) {
520 ctx->voltage_ch1 = i;
521 ctx->voltage_ch2 = i;
525 if (vdivs[i].p == 0 && vdivs[i].q == 0)
528 case SR_HWCAP_COUPLING:
529 /* TODO not supporting coupling per channel yet */
530 for (i = 0; coupling[i]; i++) {
531 if (!strcmp(value, coupling[i])) {
532 ctx->coupling_ch1 = i;
533 ctx->coupling_ch2 = i;
537 if (coupling[i] == 0)
547 static void send_chunk(struct context *ctx, unsigned char *buf,
550 struct sr_datafeed_packet packet;
551 struct sr_datafeed_analog analog;
552 float ch1, ch2, range;
553 int num_probes, data_offset, i;
555 num_probes = (ctx->ch1_enabled && ctx->ch2_enabled) ? 2 : 1;
556 packet.type = SR_DF_ANALOG;
557 packet.payload = &analog;
558 /* TODO: support for 5xxx series 9-bit samples */
559 analog.num_samples = num_samples;
560 analog.mq = SR_MQ_VOLTAGE;
561 analog.unit = SR_UNIT_VOLT;
562 analog.data = g_try_malloc(analog.num_samples * sizeof(float) * num_probes);
564 for (i = 0; i < analog.num_samples; i++) {
565 /* The device always sends data for both channels. If a channel
566 * is disabled, it contains a copy of the enabled channel's
567 * data. However, we only send the requested channels to the bus.
569 * Voltage values are encoded as a value 0-255 (0-512 on the 5200*),
570 * where the value is a point in the range represented by the vdiv
571 * setting. There are 8 vertical divs, so e.g. 500mV/div represents
572 * 4V peak-to-peak where 0 = -2V and 255 = +2V.
574 /* TODO: support for 5xxx series 9-bit samples */
575 if (ctx->ch1_enabled) {
576 range = ((float)vdivs[ctx->voltage_ch1].p / vdivs[ctx->voltage_ch1].q) * 8;
577 ch1 = range / 255 * *(buf + i * 2 + 1);
578 /* Value is centered around 0V. */
580 analog.data[data_offset++] = ch1;
582 if (ctx->ch2_enabled) {
583 range = ((float)vdivs[ctx->voltage_ch2].p / vdivs[ctx->voltage_ch2].q) * 8;
584 ch2 = range / 255 * *(buf + i * 2);
586 analog.data[data_offset++] = ch2;
589 sr_session_send(ctx->cb_data, &packet);
593 /* Called by libusb (as triggered by handle_event()) when a transfer comes in.
594 * Only channel data comes in asynchronously, and all transfers for this are
595 * queued up beforehand, so this just needs so chuck the incoming data onto
596 * the libsigrok session bus.
598 static void receive_transfer(struct libusb_transfer *transfer)
600 struct sr_datafeed_packet packet;
602 int num_samples, pre;
604 ctx = transfer->user_data;
605 sr_dbg("hantek-dso: receive_transfer(): status %d received %d bytes",
606 transfer->status, transfer->actual_length);
608 if (transfer->actual_length == 0)
609 /* Nothing to send to the bus. */
612 num_samples = transfer->actual_length / 2;
614 sr_dbg("hantek-dso: got %d-%d/%d samples in frame", ctx->samp_received + 1,
615 ctx->samp_received + num_samples, ctx->framesize);
617 /* The device always sends a full frame, but the beginning of the frame
618 * doesn't represent the trigger point. The offset at which the trigger
619 * happened came in with the capture state, so we need to start sending
620 * from there up the session bus. The samples in the frame buffer before
621 * that trigger point came after the end of the device's frame buffer was
622 * reached, and it wrapped around to overwrite up until the trigger point.
624 if (ctx->samp_received < ctx->trigger_offset) {
625 /* Trigger point not yet reached. */
626 if (ctx->samp_received + num_samples < ctx->trigger_offset) {
627 /* The entire chunk is before the trigger point. */
628 memcpy(ctx->framebuf + ctx->samp_buffered * 2,
629 transfer->buffer, num_samples * 2);
630 ctx->samp_buffered += num_samples;
632 /* This chunk hits or overruns the trigger point.
633 * Store the part before the trigger fired, and
634 * send the rest up to the session bus. */
635 pre = ctx->trigger_offset - ctx->samp_received;
636 memcpy(ctx->framebuf + ctx->samp_buffered * 2,
637 transfer->buffer, pre * 2);
638 ctx->samp_buffered += pre;
640 /* The rest of this chunk starts with the trigger point. */
641 sr_dbg("hantek-dso: reached trigger point, %d samples buffered",
644 /* Avoid the corner case where the chunk ended at
645 * exactly the trigger point. */
646 if (num_samples > pre)
647 send_chunk(ctx, transfer->buffer + pre * 2,
651 /* Already past the trigger point, just send it all out. */
652 send_chunk(ctx, transfer->buffer,
656 ctx->samp_received += num_samples;
658 /* Everything in this transfer was either copied to the buffer or
659 * sent to the session bus. */
660 g_free(transfer->buffer);
661 libusb_free_transfer(transfer);
663 if (ctx->samp_received >= ctx->framesize) {
664 /* That was the last chunk in this frame. Send the buffered
665 * pre-trigger samples out now, in one big chunk. */
666 sr_dbg("hantek-dso: end of frame, sending %d pre-trigger buffered samples",
668 send_chunk(ctx, ctx->framebuf, ctx->samp_buffered);
670 /* Mark the end of this frame. */
671 packet.type = SR_DF_FRAME_END;
672 sr_session_send(ctx->cb_data, &packet);
674 if (ctx->limit_frames && ++ctx->num_frames == ctx->limit_frames) {
675 /* Terminate session */
676 /* TODO: don't leave pending USB transfers hanging */
677 packet.type = SR_DF_END;
678 sr_session_send(ctx->cb_data, &packet);
680 ctx->dev_state = NEW_CAPTURE;
686 static int handle_event(int fd, int revents, void *cb_data)
688 struct sr_datafeed_packet packet;
692 uint32_t trigger_offset;
693 uint8_t capturestate;
695 /* Avoid compiler warnings. */
699 /* Always handle pending libusb events. */
700 tv.tv_sec = tv.tv_usec = 0;
701 libusb_handle_events_timeout(usb_context, &tv);
705 if (ctx->dev_state == NEW_CAPTURE) {
706 if (dso_capture_start(ctx) != SR_OK)
708 if (dso_enable_trigger(ctx) != SR_OK)
710 // if (dso_force_trigger(ctx) != SR_OK)
712 sr_dbg("hantek-dso: successfully requested next chunk");
713 ctx->dev_state = CAPTURE;
716 if (ctx->dev_state != CAPTURE)
719 if ((dso_get_capturestate(ctx, &capturestate, &trigger_offset)) != SR_OK)
722 sr_dbg("hantek-dso: capturestate %d", capturestate);
723 sr_dbg("hantek-dso: trigger offset 0x%.6x", trigger_offset);
724 switch (capturestate) {
726 if (++ctx->capture_empty_count >= MAX_CAPTURE_EMPTY) {
727 ctx->capture_empty_count = 0;
728 if (dso_capture_start(ctx) != SR_OK)
730 if (dso_enable_trigger(ctx) != SR_OK)
732 // if (dso_force_trigger(ctx) != SR_OK)
734 sr_dbg("hantek-dso: successfully requested next chunk");
737 case CAPTURE_FILLING:
740 case CAPTURE_READY_8BIT:
741 /* Remember where in the captured frame the trigger is. */
742 ctx->trigger_offset = trigger_offset;
744 num_probes = (ctx->ch1_enabled && ctx->ch2_enabled) ? 2 : 1;
745 ctx->framebuf = g_try_malloc(ctx->framesize * num_probes * 2);
746 ctx->samp_buffered = ctx->samp_received = 0;
748 /* Tell the scope to send us the first frame. */
749 if (dso_get_channeldata(ctx, receive_transfer) != SR_OK)
752 /* Don't hit the state machine again until we're done fetching
753 * the data we just told the scope to send.
755 ctx->dev_state = FETCH_DATA;
757 /* Tell the frontend a new frame is on the way. */
758 packet.type = SR_DF_FRAME_BEGIN;
759 sr_session_send(cb_data, &packet);
761 case CAPTURE_READY_9BIT:
763 sr_err("not yet supported");
765 case CAPTURE_TIMEOUT:
766 /* Doesn't matter, we'll try again next time. */
769 sr_dbg("unknown capture state");
775 static int hw_dev_acquisition_start(int dev_index, void *cb_data)
777 const struct libusb_pollfd **lupfd;
778 struct sr_datafeed_packet packet;
779 struct sr_datafeed_header header;
780 struct sr_datafeed_meta_analog meta;
781 struct sr_dev_inst *sdi;
785 if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
788 if (sdi->status != SR_ST_ACTIVE)
792 ctx->cb_data = cb_data;
794 if (dso_init(ctx) != SR_OK)
797 if (dso_capture_start(ctx) != SR_OK)
800 ctx->dev_state = CAPTURE;
801 lupfd = libusb_get_pollfds(usb_context);
802 for (i = 0; lupfd[i]; i++)
803 sr_source_add(lupfd[i]->fd, lupfd[i]->events, TICK, handle_event,
807 /* Send header packet to the session bus. */
808 packet.type = SR_DF_HEADER;
809 packet.payload = (unsigned char *)&header;
810 header.feed_version = 1;
811 gettimeofday(&header.starttime, NULL);
812 sr_session_send(cb_data, &packet);
814 /* Send metadata about the SR_DF_ANALOG packets to come. */
815 packet.type = SR_DF_META_ANALOG;
816 packet.payload = &meta;
817 meta.num_probes = ctx->profile->num_probes;
818 sr_session_send(cb_data, &packet);
823 /* TODO: doesn't really cancel pending transfers so they might come in after
826 static int hw_dev_acquisition_stop(int dev_index, void *cb_data)
828 struct sr_datafeed_packet packet;
829 struct sr_dev_inst *sdi;
832 if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
835 if (sdi->status != SR_ST_ACTIVE)
839 ctx->dev_state = IDLE;
841 packet.type = SR_DF_END;
842 sr_session_send(cb_data, &packet);
847 SR_PRIV struct sr_dev_driver hantek_dso_driver_info = {
848 .name = "hantek-dso",
849 .longname = "Hantek DSO",
852 .cleanup = hw_cleanup,
853 .dev_open = hw_dev_open,
854 .dev_close = hw_dev_close,
855 .dev_info_get = hw_dev_info_get,
856 .dev_status_get = hw_dev_status_get,
857 .hwcap_get_all = hw_hwcap_get_all,
858 .dev_config_set = hw_dev_config_set,
859 .dev_acquisition_start = hw_dev_acquisition_start,
860 .dev_acquisition_stop = hw_dev_acquisition_stop,