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);
162 if (!(ctx = g_try_malloc0(sizeof(struct context)))) {
163 sr_err("hantek-dso: ctx malloc failed");
167 ctx->dev_state = IDLE;
168 ctx->timebase = DEFAULT_TIMEBASE;
169 ctx->ch1_enabled = TRUE;
170 ctx->ch2_enabled = TRUE;
171 ctx->voltage_ch1 = DEFAULT_VOLTAGE;
172 ctx->voltage_ch2 = DEFAULT_VOLTAGE;
173 ctx->coupling_ch1 = DEFAULT_COUPLING;
174 ctx->coupling_ch2 = DEFAULT_COUPLING;
175 ctx->voffset_ch1 = DEFAULT_VERT_OFFSET;
176 ctx->voffset_ch2 = DEFAULT_VERT_OFFSET;
177 ctx->voffset_trigger = DEFAULT_VERT_TRIGGERPOS;
178 ctx->framesize = DEFAULT_FRAMESIZE;
179 ctx->triggerslope = SLOPE_POSITIVE;
180 ctx->triggersource = g_strdup(DEFAULT_TRIGGER_SOURCE);
181 ctx->triggerposition = DEFAULT_HORIZ_TRIGGERPOS;
183 hdi->instances = g_slist_append(hdi->instances, sdi);
188 static int configure_probes(struct context *ctx, const GSList *probes)
190 const struct sr_probe *probe;
193 ctx->ch1_enabled = ctx->ch2_enabled = FALSE;
194 for (l = probes; l; l = l->next) {
195 probe = (struct sr_probe *)l->data;
196 if (probe->index == 1)
197 ctx->ch1_enabled = probe->enabled;
198 else if (probe->index == 2)
199 ctx->ch2_enabled = probe->enabled;
205 /* Properly close and free all devices. */
206 static void clear_instances(void)
208 struct sr_dev_inst *sdi;
212 for (l = hdi->instances; l; l = l->next) {
213 if (!(sdi = l->data)) {
214 /* Log error, but continue cleaning up the rest. */
215 sr_err("hantek-dso: %s: sdi was NULL, continuing", __func__);
218 if (!(ctx = sdi->priv)) {
219 /* Log error, but continue cleaning up the rest. */
220 sr_err("hantek-dso: %s: sdi->priv was NULL, continuing", __func__);
224 sr_usb_dev_inst_free(ctx->usb);
225 g_free(ctx->triggersource);
227 sr_dev_inst_free(sdi);
230 g_slist_free(hdi->instances);
231 hdi->instances = NULL;
235 static int hw_init(void)
238 if (libusb_init(&usb_context) != 0) {
239 sr_err("hantek-dso: Failed to initialize USB.");
246 static GSList *hw_scan(GSList *options)
248 struct sr_dev_inst *sdi;
249 const struct dso_profile *prof;
252 struct libusb_device_descriptor des;
253 libusb_device **devlist;
254 int devcnt, ret, i, j;
259 hdi->instances = NULL;
263 /* Find all Hantek DSO devices and upload firmware to all of them. */
264 libusb_get_device_list(usb_context, &devlist);
265 for (i = 0; devlist[i]; i++) {
266 if ((ret = libusb_get_device_descriptor(devlist[i], &des))) {
267 sr_err("hantek-dso: failed to get device descriptor: %d", ret);
272 for (j = 0; dev_profiles[j].orig_vid; j++) {
273 if (des.idVendor == dev_profiles[j].orig_vid
274 && des.idProduct == dev_profiles[j].orig_pid) {
275 /* Device matches the pre-firmware profile. */
276 prof = &dev_profiles[j];
277 sr_dbg("hantek-dso: Found a %s %s.", prof->vendor, prof->model);
278 sdi = dso_dev_new(devcnt, prof);
279 devices = g_slist_append(devices, sdi);
281 if (ezusb_upload_firmware(devlist[i], USB_CONFIGURATION,
282 prof->firmware) == SR_OK)
283 /* Remember when the firmware on this device was updated */
284 ctx->fw_updated = g_get_monotonic_time();
286 sr_err("hantek-dso: firmware upload failed for "
287 "device %d", devcnt);
288 /* Dummy USB address of 0xff will get overwritten later. */
289 ctx->usb = sr_usb_dev_inst_new(
290 libusb_get_bus_number(devlist[i]), 0xff, NULL);
293 } else if (des.idVendor == dev_profiles[j].fw_vid
294 && des.idProduct == dev_profiles[j].fw_pid) {
295 /* Device matches the post-firmware profile. */
296 prof = &dev_profiles[j];
297 sr_dbg("hantek-dso: Found a %s %s.", prof->vendor, prof->model);
298 sdi = dso_dev_new(devcnt, prof);
299 sdi->status = SR_ST_INACTIVE;
300 devices = g_slist_append(devices, sdi);
302 ctx->usb = sr_usb_dev_inst_new(
303 libusb_get_bus_number(devlist[i]),
304 libusb_get_device_address(devlist[i]), NULL);
310 /* not a supported VID/PID */
313 libusb_free_device_list(devlist, 1);
318 static int hw_dev_open(struct sr_dev_inst *sdi)
321 int64_t timediff_us, timediff_ms;
327 * if the firmware was recently uploaded, wait up to MAX_RENUM_DELAY_MS
328 * for the FX2 to renumerate
331 if (ctx->fw_updated > 0) {
332 sr_info("hantek-dso: waiting for device to reset");
333 /* takes at least 300ms for the FX2 to be gone from the USB bus */
334 g_usleep(300 * 1000);
336 while (timediff_ms < MAX_RENUM_DELAY_MS) {
337 if ((err = dso_open(sdi)) == SR_OK)
339 g_usleep(100 * 1000);
340 timediff_us = g_get_monotonic_time() - ctx->fw_updated;
341 timediff_ms = timediff_us / 1000;
342 sr_spew("hantek-dso: waited %" PRIi64 " ms", timediff_ms);
344 sr_info("hantek-dso: device came back after %d ms", timediff_ms);
350 sr_err("hantek-dso: unable to open device");
354 err = libusb_claim_interface(ctx->usb->devhdl, USB_INTERFACE);
356 sr_err("hantek-dso: Unable to claim interface: %d", err);
363 static int hw_dev_close(struct sr_dev_inst *sdi)
371 static int hw_cleanup(void)
377 libusb_exit(usb_context);
383 static int hw_info_get(int info_id, const void **data,
384 const struct sr_dev_inst *sdi)
395 case SR_DI_NUM_PROBES:
396 *data = GINT_TO_POINTER(NUM_PROBES);
398 case SR_DI_PROBE_NAMES:
401 case SR_DI_BUFFERSIZES:
404 case SR_DI_TIMEBASES:
407 case SR_DI_TRIGGER_SOURCES:
408 *data = trigger_sources;
411 *data = filter_targets;
419 /* TODO remove this */
420 case SR_DI_CUR_SAMPLERATE:
430 static int hw_dev_status_get(int dev_index)
432 struct sr_dev_inst *sdi;
434 if (!(sdi = sr_dev_inst_get(hdi->instances, dev_index)))
435 return SR_ST_NOT_FOUND;
440 static int hw_dev_config_set(const struct sr_dev_inst *sdi, int hwcap,
444 struct sr_rational tmp_rat;
450 if (sdi->status != SR_ST_ACTIVE)
456 case SR_HWCAP_LIMIT_FRAMES:
457 ctx->limit_frames = *(const uint64_t *)value;
459 case SR_HWCAP_PROBECONFIG:
460 ret = configure_probes(ctx, (const GSList *)value);
462 case SR_HWCAP_TRIGGER_SLOPE:
463 tmp_u64 = *(const int *)value;
464 if (tmp_u64 != SLOPE_NEGATIVE && tmp_u64 != SLOPE_POSITIVE)
466 ctx->triggerslope = tmp_u64;
468 case SR_HWCAP_HORIZ_TRIGGERPOS:
469 tmp_float = *(const float *)value;
470 if (tmp_float < 0.0 || tmp_float > 1.0) {
471 sr_err("hantek-dso: trigger position should be between 0.0 and 1.0");
474 ctx->triggerposition = tmp_float;
476 case SR_HWCAP_BUFFERSIZE:
477 tmp_u64 = *(const int *)value;
478 for (i = 0; buffersizes[i]; i++) {
479 if (buffersizes[i] == tmp_u64) {
480 ctx->framesize = tmp_u64;
484 if (buffersizes[i] == 0)
487 case SR_HWCAP_TIMEBASE:
488 tmp_rat = *(const struct sr_rational *)value;
489 for (i = 0; timebases[i].p && timebases[i].q; i++) {
490 if (timebases[i].p == tmp_rat.p
491 && timebases[i].q == tmp_rat.q) {
496 if (timebases[i].p == 0 && timebases[i].q == 0)
499 case SR_HWCAP_TRIGGER_SOURCE:
500 for (i = 0; trigger_sources[i]; i++) {
501 if (!strcmp(value, trigger_sources[i])) {
502 ctx->triggersource = g_strdup(value);
506 if (trigger_sources[i] == 0)
509 case SR_HWCAP_FILTER:
510 ctx->filter_ch1 = ctx->filter_ch2 = ctx->filter_trigger = 0;
511 targets = g_strsplit(value, ",", 0);
512 for (i = 0; targets[i]; i++) {
513 if (targets[i] == '\0')
514 /* Empty filter string can be used to clear them all. */
516 else if (!strcmp(targets[i], "CH1"))
517 ctx->filter_ch1 = TRUE;
518 else if (!strcmp(targets[i], "CH2"))
519 ctx->filter_ch2 = TRUE;
520 else if (!strcmp(targets[i], "TRIGGER"))
521 ctx->filter_trigger = TRUE;
523 sr_err("invalid filter target %s", targets[i]);
530 /* TODO not supporting vdiv per channel yet */
531 tmp_rat = *(const struct sr_rational *)value;
532 for (i = 0; vdivs[i].p && vdivs[i].q; i++) {
533 if (vdivs[i].p == tmp_rat.p
534 && vdivs[i].q == tmp_rat.q) {
535 ctx->voltage_ch1 = i;
536 ctx->voltage_ch2 = i;
540 if (vdivs[i].p == 0 && vdivs[i].q == 0)
543 case SR_HWCAP_COUPLING:
544 /* TODO not supporting coupling per channel yet */
545 for (i = 0; coupling[i]; i++) {
546 if (!strcmp(value, coupling[i])) {
547 ctx->coupling_ch1 = i;
548 ctx->coupling_ch2 = i;
552 if (coupling[i] == 0)
562 static void send_chunk(struct context *ctx, unsigned char *buf,
565 struct sr_datafeed_packet packet;
566 struct sr_datafeed_analog analog;
567 float ch1, ch2, range;
568 int num_probes, data_offset, i;
570 num_probes = (ctx->ch1_enabled && ctx->ch2_enabled) ? 2 : 1;
571 packet.type = SR_DF_ANALOG;
572 packet.payload = &analog;
573 /* TODO: support for 5xxx series 9-bit samples */
574 analog.num_samples = num_samples;
575 analog.mq = SR_MQ_VOLTAGE;
576 analog.unit = SR_UNIT_VOLT;
577 analog.data = g_try_malloc(analog.num_samples * sizeof(float) * num_probes);
579 for (i = 0; i < analog.num_samples; i++) {
580 /* The device always sends data for both channels. If a channel
581 * is disabled, it contains a copy of the enabled channel's
582 * data. However, we only send the requested channels to the bus.
584 * Voltage values are encoded as a value 0-255 (0-512 on the 5200*),
585 * where the value is a point in the range represented by the vdiv
586 * setting. There are 8 vertical divs, so e.g. 500mV/div represents
587 * 4V peak-to-peak where 0 = -2V and 255 = +2V.
589 /* TODO: support for 5xxx series 9-bit samples */
590 if (ctx->ch1_enabled) {
591 range = ((float)vdivs[ctx->voltage_ch1].p / vdivs[ctx->voltage_ch1].q) * 8;
592 ch1 = range / 255 * *(buf + i * 2 + 1);
593 /* Value is centered around 0V. */
595 analog.data[data_offset++] = ch1;
597 if (ctx->ch2_enabled) {
598 range = ((float)vdivs[ctx->voltage_ch2].p / vdivs[ctx->voltage_ch2].q) * 8;
599 ch2 = range / 255 * *(buf + i * 2);
601 analog.data[data_offset++] = ch2;
604 sr_session_send(ctx->cb_data, &packet);
608 /* Called by libusb (as triggered by handle_event()) when a transfer comes in.
609 * Only channel data comes in asynchronously, and all transfers for this are
610 * queued up beforehand, so this just needs so chuck the incoming data onto
611 * the libsigrok session bus.
613 static void receive_transfer(struct libusb_transfer *transfer)
615 struct sr_datafeed_packet packet;
617 int num_samples, pre;
619 ctx = transfer->user_data;
620 sr_dbg("hantek-dso: receive_transfer(): status %d received %d bytes",
621 transfer->status, transfer->actual_length);
623 if (transfer->actual_length == 0)
624 /* Nothing to send to the bus. */
627 num_samples = transfer->actual_length / 2;
629 sr_dbg("hantek-dso: got %d-%d/%d samples in frame", ctx->samp_received + 1,
630 ctx->samp_received + num_samples, ctx->framesize);
632 /* The device always sends a full frame, but the beginning of the frame
633 * doesn't represent the trigger point. The offset at which the trigger
634 * happened came in with the capture state, so we need to start sending
635 * from there up the session bus. The samples in the frame buffer before
636 * that trigger point came after the end of the device's frame buffer was
637 * reached, and it wrapped around to overwrite up until the trigger point.
639 if (ctx->samp_received < ctx->trigger_offset) {
640 /* Trigger point not yet reached. */
641 if (ctx->samp_received + num_samples < ctx->trigger_offset) {
642 /* The entire chunk is before the trigger point. */
643 memcpy(ctx->framebuf + ctx->samp_buffered * 2,
644 transfer->buffer, num_samples * 2);
645 ctx->samp_buffered += num_samples;
647 /* This chunk hits or overruns the trigger point.
648 * Store the part before the trigger fired, and
649 * send the rest up to the session bus. */
650 pre = ctx->trigger_offset - ctx->samp_received;
651 memcpy(ctx->framebuf + ctx->samp_buffered * 2,
652 transfer->buffer, pre * 2);
653 ctx->samp_buffered += pre;
655 /* The rest of this chunk starts with the trigger point. */
656 sr_dbg("hantek-dso: reached trigger point, %d samples buffered",
659 /* Avoid the corner case where the chunk ended at
660 * exactly the trigger point. */
661 if (num_samples > pre)
662 send_chunk(ctx, transfer->buffer + pre * 2,
666 /* Already past the trigger point, just send it all out. */
667 send_chunk(ctx, transfer->buffer,
671 ctx->samp_received += num_samples;
673 /* Everything in this transfer was either copied to the buffer or
674 * sent to the session bus. */
675 g_free(transfer->buffer);
676 libusb_free_transfer(transfer);
678 if (ctx->samp_received >= ctx->framesize) {
679 /* That was the last chunk in this frame. Send the buffered
680 * pre-trigger samples out now, in one big chunk. */
681 sr_dbg("hantek-dso: end of frame, sending %d pre-trigger buffered samples",
683 send_chunk(ctx, ctx->framebuf, ctx->samp_buffered);
685 /* Mark the end of this frame. */
686 packet.type = SR_DF_FRAME_END;
687 sr_session_send(ctx->cb_data, &packet);
689 if (ctx->limit_frames && ++ctx->num_frames == ctx->limit_frames) {
690 /* Terminate session */
691 /* TODO: don't leave pending USB transfers hanging */
692 packet.type = SR_DF_END;
693 sr_session_send(ctx->cb_data, &packet);
695 ctx->dev_state = NEW_CAPTURE;
701 static int handle_event(int fd, int revents, void *cb_data)
703 struct sr_datafeed_packet packet;
707 uint32_t trigger_offset;
708 uint8_t capturestate;
710 /* Avoid compiler warnings. */
714 /* Always handle pending libusb events. */
715 tv.tv_sec = tv.tv_usec = 0;
716 libusb_handle_events_timeout(usb_context, &tv);
720 if (ctx->dev_state == NEW_CAPTURE) {
721 if (dso_capture_start(ctx) != SR_OK)
723 if (dso_enable_trigger(ctx) != SR_OK)
725 // if (dso_force_trigger(ctx) != SR_OK)
727 sr_dbg("hantek-dso: successfully requested next chunk");
728 ctx->dev_state = CAPTURE;
731 if (ctx->dev_state != CAPTURE)
734 if ((dso_get_capturestate(ctx, &capturestate, &trigger_offset)) != SR_OK)
737 sr_dbg("hantek-dso: capturestate %d", capturestate);
738 sr_dbg("hantek-dso: trigger offset 0x%.6x", trigger_offset);
739 switch (capturestate) {
741 if (++ctx->capture_empty_count >= MAX_CAPTURE_EMPTY) {
742 ctx->capture_empty_count = 0;
743 if (dso_capture_start(ctx) != SR_OK)
745 if (dso_enable_trigger(ctx) != SR_OK)
747 // if (dso_force_trigger(ctx) != SR_OK)
749 sr_dbg("hantek-dso: successfully requested next chunk");
752 case CAPTURE_FILLING:
755 case CAPTURE_READY_8BIT:
756 /* Remember where in the captured frame the trigger is. */
757 ctx->trigger_offset = trigger_offset;
759 num_probes = (ctx->ch1_enabled && ctx->ch2_enabled) ? 2 : 1;
760 ctx->framebuf = g_try_malloc(ctx->framesize * num_probes * 2);
761 ctx->samp_buffered = ctx->samp_received = 0;
763 /* Tell the scope to send us the first frame. */
764 if (dso_get_channeldata(ctx, receive_transfer) != SR_OK)
767 /* Don't hit the state machine again until we're done fetching
768 * the data we just told the scope to send.
770 ctx->dev_state = FETCH_DATA;
772 /* Tell the frontend a new frame is on the way. */
773 packet.type = SR_DF_FRAME_BEGIN;
774 sr_session_send(cb_data, &packet);
776 case CAPTURE_READY_9BIT:
778 sr_err("not yet supported");
780 case CAPTURE_TIMEOUT:
781 /* Doesn't matter, we'll try again next time. */
784 sr_dbg("unknown capture state");
790 static int hw_dev_acquisition_start(int dev_index, void *cb_data)
792 const struct libusb_pollfd **lupfd;
793 struct sr_datafeed_packet packet;
794 struct sr_datafeed_header header;
795 struct sr_datafeed_meta_analog meta;
796 struct sr_dev_inst *sdi;
800 if (!(sdi = sr_dev_inst_get(hdi->instances, dev_index)))
803 if (sdi->status != SR_ST_ACTIVE)
807 ctx->cb_data = cb_data;
809 if (dso_init(ctx) != SR_OK)
812 if (dso_capture_start(ctx) != SR_OK)
815 ctx->dev_state = CAPTURE;
816 lupfd = libusb_get_pollfds(usb_context);
817 for (i = 0; lupfd[i]; i++)
818 sr_source_add(lupfd[i]->fd, lupfd[i]->events, TICK, handle_event,
822 /* Send header packet to the session bus. */
823 packet.type = SR_DF_HEADER;
824 packet.payload = (unsigned char *)&header;
825 header.feed_version = 1;
826 gettimeofday(&header.starttime, NULL);
827 sr_session_send(cb_data, &packet);
829 /* Send metadata about the SR_DF_ANALOG packets to come. */
830 packet.type = SR_DF_META_ANALOG;
831 packet.payload = &meta;
832 meta.num_probes = NUM_PROBES;
833 sr_session_send(cb_data, &packet);
838 /* TODO: doesn't really cancel pending transfers so they might come in after
841 static int hw_dev_acquisition_stop(int dev_index, void *cb_data)
843 struct sr_datafeed_packet packet;
844 struct sr_dev_inst *sdi;
847 if (!(sdi = sr_dev_inst_get(hdi->instances, dev_index)))
850 if (sdi->status != SR_ST_ACTIVE)
854 ctx->dev_state = IDLE;
856 packet.type = SR_DF_END;
857 sr_session_send(cb_data, &packet);
862 SR_PRIV struct sr_dev_driver hantek_dso_driver_info = {
863 .name = "hantek-dso",
864 .longname = "Hantek DSO",
867 .cleanup = hw_cleanup,
869 .dev_open = hw_dev_open,
870 .dev_close = hw_dev_close,
871 .info_get = hw_info_get,
872 .dev_status_get = hw_dev_status_get,
873 .dev_config_set = hw_dev_config_set,
874 .dev_acquisition_start = hw_dev_acquisition_start,
875 .dev_acquisition_stop = hw_dev_acquisition_stop,