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 struct sr_dev_driver hantek_dso_driver_info;
149 static struct sr_dev_driver *hdi = &hantek_dso_driver_info;
151 static struct sr_dev_inst *dso_dev_new(int index, const struct dso_profile *prof)
153 struct sr_dev_inst *sdi;
156 sdi = sr_dev_inst_new(index, SR_ST_INITIALIZING,
157 prof->vendor, prof->model, NULL);
161 if (!(ctx = g_try_malloc0(sizeof(struct context)))) {
162 sr_err("hantek-dso: ctx malloc failed");
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;
182 hdi->instances = g_slist_append(hdi->instances, sdi);
187 static int configure_probes(struct context *ctx, const GSList *probes)
189 const struct sr_probe *probe;
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;
204 static int hw_init(void)
207 if (libusb_init(&usb_context) != 0) {
208 sr_err("hantek-dso: Failed to initialize USB.");
215 static int hw_scan(void)
217 struct sr_dev_inst *sdi;
218 struct libusb_device_descriptor des;
219 const struct dso_profile *prof;
221 libusb_device **devlist;
222 int devcnt, ret, i, j;
224 /* Find all Hantek DSO devices and upload firmware to all of them. */
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);
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);
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();
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);
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;
262 ctx->usb = sr_usb_dev_inst_new(
263 libusb_get_bus_number(devlist[i]),
264 libusb_get_device_address(devlist[i]), NULL);
270 /* not a supported VID/PID */
273 libusb_free_device_list(devlist, 1);
278 static int hw_dev_open(int dev_index)
280 struct sr_dev_inst *sdi;
282 int64_t timediff_us, timediff_ms;
285 if (!(sdi = sr_dev_inst_get(hdi->instances, dev_index)))
290 * if the firmware was recently uploaded, wait up to MAX_RENUM_DELAY_MS
291 * for the FX2 to renumerate
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);
299 while (timediff_ms < MAX_RENUM_DELAY_MS) {
300 if ((err = dso_open(dev_index)) == SR_OK)
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);
307 sr_info("hantek-dso: device came back after %d ms", timediff_ms);
309 err = dso_open(dev_index);
313 sr_err("hantek-dso: unable to open device");
317 err = libusb_claim_interface(ctx->usb->devhdl, USB_INTERFACE);
319 sr_err("hantek-dso: Unable to claim interface: %d", err);
326 static int hw_dev_close(int dev_index)
328 struct sr_dev_inst *sdi;
330 if (!(sdi = sr_dev_inst_get(hdi->instances, dev_index)))
338 static int hw_cleanup(void)
341 struct sr_dev_inst *sdi;
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__);
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__);
357 sr_usb_dev_inst_free(ctx->usb);
358 g_free(ctx->triggersource);
360 sr_dev_inst_free(sdi);
363 g_slist_free(hdi->instances);
364 hdi->instances = NULL;
367 libusb_exit(usb_context);
373 static const void *hw_dev_info_get(int dev_index, int dev_info_id)
375 struct sr_dev_inst *sdi;
379 if (!(sdi = sr_dev_inst_get(hdi->instances, dev_index)))
383 switch (dev_info_id) {
387 case SR_DI_NUM_PROBES:
388 info = GINT_TO_POINTER(NUM_PROBES);
390 case SR_DI_PROBE_NAMES:
393 case SR_DI_BUFFERSIZES:
396 case SR_DI_TIMEBASES:
399 case SR_DI_TRIGGER_SOURCES:
400 info = trigger_sources;
403 info = filter_targets;
411 /* TODO remove this */
412 case SR_DI_CUR_SAMPLERATE:
420 static int hw_dev_status_get(int dev_index)
422 struct sr_dev_inst *sdi;
424 if (!(sdi = sr_dev_inst_get(hdi->instances, dev_index)))
425 return SR_ST_NOT_FOUND;
430 static const int *hw_hwcap_get_all(void)
435 static int hw_dev_config_set(int dev_index, int hwcap, const void *value)
437 struct sr_dev_inst *sdi;
439 struct sr_rational tmp_rat;
445 if (!(sdi = sr_dev_inst_get(hdi->instances, dev_index)))
448 if (sdi->status != SR_ST_ACTIVE)
454 case SR_HWCAP_LIMIT_FRAMES:
455 ctx->limit_frames = *(const uint64_t *)value;
457 case SR_HWCAP_PROBECONFIG:
458 ret = configure_probes(ctx, (const GSList *)value);
460 case SR_HWCAP_TRIGGER_SLOPE:
461 tmp_u64 = *(const int *)value;
462 if (tmp_u64 != SLOPE_NEGATIVE && tmp_u64 != SLOPE_POSITIVE)
464 ctx->triggerslope = tmp_u64;
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");
472 ctx->triggerposition = tmp_float;
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;
482 if (buffersizes[i] == 0)
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) {
494 if (timebases[i].p == 0 && timebases[i].q == 0)
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);
504 if (trigger_sources[i] == 0)
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. */
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;
521 sr_err("invalid filter target %s", targets[i]);
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;
538 if (vdivs[i].p == 0 && vdivs[i].q == 0)
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;
550 if (coupling[i] == 0)
560 static void send_chunk(struct context *ctx, unsigned char *buf,
563 struct sr_datafeed_packet packet;
564 struct sr_datafeed_analog analog;
565 float ch1, ch2, range;
566 int num_probes, data_offset, i;
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);
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.
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.
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. */
593 analog.data[data_offset++] = ch1;
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);
599 analog.data[data_offset++] = ch2;
602 sr_session_send(ctx->cb_data, &packet);
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.
611 static void receive_transfer(struct libusb_transfer *transfer)
613 struct sr_datafeed_packet packet;
615 int num_samples, pre;
617 ctx = transfer->user_data;
618 sr_dbg("hantek-dso: receive_transfer(): status %d received %d bytes",
619 transfer->status, transfer->actual_length);
621 if (transfer->actual_length == 0)
622 /* Nothing to send to the bus. */
625 num_samples = transfer->actual_length / 2;
627 sr_dbg("hantek-dso: got %d-%d/%d samples in frame", ctx->samp_received + 1,
628 ctx->samp_received + num_samples, ctx->framesize);
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.
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;
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;
653 /* The rest of this chunk starts with the trigger point. */
654 sr_dbg("hantek-dso: reached trigger point, %d samples buffered",
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,
664 /* Already past the trigger point, just send it all out. */
665 send_chunk(ctx, transfer->buffer,
669 ctx->samp_received += num_samples;
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);
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",
681 send_chunk(ctx, ctx->framebuf, ctx->samp_buffered);
683 /* Mark the end of this frame. */
684 packet.type = SR_DF_FRAME_END;
685 sr_session_send(ctx->cb_data, &packet);
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);
693 ctx->dev_state = NEW_CAPTURE;
699 static int handle_event(int fd, int revents, void *cb_data)
701 struct sr_datafeed_packet packet;
705 uint32_t trigger_offset;
706 uint8_t capturestate;
708 /* Avoid compiler warnings. */
712 /* Always handle pending libusb events. */
713 tv.tv_sec = tv.tv_usec = 0;
714 libusb_handle_events_timeout(usb_context, &tv);
718 if (ctx->dev_state == NEW_CAPTURE) {
719 if (dso_capture_start(ctx) != SR_OK)
721 if (dso_enable_trigger(ctx) != SR_OK)
723 // if (dso_force_trigger(ctx) != SR_OK)
725 sr_dbg("hantek-dso: successfully requested next chunk");
726 ctx->dev_state = CAPTURE;
729 if (ctx->dev_state != CAPTURE)
732 if ((dso_get_capturestate(ctx, &capturestate, &trigger_offset)) != SR_OK)
735 sr_dbg("hantek-dso: capturestate %d", capturestate);
736 sr_dbg("hantek-dso: trigger offset 0x%.6x", trigger_offset);
737 switch (capturestate) {
739 if (++ctx->capture_empty_count >= MAX_CAPTURE_EMPTY) {
740 ctx->capture_empty_count = 0;
741 if (dso_capture_start(ctx) != SR_OK)
743 if (dso_enable_trigger(ctx) != SR_OK)
745 // if (dso_force_trigger(ctx) != SR_OK)
747 sr_dbg("hantek-dso: successfully requested next chunk");
750 case CAPTURE_FILLING:
753 case CAPTURE_READY_8BIT:
754 /* Remember where in the captured frame the trigger is. */
755 ctx->trigger_offset = trigger_offset;
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;
761 /* Tell the scope to send us the first frame. */
762 if (dso_get_channeldata(ctx, receive_transfer) != SR_OK)
765 /* Don't hit the state machine again until we're done fetching
766 * the data we just told the scope to send.
768 ctx->dev_state = FETCH_DATA;
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);
774 case CAPTURE_READY_9BIT:
776 sr_err("not yet supported");
778 case CAPTURE_TIMEOUT:
779 /* Doesn't matter, we'll try again next time. */
782 sr_dbg("unknown capture state");
788 static int hw_dev_acquisition_start(int dev_index, void *cb_data)
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;
798 if (!(sdi = sr_dev_inst_get(hdi->instances, dev_index)))
801 if (sdi->status != SR_ST_ACTIVE)
805 ctx->cb_data = cb_data;
807 if (dso_init(ctx) != SR_OK)
810 if (dso_capture_start(ctx) != SR_OK)
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,
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);
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);
836 /* TODO: doesn't really cancel pending transfers so they might come in after
839 static int hw_dev_acquisition_stop(int dev_index, void *cb_data)
841 struct sr_datafeed_packet packet;
842 struct sr_dev_inst *sdi;
845 if (!(sdi = sr_dev_inst_get(hdi->instances, dev_index)))
848 if (sdi->status != SR_ST_ACTIVE)
852 ctx->dev_state = IDLE;
854 packet.type = SR_DF_END;
855 sr_session_send(cb_data, &packet);
860 SR_PRIV struct sr_dev_driver hantek_dso_driver_info = {
861 .name = "hantek-dso",
862 .longname = "Hantek DSO",
865 .cleanup = hw_cleanup,
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,