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>
32 #include "libsigrok.h"
33 #include "libsigrok-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[] = {
64 { 0x04b4, 0x2090, 0x04b5, 0x2090,
66 FIRMWARE_DIR "/hantek-dso-2xxx.fw" },
67 { 0x04b4, 0x2150, 0x04b5, 0x2150,
69 FIRMWARE_DIR "/hantek-dso-2xxx.fw" },
70 { 0x04b4, 0x2250, 0x04b5, 0x2250,
72 FIRMWARE_DIR "/hantek-dso-2xxx.fw" },
73 { 0x04b4, 0x5200, 0x04b5, 0x5200,
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 },
82 static const uint64_t buffersizes[] = {
89 static const struct sr_rational timebases[] = {
110 static const struct sr_rational vdivs[] = {
125 static const char *trigger_sources[] = {
133 static const char *filter_targets[] = {
136 /* TODO: "TRIGGER", */
140 static const char *coupling[] = {
147 SR_PRIV libusb_context *usb_context = NULL;
148 SR_PRIV GSList *dev_insts = NULL;
150 static struct sr_dev_inst *dso_dev_new(int index, const struct dso_profile *prof)
152 struct sr_dev_inst *sdi;
155 sdi = sr_dev_inst_new(index, SR_ST_INITIALIZING,
156 prof->vendor, prof->model, NULL);
160 if (!(ctx = g_try_malloc0(sizeof(struct context)))) {
161 sr_err("hantek-dso: ctx malloc failed");
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;
181 dev_insts = g_slist_append(dev_insts, sdi);
186 static int configure_probes(struct context *ctx, const GSList *probes)
188 const struct sr_probe *probe;
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;
203 static int hw_init(void)
206 if (libusb_init(&usb_context) != 0) {
207 sr_err("hantek-dso: Failed to initialize USB.");
214 static int hw_scan(void)
216 struct sr_dev_inst *sdi;
217 struct libusb_device_descriptor des;
218 const struct dso_profile *prof;
220 libusb_device **devlist;
221 int devcnt, ret, i, j;
223 /* Find all Hantek DSO devices and upload firmware to all of them. */
225 libusb_get_device_list(usb_context, &devlist);
226 for (i = 0; devlist[i]; i++) {
227 if ((ret = libusb_get_device_descriptor(devlist[i], &des))) {
228 sr_err("hantek-dso: failed to get device descriptor: %d", ret);
233 for (j = 0; dev_profiles[j].orig_vid; j++) {
234 if (des.idVendor == dev_profiles[j].orig_vid
235 && des.idProduct == dev_profiles[j].orig_pid) {
236 /* Device matches the pre-firmware profile. */
237 prof = &dev_profiles[j];
238 sr_dbg("hantek-dso: Found a %s %s.", prof->vendor, prof->model);
239 sdi = dso_dev_new(devcnt, prof);
241 if (ezusb_upload_firmware(devlist[i], USB_CONFIGURATION,
242 prof->firmware) == SR_OK)
243 /* Remember when the firmware on this device was updated */
244 ctx->fw_updated = g_get_monotonic_time();
246 sr_err("hantek-dso: firmware upload failed for "
247 "device %d", devcnt);
248 /* Dummy USB address of 0xff will get overwritten later. */
249 ctx->usb = sr_usb_dev_inst_new(
250 libusb_get_bus_number(devlist[i]), 0xff, NULL);
253 } else if (des.idVendor == dev_profiles[j].fw_vid
254 && des.idProduct == dev_profiles[j].fw_pid) {
255 /* Device matches the post-firmware profile. */
256 prof = &dev_profiles[j];
257 sr_dbg("hantek-dso: Found a %s %s.", prof->vendor, prof->model);
258 sdi = dso_dev_new(devcnt, prof);
259 sdi->status = SR_ST_INACTIVE;
261 ctx->usb = sr_usb_dev_inst_new(
262 libusb_get_bus_number(devlist[i]),
263 libusb_get_device_address(devlist[i]), NULL);
269 /* not a supported VID/PID */
272 libusb_free_device_list(devlist, 1);
277 static int hw_dev_open(int dev_index)
279 struct sr_dev_inst *sdi;
281 int64_t timediff_us, timediff_ms;
284 if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
289 * if the firmware was recently uploaded, wait up to MAX_RENUM_DELAY_MS
290 * for the FX2 to renumerate
293 if (ctx->fw_updated > 0) {
294 sr_info("hantek-dso: waiting for device to reset");
295 /* takes at least 300ms for the FX2 to be gone from the USB bus */
296 g_usleep(300 * 1000);
298 while (timediff_ms < MAX_RENUM_DELAY_MS) {
299 if ((err = dso_open(dev_index)) == SR_OK)
301 g_usleep(100 * 1000);
302 timediff_us = g_get_monotonic_time() - ctx->fw_updated;
303 timediff_ms = timediff_us / 1000;
304 sr_spew("hantek-dso: waited %" PRIi64 " ms", timediff_ms);
306 sr_info("hantek-dso: device came back after %d ms", timediff_ms);
308 err = dso_open(dev_index);
312 sr_err("hantek-dso: unable to open device");
316 err = libusb_claim_interface(ctx->usb->devhdl, USB_INTERFACE);
318 sr_err("hantek-dso: Unable to claim interface: %d", err);
325 static int hw_dev_close(int dev_index)
327 struct sr_dev_inst *sdi;
329 if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
337 static int hw_cleanup(void)
340 struct sr_dev_inst *sdi;
343 /* Properly close and free all devices. */
344 for (l = dev_insts; l; l = l->next) {
345 if (!(sdi = l->data)) {
346 /* Log error, but continue cleaning up the rest. */
347 sr_err("hantek-dso: %s: sdi was NULL, continuing", __func__);
350 if (!(ctx = sdi->priv)) {
351 /* Log error, but continue cleaning up the rest. */
352 sr_err("hantek-dso: %s: sdi->priv was NULL, continuing", __func__);
356 sr_usb_dev_inst_free(ctx->usb);
357 g_free(ctx->triggersource);
359 sr_dev_inst_free(sdi);
362 g_slist_free(dev_insts);
366 libusb_exit(usb_context);
372 static const void *hw_dev_info_get(int dev_index, int dev_info_id)
374 struct sr_dev_inst *sdi;
378 if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
382 switch (dev_info_id) {
386 case SR_DI_NUM_PROBES:
387 info = GINT_TO_POINTER(NUM_PROBES);
389 case SR_DI_PROBE_NAMES:
392 case SR_DI_BUFFERSIZES:
395 case SR_DI_TIMEBASES:
398 case SR_DI_TRIGGER_SOURCES:
399 info = trigger_sources;
402 info = filter_targets;
410 /* TODO remove this */
411 case SR_DI_CUR_SAMPLERATE:
419 static int hw_dev_status_get(int dev_index)
421 struct sr_dev_inst *sdi;
423 if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
424 return SR_ST_NOT_FOUND;
429 static const int *hw_hwcap_get_all(void)
434 static int hw_dev_config_set(int dev_index, int hwcap, const void *value)
436 struct sr_dev_inst *sdi;
438 struct sr_rational tmp_rat;
444 if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
447 if (sdi->status != SR_ST_ACTIVE)
453 case SR_HWCAP_LIMIT_FRAMES:
454 ctx->limit_frames = *(const uint64_t *)value;
456 case SR_HWCAP_PROBECONFIG:
457 ret = configure_probes(ctx, (const GSList *)value);
459 case SR_HWCAP_TRIGGER_SLOPE:
460 tmp_u64 = *(const int *)value;
461 if (tmp_u64 != SLOPE_NEGATIVE && tmp_u64 != SLOPE_POSITIVE)
463 ctx->triggerslope = tmp_u64;
465 case SR_HWCAP_HORIZ_TRIGGERPOS:
466 tmp_float = *(const float *)value;
467 if (tmp_float < 0.0 || tmp_float > 1.0) {
468 sr_err("hantek-dso: trigger position should be between 0.0 and 1.0");
471 ctx->triggerposition = tmp_float;
473 case SR_HWCAP_BUFFERSIZE:
474 tmp_u64 = *(const int *)value;
475 for (i = 0; buffersizes[i]; i++) {
476 if (buffersizes[i] == tmp_u64) {
477 ctx->framesize = tmp_u64;
481 if (buffersizes[i] == 0)
484 case SR_HWCAP_TIMEBASE:
485 tmp_rat = *(const struct sr_rational *)value;
486 for (i = 0; timebases[i].p && timebases[i].q; i++) {
487 if (timebases[i].p == tmp_rat.p
488 && timebases[i].q == tmp_rat.q) {
493 if (timebases[i].p == 0 && timebases[i].q == 0)
496 case SR_HWCAP_TRIGGER_SOURCE:
497 for (i = 0; trigger_sources[i]; i++) {
498 if (!strcmp(value, trigger_sources[i])) {
499 ctx->triggersource = g_strdup(value);
503 if (trigger_sources[i] == 0)
506 case SR_HWCAP_FILTER:
507 ctx->filter_ch1 = ctx->filter_ch2 = ctx->filter_trigger = 0;
508 targets = g_strsplit(value, ",", 0);
509 for (i = 0; targets[i]; i++) {
510 if (targets[i] == '\0')
511 /* Empty filter string can be used to clear them all. */
513 else if (!strcmp(targets[i], "CH1"))
514 ctx->filter_ch1 = TRUE;
515 else if (!strcmp(targets[i], "CH2"))
516 ctx->filter_ch2 = TRUE;
517 else if (!strcmp(targets[i], "TRIGGER"))
518 ctx->filter_trigger = TRUE;
520 sr_err("invalid filter target %s", targets[i]);
527 /* TODO not supporting vdiv per channel yet */
528 tmp_rat = *(const struct sr_rational *)value;
529 for (i = 0; vdivs[i].p && vdivs[i].q; i++) {
530 if (vdivs[i].p == tmp_rat.p
531 && vdivs[i].q == tmp_rat.q) {
532 ctx->voltage_ch1 = i;
533 ctx->voltage_ch2 = i;
537 if (vdivs[i].p == 0 && vdivs[i].q == 0)
540 case SR_HWCAP_COUPLING:
541 /* TODO not supporting coupling per channel yet */
542 for (i = 0; coupling[i]; i++) {
543 if (!strcmp(value, coupling[i])) {
544 ctx->coupling_ch1 = i;
545 ctx->coupling_ch2 = i;
549 if (coupling[i] == 0)
559 static void send_chunk(struct context *ctx, unsigned char *buf,
562 struct sr_datafeed_packet packet;
563 struct sr_datafeed_analog analog;
564 float ch1, ch2, range;
565 int num_probes, data_offset, i;
567 num_probes = (ctx->ch1_enabled && ctx->ch2_enabled) ? 2 : 1;
568 packet.type = SR_DF_ANALOG;
569 packet.payload = &analog;
570 /* TODO: support for 5xxx series 9-bit samples */
571 analog.num_samples = num_samples;
572 analog.mq = SR_MQ_VOLTAGE;
573 analog.unit = SR_UNIT_VOLT;
574 analog.data = g_try_malloc(analog.num_samples * sizeof(float) * num_probes);
576 for (i = 0; i < analog.num_samples; i++) {
577 /* The device always sends data for both channels. If a channel
578 * is disabled, it contains a copy of the enabled channel's
579 * data. However, we only send the requested channels to the bus.
581 * Voltage values are encoded as a value 0-255 (0-512 on the 5200*),
582 * where the value is a point in the range represented by the vdiv
583 * setting. There are 8 vertical divs, so e.g. 500mV/div represents
584 * 4V peak-to-peak where 0 = -2V and 255 = +2V.
586 /* TODO: support for 5xxx series 9-bit samples */
587 if (ctx->ch1_enabled) {
588 range = ((float)vdivs[ctx->voltage_ch1].p / vdivs[ctx->voltage_ch1].q) * 8;
589 ch1 = range / 255 * *(buf + i * 2 + 1);
590 /* Value is centered around 0V. */
592 analog.data[data_offset++] = ch1;
594 if (ctx->ch2_enabled) {
595 range = ((float)vdivs[ctx->voltage_ch2].p / vdivs[ctx->voltage_ch2].q) * 8;
596 ch2 = range / 255 * *(buf + i * 2);
598 analog.data[data_offset++] = ch2;
601 sr_session_send(ctx->cb_data, &packet);
605 /* Called by libusb (as triggered by handle_event()) when a transfer comes in.
606 * Only channel data comes in asynchronously, and all transfers for this are
607 * queued up beforehand, so this just needs so chuck the incoming data onto
608 * the libsigrok session bus.
610 static void receive_transfer(struct libusb_transfer *transfer)
612 struct sr_datafeed_packet packet;
614 int num_samples, pre;
616 ctx = transfer->user_data;
617 sr_dbg("hantek-dso: receive_transfer(): status %d received %d bytes",
618 transfer->status, transfer->actual_length);
620 if (transfer->actual_length == 0)
621 /* Nothing to send to the bus. */
624 num_samples = transfer->actual_length / 2;
626 sr_dbg("hantek-dso: got %d-%d/%d samples in frame", ctx->samp_received + 1,
627 ctx->samp_received + num_samples, ctx->framesize);
629 /* The device always sends a full frame, but the beginning of the frame
630 * doesn't represent the trigger point. The offset at which the trigger
631 * happened came in with the capture state, so we need to start sending
632 * from there up the session bus. The samples in the frame buffer before
633 * that trigger point came after the end of the device's frame buffer was
634 * reached, and it wrapped around to overwrite up until the trigger point.
636 if (ctx->samp_received < ctx->trigger_offset) {
637 /* Trigger point not yet reached. */
638 if (ctx->samp_received + num_samples < ctx->trigger_offset) {
639 /* The entire chunk is before the trigger point. */
640 memcpy(ctx->framebuf + ctx->samp_buffered * 2,
641 transfer->buffer, num_samples * 2);
642 ctx->samp_buffered += num_samples;
644 /* This chunk hits or overruns the trigger point.
645 * Store the part before the trigger fired, and
646 * send the rest up to the session bus. */
647 pre = ctx->trigger_offset - ctx->samp_received;
648 memcpy(ctx->framebuf + ctx->samp_buffered * 2,
649 transfer->buffer, pre * 2);
650 ctx->samp_buffered += pre;
652 /* The rest of this chunk starts with the trigger point. */
653 sr_dbg("hantek-dso: reached trigger point, %d samples buffered",
656 /* Avoid the corner case where the chunk ended at
657 * exactly the trigger point. */
658 if (num_samples > pre)
659 send_chunk(ctx, transfer->buffer + pre * 2,
663 /* Already past the trigger point, just send it all out. */
664 send_chunk(ctx, transfer->buffer,
668 ctx->samp_received += num_samples;
670 /* Everything in this transfer was either copied to the buffer or
671 * sent to the session bus. */
672 g_free(transfer->buffer);
673 libusb_free_transfer(transfer);
675 if (ctx->samp_received >= ctx->framesize) {
676 /* That was the last chunk in this frame. Send the buffered
677 * pre-trigger samples out now, in one big chunk. */
678 sr_dbg("hantek-dso: end of frame, sending %d pre-trigger buffered samples",
680 send_chunk(ctx, ctx->framebuf, ctx->samp_buffered);
682 /* Mark the end of this frame. */
683 packet.type = SR_DF_FRAME_END;
684 sr_session_send(ctx->cb_data, &packet);
686 if (ctx->limit_frames && ++ctx->num_frames == ctx->limit_frames) {
687 /* Terminate session */
688 /* TODO: don't leave pending USB transfers hanging */
689 packet.type = SR_DF_END;
690 sr_session_send(ctx->cb_data, &packet);
692 ctx->dev_state = NEW_CAPTURE;
698 static int handle_event(int fd, int revents, void *cb_data)
700 struct sr_datafeed_packet packet;
704 uint32_t trigger_offset;
705 uint8_t capturestate;
707 /* Avoid compiler warnings. */
711 /* Always handle pending libusb events. */
712 tv.tv_sec = tv.tv_usec = 0;
713 libusb_handle_events_timeout(usb_context, &tv);
717 if (ctx->dev_state == NEW_CAPTURE) {
718 if (dso_capture_start(ctx) != SR_OK)
720 if (dso_enable_trigger(ctx) != SR_OK)
722 // if (dso_force_trigger(ctx) != SR_OK)
724 sr_dbg("hantek-dso: successfully requested next chunk");
725 ctx->dev_state = CAPTURE;
728 if (ctx->dev_state != CAPTURE)
731 if ((dso_get_capturestate(ctx, &capturestate, &trigger_offset)) != SR_OK)
734 sr_dbg("hantek-dso: capturestate %d", capturestate);
735 sr_dbg("hantek-dso: trigger offset 0x%.6x", trigger_offset);
736 switch (capturestate) {
738 if (++ctx->capture_empty_count >= MAX_CAPTURE_EMPTY) {
739 ctx->capture_empty_count = 0;
740 if (dso_capture_start(ctx) != SR_OK)
742 if (dso_enable_trigger(ctx) != SR_OK)
744 // if (dso_force_trigger(ctx) != SR_OK)
746 sr_dbg("hantek-dso: successfully requested next chunk");
749 case CAPTURE_FILLING:
752 case CAPTURE_READY_8BIT:
753 /* Remember where in the captured frame the trigger is. */
754 ctx->trigger_offset = trigger_offset;
756 num_probes = (ctx->ch1_enabled && ctx->ch2_enabled) ? 2 : 1;
757 ctx->framebuf = g_try_malloc(ctx->framesize * num_probes * 2);
758 ctx->samp_buffered = ctx->samp_received = 0;
760 /* Tell the scope to send us the first frame. */
761 if (dso_get_channeldata(ctx, receive_transfer) != SR_OK)
764 /* Don't hit the state machine again until we're done fetching
765 * the data we just told the scope to send.
767 ctx->dev_state = FETCH_DATA;
769 /* Tell the frontend a new frame is on the way. */
770 packet.type = SR_DF_FRAME_BEGIN;
771 sr_session_send(cb_data, &packet);
773 case CAPTURE_READY_9BIT:
775 sr_err("not yet supported");
777 case CAPTURE_TIMEOUT:
778 /* Doesn't matter, we'll try again next time. */
781 sr_dbg("unknown capture state");
787 static int hw_dev_acquisition_start(int dev_index, void *cb_data)
789 const struct libusb_pollfd **lupfd;
790 struct sr_datafeed_packet packet;
791 struct sr_datafeed_header header;
792 struct sr_datafeed_meta_analog meta;
793 struct sr_dev_inst *sdi;
797 if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
800 if (sdi->status != SR_ST_ACTIVE)
804 ctx->cb_data = cb_data;
806 if (dso_init(ctx) != SR_OK)
809 if (dso_capture_start(ctx) != SR_OK)
812 ctx->dev_state = CAPTURE;
813 lupfd = libusb_get_pollfds(usb_context);
814 for (i = 0; lupfd[i]; i++)
815 sr_source_add(lupfd[i]->fd, lupfd[i]->events, TICK, handle_event,
819 /* Send header packet to the session bus. */
820 packet.type = SR_DF_HEADER;
821 packet.payload = (unsigned char *)&header;
822 header.feed_version = 1;
823 gettimeofday(&header.starttime, NULL);
824 sr_session_send(cb_data, &packet);
826 /* Send metadata about the SR_DF_ANALOG packets to come. */
827 packet.type = SR_DF_META_ANALOG;
828 packet.payload = &meta;
829 meta.num_probes = NUM_PROBES;
830 sr_session_send(cb_data, &packet);
835 /* TODO: doesn't really cancel pending transfers so they might come in after
838 static int hw_dev_acquisition_stop(int dev_index, void *cb_data)
840 struct sr_datafeed_packet packet;
841 struct sr_dev_inst *sdi;
844 if (!(sdi = sr_dev_inst_get(dev_insts, dev_index)))
847 if (sdi->status != SR_ST_ACTIVE)
851 ctx->dev_state = IDLE;
853 packet.type = SR_DF_END;
854 sr_session_send(cb_data, &packet);
859 SR_PRIV struct sr_dev_driver hantek_dso_driver_info = {
860 .name = "hantek-dso",
861 .longname = "Hantek DSO",
864 .cleanup = hw_cleanup,
866 .dev_open = hw_dev_open,
867 .dev_close = hw_dev_close,
868 .dev_info_get = hw_dev_info_get,
869 .dev_status_get = hw_dev_status_get,
870 .hwcap_get_all = hw_hwcap_get_all,
871 .dev_config_set = hw_dev_config_set,
872 .dev_acquisition_start = hw_dev_acquisition_start,
873 .dev_acquisition_stop = hw_dev_acquisition_stop,