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"
36 /* Max time in ms before we want to check on USB events */
37 /* TODO tune this properly */
40 static const int32_t devopts[] = {
46 SR_CONF_TRIGGER_SOURCE,
47 SR_CONF_TRIGGER_SLOPE,
48 SR_CONF_HORIZ_TRIGGERPOS,
54 static const char *probe_names[] = {
59 static const struct dso_profile dev_profiles[] = {
60 { 0x04b4, 0x2090, 0x04b5, 0x2090,
62 FIRMWARE_DIR "/hantek-dso-2090.fw" },
63 { 0x04b4, 0x2150, 0x04b5, 0x2150,
65 FIRMWARE_DIR "/hantek-dso-2150.fw" },
66 { 0x04b4, 0x2250, 0x04b5, 0x2250,
68 FIRMWARE_DIR "/hantek-dso-2250.fw" },
69 { 0x04b4, 0x5200, 0x04b5, 0x5200,
71 FIRMWARE_DIR "/hantek-dso-5200.fw" },
72 { 0x04b4, 0x520a, 0x04b5, 0x520a,
73 "Hantek", "DSO-5200A",
74 FIRMWARE_DIR "/hantek-dso-5200A.fw" },
75 { 0, 0, 0, 0, 0, 0, 0 },
78 static const uint64_t buffersizes[] = {
84 static const uint64_t timebases[][2] = {
104 static const uint64_t vdivs[][2] = {
118 static const char *trigger_sources[] = {
125 static const char *filter_targets[] = {
128 /* TODO: "TRIGGER", */
131 static const char *coupling[] = {
137 SR_PRIV struct sr_dev_driver hantek_dso_driver_info;
138 static struct sr_dev_driver *di = &hantek_dso_driver_info;
140 static int hw_dev_acquisition_stop(struct sr_dev_inst *sdi, void *cb_data);
142 static struct sr_dev_inst *dso_dev_new(int index, const struct dso_profile *prof)
144 struct sr_dev_inst *sdi;
145 struct sr_probe *probe;
146 struct drv_context *drvc;
147 struct dev_context *devc;
150 sdi = sr_dev_inst_new(index, SR_ST_INITIALIZING,
151 prof->vendor, prof->model, NULL);
157 * Add only the real probes -- EXT isn't a source of data, only
158 * a trigger source internal to the device.
160 for (i = 0; probe_names[i]; i++) {
161 if (!(probe = sr_probe_new(i, SR_PROBE_ANALOG, TRUE,
164 sdi->probes = g_slist_append(sdi->probes, probe);
167 if (!(devc = g_try_malloc0(sizeof(struct dev_context)))) {
168 sr_err("Device context malloc failed.");
172 devc->profile = prof;
173 devc->dev_state = IDLE;
174 devc->timebase = DEFAULT_TIMEBASE;
175 devc->ch1_enabled = TRUE;
176 devc->ch2_enabled = TRUE;
177 devc->voltage_ch1 = DEFAULT_VOLTAGE;
178 devc->voltage_ch2 = DEFAULT_VOLTAGE;
179 devc->coupling_ch1 = DEFAULT_COUPLING;
180 devc->coupling_ch2 = DEFAULT_COUPLING;
181 devc->voffset_ch1 = DEFAULT_VERT_OFFSET;
182 devc->voffset_ch2 = DEFAULT_VERT_OFFSET;
183 devc->voffset_trigger = DEFAULT_VERT_TRIGGERPOS;
184 devc->framesize = DEFAULT_FRAMESIZE;
185 devc->triggerslope = SLOPE_POSITIVE;
186 devc->triggersource = g_strdup(DEFAULT_TRIGGER_SOURCE);
187 devc->triggerposition = DEFAULT_HORIZ_TRIGGERPOS;
190 drvc->instances = g_slist_append(drvc->instances, sdi);
195 static int configure_probes(const struct sr_dev_inst *sdi)
197 struct dev_context *devc;
198 struct sr_probe *probe;
204 g_slist_free(devc->enabled_probes);
205 devc->ch1_enabled = devc->ch2_enabled = FALSE;
206 for (l = sdi->probes, p = 0; l; l = l->next, p++) {
209 devc->ch1_enabled = probe->enabled;
211 devc->ch2_enabled = probe->enabled;
213 devc->enabled_probes = g_slist_append(devc->enabled_probes, probe);
219 /* Properly close and free all devices. */
220 static int clear_instances(void)
222 struct sr_dev_inst *sdi;
223 struct drv_context *drvc;
224 struct dev_context *devc;
228 for (l = drvc->instances; l; l = l->next) {
229 if (!(sdi = l->data)) {
230 /* Log error, but continue cleaning up the rest. */
231 sr_err("%s: sdi was NULL, continuing", __func__);
234 if (!(devc = sdi->priv)) {
235 /* Log error, but continue cleaning up the rest. */
236 sr_err("%s: sdi->priv was NULL, continuing", __func__);
240 sr_usb_dev_inst_free(devc->usb);
241 g_free(devc->triggersource);
242 g_slist_free(devc->enabled_probes);
244 sr_dev_inst_free(sdi);
247 g_slist_free(drvc->instances);
248 drvc->instances = NULL;
253 static int hw_init(struct sr_context *sr_ctx)
255 return std_hw_init(sr_ctx, di, DRIVER_LOG_DOMAIN);
258 static GSList *hw_scan(GSList *options)
260 struct sr_dev_inst *sdi;
261 const struct dso_profile *prof;
262 struct drv_context *drvc;
263 struct dev_context *devc;
265 struct libusb_device_descriptor des;
266 libusb_device **devlist;
267 int devcnt, ret, i, j;
272 drvc->instances = NULL;
279 /* Find all Hantek DSO devices and upload firmware to all of them. */
280 libusb_get_device_list(drvc->sr_ctx->libusb_ctx, &devlist);
281 for (i = 0; devlist[i]; i++) {
282 if ((ret = libusb_get_device_descriptor(devlist[i], &des))) {
283 sr_err("Failed to get device descriptor: %s.",
284 libusb_error_name(ret));
289 for (j = 0; dev_profiles[j].orig_vid; j++) {
290 if (des.idVendor == dev_profiles[j].orig_vid
291 && des.idProduct == dev_profiles[j].orig_pid) {
292 /* Device matches the pre-firmware profile. */
293 prof = &dev_profiles[j];
294 sr_dbg("Found a %s %s.", prof->vendor, prof->model);
295 sdi = dso_dev_new(devcnt, prof);
296 devices = g_slist_append(devices, sdi);
298 if (ezusb_upload_firmware(devlist[i], USB_CONFIGURATION,
299 prof->firmware) == SR_OK)
300 /* Remember when the firmware on this device was updated */
301 devc->fw_updated = g_get_monotonic_time();
303 sr_err("Firmware upload failed for "
304 "device %d.", devcnt);
305 /* Dummy USB address of 0xff will get overwritten later. */
306 devc->usb = sr_usb_dev_inst_new(
307 libusb_get_bus_number(devlist[i]), 0xff, NULL);
310 } else if (des.idVendor == dev_profiles[j].fw_vid
311 && des.idProduct == dev_profiles[j].fw_pid) {
312 /* Device matches the post-firmware profile. */
313 prof = &dev_profiles[j];
314 sr_dbg("Found a %s %s.", prof->vendor, prof->model);
315 sdi = dso_dev_new(devcnt, prof);
316 sdi->status = SR_ST_INACTIVE;
317 devices = g_slist_append(devices, sdi);
319 devc->usb = sr_usb_dev_inst_new(
320 libusb_get_bus_number(devlist[i]),
321 libusb_get_device_address(devlist[i]), NULL);
327 /* not a supported VID/PID */
330 libusb_free_device_list(devlist, 1);
335 static GSList *hw_dev_list(void)
337 return ((struct drv_context *)(di->priv))->instances;
340 static int hw_dev_open(struct sr_dev_inst *sdi)
342 struct dev_context *devc;
343 int64_t timediff_us, timediff_ms;
349 * If the firmware was recently uploaded, wait up to MAX_RENUM_DELAY_MS
350 * for the FX2 to renumerate.
353 if (devc->fw_updated > 0) {
354 sr_info("Waiting for device to reset.");
355 /* Takes >= 300ms for the FX2 to be gone from the USB bus. */
356 g_usleep(300 * 1000);
358 while (timediff_ms < MAX_RENUM_DELAY_MS) {
359 if ((err = dso_open(sdi)) == SR_OK)
361 g_usleep(100 * 1000);
362 timediff_us = g_get_monotonic_time() - devc->fw_updated;
363 timediff_ms = timediff_us / 1000;
364 sr_spew("Waited %" PRIi64 " ms.", timediff_ms);
366 sr_info("Device came back after %d ms.", timediff_ms);
372 sr_err("Unable to open device.");
376 err = libusb_claim_interface(devc->usb->devhdl, USB_INTERFACE);
378 sr_err("Unable to claim interface: %s.",
379 libusb_error_name(err));
386 static int hw_dev_close(struct sr_dev_inst *sdi)
393 static int hw_cleanup(void)
395 struct drv_context *drvc;
397 if (!(drvc = di->priv))
405 static int config_set(int id, GVariant *data, const struct sr_dev_inst *sdi)
407 struct dev_context *devc;
409 uint64_t tmp_u64, p, q;
415 if (sdi->status != SR_ST_ACTIVE)
421 case SR_CONF_LIMIT_FRAMES:
422 devc->limit_frames = g_variant_get_uint64(data);
424 case SR_CONF_TRIGGER_SLOPE:
425 tmp_u64 = g_variant_get_uint64(data);
426 if (tmp_u64 != SLOPE_NEGATIVE && tmp_u64 != SLOPE_POSITIVE)
428 devc->triggerslope = tmp_u64;
430 case SR_CONF_HORIZ_TRIGGERPOS:
431 tmp_double = g_variant_get_double(data);
432 if (tmp_double < 0.0 || tmp_double > 1.0) {
433 sr_err("Trigger position should be between 0.0 and 1.0.");
436 devc->triggerposition = tmp_double;
438 case SR_CONF_BUFFERSIZE:
439 tmp_u64 = g_variant_get_uint64(data);
440 for (i = 0; buffersizes[i]; i++) {
441 if (buffersizes[i] == tmp_u64) {
442 devc->framesize = tmp_u64;
446 if (buffersizes[i] == 0)
449 case SR_CONF_TIMEBASE:
450 g_variant_get(data, "(tt)", &p, &q);
452 for (i = 0; i < ARRAY_SIZE(timebases); i++) {
453 if (timebases[i][0] == p && timebases[i][1] == q) {
459 devc->timebase = tmp_int;
463 case SR_CONF_TRIGGER_SOURCE:
464 tmp_str = g_variant_get_string(data, NULL);
465 for (i = 0; trigger_sources[i]; i++) {
466 if (!strcmp(tmp_str, trigger_sources[i])) {
467 devc->triggersource = g_strdup(tmp_str);
471 if (trigger_sources[i] == 0)
475 tmp_str = g_variant_get_string(data, NULL);
476 devc->filter_ch1 = devc->filter_ch2 = devc->filter_trigger = 0;
477 targets = g_strsplit(tmp_str, ",", 0);
478 for (i = 0; targets[i]; i++) {
479 if (targets[i] == '\0')
480 /* Empty filter string can be used to clear them all. */
482 else if (!strcmp(targets[i], "CH1"))
483 devc->filter_ch1 = TRUE;
484 else if (!strcmp(targets[i], "CH2"))
485 devc->filter_ch2 = TRUE;
486 else if (!strcmp(targets[i], "TRIGGER"))
487 devc->filter_trigger = TRUE;
489 sr_err("Invalid filter target %s.", targets[i]);
496 /* TODO: Not supporting vdiv per channel yet. */
497 g_variant_get(data, "(tt)", &p, &q);
499 for (i = 0; i < ARRAY_SIZE(vdivs); i++) {
500 if (vdivs[i][0] == p && vdivs[i][1] == q) {
506 devc->voltage_ch1 = tmp_int;
507 devc->voltage_ch2 = tmp_int;
511 case SR_CONF_COUPLING:
512 tmp_str = g_variant_get_string(data, NULL);
513 /* TODO: Not supporting coupling per channel yet. */
514 for (i = 0; coupling[i]; i++) {
515 if (!strcmp(tmp_str, coupling[i])) {
516 devc->coupling_ch1 = i;
517 devc->coupling_ch2 = i;
521 if (coupling[i] == 0)
532 static int config_list(int key, GVariant **data, const struct sr_dev_inst *sdi)
538 case SR_CONF_DEVICE_OPTIONS:
539 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_INT32,
540 devopts, ARRAY_SIZE(devopts), sizeof(int32_t));
542 case SR_CONF_BUFFERSIZE:
543 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT64,
544 buffersizes, ARRAY_SIZE(buffersizes), sizeof(uint64_t));
546 case SR_CONF_COUPLING:
547 *data = g_variant_new_strv(coupling, ARRAY_SIZE(coupling));
550 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT64,
551 vdivs, ARRAY_SIZE(vdivs) * 2, sizeof(uint64_t));
554 *data = g_variant_new_strv(filter_targets,
555 ARRAY_SIZE(filter_targets));
557 case SR_CONF_TIMEBASE:
558 *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT64,
559 timebases, ARRAY_SIZE(timebases) * 2, sizeof(uint64_t));
561 case SR_CONF_TRIGGER_SOURCE:
562 *data = g_variant_new_strv(trigger_sources,
563 ARRAY_SIZE(trigger_sources));
572 static void send_chunk(struct sr_dev_inst *sdi, unsigned char *buf,
575 struct sr_datafeed_packet packet;
576 struct sr_datafeed_analog analog;
577 struct dev_context *devc;
578 float ch1, ch2, range;
579 int num_probes, data_offset, i;
582 num_probes = (devc->ch1_enabled && devc->ch2_enabled) ? 2 : 1;
583 packet.type = SR_DF_ANALOG;
584 packet.payload = &analog;
585 /* TODO: support for 5xxx series 9-bit samples */
586 analog.probes = devc->enabled_probes;
587 analog.num_samples = num_samples;
588 analog.mq = SR_MQ_VOLTAGE;
589 analog.unit = SR_UNIT_VOLT;
590 /* TODO: Check malloc return value. */
591 analog.data = g_try_malloc(analog.num_samples * sizeof(float) * num_probes);
593 for (i = 0; i < analog.num_samples; i++) {
595 * The device always sends data for both channels. If a channel
596 * is disabled, it contains a copy of the enabled channel's
597 * data. However, we only send the requested channels to
600 * Voltage values are encoded as a value 0-255 (0-512 on the
601 * DSO-5200*), where the value is a point in the range
602 * represented by the vdiv setting. There are 8 vertical divs,
603 * so e.g. 500mV/div represents 4V peak-to-peak where 0 = -2V
606 /* TODO: Support for DSO-5xxx series 9-bit samples. */
607 if (devc->ch1_enabled) {
608 range = ((float)vdivs[devc->voltage_ch1][0] / vdivs[devc->voltage_ch1][1]) * 8;
609 ch1 = range / 255 * *(buf + i * 2 + 1);
610 /* Value is centered around 0V. */
612 analog.data[data_offset++] = ch1;
614 if (devc->ch2_enabled) {
615 range = ((float)vdivs[devc->voltage_ch2][0] / vdivs[devc->voltage_ch2][1]) * 8;
616 ch2 = range / 255 * *(buf + i * 2);
618 analog.data[data_offset++] = ch2;
621 sr_session_send(devc->cb_data, &packet);
625 * Called by libusb (as triggered by handle_event()) when a transfer comes in.
626 * Only channel data comes in asynchronously, and all transfers for this are
627 * queued up beforehand, so this just needs to chuck the incoming data onto
628 * the libsigrok session bus.
630 static void receive_transfer(struct libusb_transfer *transfer)
632 struct sr_datafeed_packet packet;
633 struct sr_dev_inst *sdi;
634 struct dev_context *devc;
635 int num_samples, pre;
637 sdi = transfer->user_data;
639 sr_dbg("receive_transfer(): status %d received %d bytes.",
640 transfer->status, transfer->actual_length);
642 if (transfer->actual_length == 0)
643 /* Nothing to send to the bus. */
646 num_samples = transfer->actual_length / 2;
648 sr_dbg("Got %d-%d/%d samples in frame.", devc->samp_received + 1,
649 devc->samp_received + num_samples, devc->framesize);
652 * The device always sends a full frame, but the beginning of the frame
653 * doesn't represent the trigger point. The offset at which the trigger
654 * happened came in with the capture state, so we need to start sending
655 * from there up the session bus. The samples in the frame buffer
656 * before that trigger point came after the end of the device's frame
657 * buffer was reached, and it wrapped around to overwrite up until the
660 if (devc->samp_received < devc->trigger_offset) {
661 /* Trigger point not yet reached. */
662 if (devc->samp_received + num_samples < devc->trigger_offset) {
663 /* The entire chunk is before the trigger point. */
664 memcpy(devc->framebuf + devc->samp_buffered * 2,
665 transfer->buffer, num_samples * 2);
666 devc->samp_buffered += num_samples;
669 * This chunk hits or overruns the trigger point.
670 * Store the part before the trigger fired, and
671 * send the rest up to the session bus.
673 pre = devc->trigger_offset - devc->samp_received;
674 memcpy(devc->framebuf + devc->samp_buffered * 2,
675 transfer->buffer, pre * 2);
676 devc->samp_buffered += pre;
678 /* The rest of this chunk starts with the trigger point. */
679 sr_dbg("Reached trigger point, %d samples buffered.",
680 devc->samp_buffered);
682 /* Avoid the corner case where the chunk ended at
683 * exactly the trigger point. */
684 if (num_samples > pre)
685 send_chunk(sdi, transfer->buffer + pre * 2,
689 /* Already past the trigger point, just send it all out. */
690 send_chunk(sdi, transfer->buffer,
694 devc->samp_received += num_samples;
696 /* Everything in this transfer was either copied to the buffer or
697 * sent to the session bus. */
698 g_free(transfer->buffer);
699 libusb_free_transfer(transfer);
701 if (devc->samp_received >= devc->framesize) {
702 /* That was the last chunk in this frame. Send the buffered
703 * pre-trigger samples out now, in one big chunk. */
704 sr_dbg("End of frame, sending %d pre-trigger buffered samples.",
705 devc->samp_buffered);
706 send_chunk(sdi, devc->framebuf, devc->samp_buffered);
708 /* Mark the end of this frame. */
709 packet.type = SR_DF_FRAME_END;
710 sr_session_send(devc->cb_data, &packet);
712 if (devc->limit_frames && ++devc->num_frames == devc->limit_frames) {
713 /* Terminate session */
714 devc->dev_state = STOPPING;
716 devc->dev_state = NEW_CAPTURE;
721 static int handle_event(int fd, int revents, void *cb_data)
723 const struct sr_dev_inst *sdi;
724 struct sr_datafeed_packet packet;
726 struct dev_context *devc;
727 struct drv_context *drvc = di->priv;
728 const struct libusb_pollfd **lupfd;
730 uint32_t trigger_offset;
731 uint8_t capturestate;
738 if (devc->dev_state == STOPPING) {
739 /* We've been told to wind up the acquisition. */
740 sr_dbg("Stopping acquisition.");
742 * TODO: Doesn't really cancel pending transfers so they might
743 * come in after SR_DF_END is sent.
745 lupfd = libusb_get_pollfds(drvc->sr_ctx->libusb_ctx);
746 for (i = 0; lupfd[i]; i++)
747 sr_source_remove(lupfd[i]->fd);
750 packet.type = SR_DF_END;
751 sr_session_send(sdi, &packet);
753 devc->dev_state = IDLE;
758 /* Always handle pending libusb events. */
759 tv.tv_sec = tv.tv_usec = 0;
760 libusb_handle_events_timeout(drvc->sr_ctx->libusb_ctx, &tv);
763 if (devc->dev_state == NEW_CAPTURE) {
764 if (dso_capture_start(devc) != SR_OK)
766 if (dso_enable_trigger(devc) != SR_OK)
768 // if (dso_force_trigger(devc) != SR_OK)
770 sr_dbg("Successfully requested next chunk.");
771 devc->dev_state = CAPTURE;
774 if (devc->dev_state != CAPTURE)
777 if ((dso_get_capturestate(devc, &capturestate, &trigger_offset)) != SR_OK)
780 sr_dbg("Capturestate %d.", capturestate);
781 sr_dbg("Trigger offset 0x%.6x.", trigger_offset);
782 switch (capturestate) {
784 if (++devc->capture_empty_count >= MAX_CAPTURE_EMPTY) {
785 devc->capture_empty_count = 0;
786 if (dso_capture_start(devc) != SR_OK)
788 if (dso_enable_trigger(devc) != SR_OK)
790 // if (dso_force_trigger(devc) != SR_OK)
792 sr_dbg("Successfully requested next chunk.");
795 case CAPTURE_FILLING:
798 case CAPTURE_READY_8BIT:
799 /* Remember where in the captured frame the trigger is. */
800 devc->trigger_offset = trigger_offset;
802 num_probes = (devc->ch1_enabled && devc->ch2_enabled) ? 2 : 1;
803 /* TODO: Check malloc return value. */
804 devc->framebuf = g_try_malloc(devc->framesize * num_probes * 2);
805 devc->samp_buffered = devc->samp_received = 0;
807 /* Tell the scope to send us the first frame. */
808 if (dso_get_channeldata(sdi, receive_transfer) != SR_OK)
812 * Don't hit the state machine again until we're done fetching
813 * the data we just told the scope to send.
815 devc->dev_state = FETCH_DATA;
817 /* Tell the frontend a new frame is on the way. */
818 packet.type = SR_DF_FRAME_BEGIN;
819 sr_session_send(sdi, &packet);
821 case CAPTURE_READY_9BIT:
823 sr_err("Not yet supported.");
825 case CAPTURE_TIMEOUT:
826 /* Doesn't matter, we'll try again next time. */
829 sr_dbg("Unknown capture state: %d.", capturestate);
836 static int hw_dev_acquisition_start(const struct sr_dev_inst *sdi,
839 const struct libusb_pollfd **lupfd;
840 struct dev_context *devc;
841 struct drv_context *drvc = di->priv;
844 if (sdi->status != SR_ST_ACTIVE)
848 devc->cb_data = cb_data;
850 if (configure_probes(sdi) != SR_OK) {
851 sr_err("Failed to configure probes.");
855 if (dso_init(devc) != SR_OK)
858 if (dso_capture_start(devc) != SR_OK)
861 devc->dev_state = CAPTURE;
862 lupfd = libusb_get_pollfds(drvc->sr_ctx->libusb_ctx);
863 for (i = 0; lupfd[i]; i++)
864 sr_source_add(lupfd[i]->fd, lupfd[i]->events, TICK,
865 handle_event, (void *)sdi);
868 /* Send header packet to the session bus. */
869 std_session_send_df_header(cb_data, DRIVER_LOG_DOMAIN);
874 static int hw_dev_acquisition_stop(struct sr_dev_inst *sdi, void *cb_data)
876 struct dev_context *devc;
880 if (sdi->status != SR_ST_ACTIVE)
884 devc->dev_state = STOPPING;
889 SR_PRIV struct sr_dev_driver hantek_dso_driver_info = {
890 .name = "hantek-dso",
891 .longname = "Hantek DSO",
894 .cleanup = hw_cleanup,
896 .dev_list = hw_dev_list,
897 .dev_clear = clear_instances,
899 .config_set = config_set,
900 .config_list = config_list,
901 .dev_open = hw_dev_open,
902 .dev_close = hw_dev_close,
903 .dev_acquisition_start = hw_dev_acquisition_start,
904 .dev_acquisition_stop = hw_dev_acquisition_stop,