2 * This file is part of the libsigrok project.
4 * Copyright (C) 2012 Uwe Hermann <uwe@hermann-uwe.de>
5 * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
26 #include <libsigrok/libsigrok.h>
27 #include "libsigrok-internal.h"
29 /* SR_CONF_CONN takes one of these: */
30 #define CONN_USB_VIDPID "^([0-9a-z]{4})\\.([0-9a-z]{4})$"
31 #define CONN_USB_BUSADDR "^(\\d+)\\.(\\d+)$"
33 #define LOG_PREFIX "usb"
36 * Find USB devices according to a connection string.
38 * @param usb_ctx libusb context to use while scanning.
39 * @param conn Connection string specifying the device(s) to match. This
40 * can be of the form "<bus>.<address>", or "<vendorid>.<productid>".
42 * @return A GSList of struct sr_usb_dev_inst, with bus and address fields
43 * matching the device that matched the connection string. The GSList and
44 * its contents must be freed by the caller.
46 SR_PRIV GSList *sr_usb_find(libusb_context *usb_ctx, const char *conn)
48 struct sr_usb_dev_inst *usb;
49 struct libusb_device **devlist;
50 struct libusb_device_descriptor des;
54 int vid, pid, bus, addr, b, a, ret, i;
57 vid = pid = bus = addr = 0;
58 reg = g_regex_new(CONN_USB_VIDPID, 0, 0, NULL);
59 if (g_regex_match(reg, conn, 0, &match)) {
60 if ((mstr = g_match_info_fetch(match, 1)))
61 vid = strtoul(mstr, NULL, 16);
64 if ((mstr = g_match_info_fetch(match, 2)))
65 pid = strtoul(mstr, NULL, 16);
67 sr_dbg("Trying to find USB device with VID:PID = %04x:%04x.",
70 g_match_info_unref(match);
72 reg = g_regex_new(CONN_USB_BUSADDR, 0, 0, NULL);
73 if (g_regex_match(reg, conn, 0, &match)) {
74 if ((mstr = g_match_info_fetch(match, 1)))
75 bus = strtoul(mstr, NULL, 10);
78 if ((mstr = g_match_info_fetch(match, 2)))
79 addr = strtoul(mstr, NULL, 10);
81 sr_dbg("Trying to find USB device with bus.address = "
85 g_match_info_unref(match);
88 if (vid + pid + bus + addr == 0) {
89 sr_err("Neither VID:PID nor bus.address was specified.");
94 sr_err("Invalid bus specified: %d.", bus);
99 sr_err("Invalid address specified: %d.", addr);
103 /* Looks like a valid USB device specification, but is it connected? */
105 libusb_get_device_list(usb_ctx, &devlist);
106 for (i = 0; devlist[i]; i++) {
107 if ((ret = libusb_get_device_descriptor(devlist[i], &des))) {
108 sr_err("Failed to get device descriptor: %s.",
109 libusb_error_name(ret));
113 if (vid + pid && (des.idVendor != vid || des.idProduct != pid))
116 b = libusb_get_bus_number(devlist[i]);
117 a = libusb_get_device_address(devlist[i]);
118 if (bus + addr && (b != bus || a != addr))
121 sr_dbg("Found USB device (VID:PID = %04x:%04x, bus.address = "
122 "%d.%d).", des.idVendor, des.idProduct, b, a);
124 usb = sr_usb_dev_inst_new(libusb_get_bus_number(devlist[i]),
125 libusb_get_device_address(devlist[i]), NULL);
126 devices = g_slist_append(devices, usb);
128 libusb_free_device_list(devlist, 1);
130 sr_dbg("Found %d device(s).", g_slist_length(devices));
135 SR_PRIV int sr_usb_open(libusb_context *usb_ctx, struct sr_usb_dev_inst *usb)
137 struct libusb_device **devlist;
138 struct libusb_device_descriptor des;
139 int ret, r, cnt, i, a, b;
141 sr_dbg("Trying to open USB device %d.%d.", usb->bus, usb->address);
143 if ((cnt = libusb_get_device_list(usb_ctx, &devlist)) < 0) {
144 sr_err("Failed to retrieve device list: %s.",
145 libusb_error_name(cnt));
150 for (i = 0; i < cnt; i++) {
151 if ((r = libusb_get_device_descriptor(devlist[i], &des)) < 0) {
152 sr_err("Failed to get device descriptor: %s.",
153 libusb_error_name(r));
157 b = libusb_get_bus_number(devlist[i]);
158 a = libusb_get_device_address(devlist[i]);
159 if (b != usb->bus || a != usb->address)
162 if ((r = libusb_open(devlist[i], &usb->devhdl)) < 0) {
163 sr_err("Failed to open device: %s.",
164 libusb_error_name(r));
168 sr_dbg("Opened USB device (VID:PID = %04x:%04x, bus.address = "
169 "%d.%d).", des.idVendor, des.idProduct, b, a);
175 libusb_free_device_list(devlist, 1);
180 SR_PRIV void sr_usb_close(struct sr_usb_dev_inst *usb)
182 libusb_close(usb->devhdl);
184 sr_dbg("Closed USB device %d.%d.", usb->bus, usb->address);
189 * USB callback wrapper run when the main loop is idle.
191 static int usb_callback(int fd, int revents, void *cb_data)
193 int64_t start_time, stop_time, due, timeout;
195 struct sr_context *ctx;
202 start_time = g_get_monotonic_time();
205 if (due > start_time) {
206 timeout = due - start_time;
207 tv.tv_sec = timeout / G_USEC_PER_SEC;
208 tv.tv_usec = timeout % G_USEC_PER_SEC;
210 sr_spew("libusb_handle_events enter: %g ms timeout",
213 ret = libusb_handle_events_timeout_completed(ctx->libusb_ctx,
214 (ctx->usb_timeout < 0) ? NULL : &tv, NULL);
216 /* Warn but still invoke the callback, to give
217 * the driver a chance to deal with the problem.
219 sr_warn("Error handling libusb event (%s)",
220 libusb_error_name(ret));
222 stop_time = g_get_monotonic_time();
224 sr_spew("libusb_handle_events leave: %g ms elapsed",
225 1e-3 * (stop_time - start_time));
227 * The event source may have been removed by the driver's
228 * libusb transfer callback. Skip the callback in that case.
230 if (!ctx->usb_source_present)
233 /* Timeout already expired on entry.
235 stop_time = start_time;
237 sr_spew("libusb_handle_events skipped");
240 if (ctx->usb_timeout >= 0)
241 ctx->usb_due = stop_time + ctx->usb_timeout;
243 * Run the registered callback to execute any follow-up activity
244 * to libusb's event handling.
246 return ctx->usb_cb(-1, (stop_time < due) ? G_IO_IN : 0,
251 SR_PRIV int usb_source_add(struct sr_session *session, struct sr_context *ctx,
252 int timeout, sr_receive_data_callback cb, void *cb_data)
256 if (ctx->usb_source_present) {
257 sr_err("A USB event source is already present.");
263 ctx->usb_timeout = INT64_C(1000) * timeout;
264 ctx->usb_due = g_get_monotonic_time() + ctx->usb_timeout;
266 ctx->usb_timeout = -1;
267 ctx->usb_due = INT64_MAX;
270 ctx->usb_cb_data = cb_data;
272 * TODO: Install an idle source which will fire permanently, and block
273 * in a wrapper callback until any libusb events have been processed.
274 * This will have to do for now, until we implement a proper way to
275 * deal with libusb events on Windows.
277 ret = sr_session_source_add_internal(session, NULL, 0,
278 0, &usb_callback, ctx, (gintptr)ctx->libusb_ctx);
280 const struct libusb_pollfd **lupfd;
285 lupfd = libusb_get_pollfds(ctx->libusb_ctx);
286 if (!lupfd || !lupfd[0]) {
288 sr_err("Failed to get libusb file descriptors.");
291 while (lupfd[num_fds])
293 pollfds = g_new(GPollFD, num_fds);
295 for (i = 0; i < num_fds; ++i) {
296 pollfds[i].fd = lupfd[i]->fd;
297 pollfds[i].events = lupfd[i]->events;
298 pollfds[i].revents = 0;
301 ret = sr_session_source_add_internal(session, pollfds, num_fds,
302 timeout, cb, cb_data, (gintptr)ctx->libusb_ctx);
305 ctx->usb_source_present = (ret == SR_OK);
310 SR_PRIV int usb_source_remove(struct sr_session *session, struct sr_context *ctx)
312 return sr_session_source_remove_internal(session,
313 (gintptr)ctx->libusb_ctx);
316 SR_PRIV int usb_get_port_path(libusb_device *dev, char *path, int path_len)
318 uint8_t port_numbers[8];
322 * FreeBSD requires that devices prior to calling libusb_get_port_numbers()
323 * have been opened with libusb_open().
326 struct libusb_device_handle *devh;
327 if (libusb_open(dev, &devh) != 0)
330 n = libusb_get_port_numbers(dev, port_numbers, sizeof(port_numbers));
335 /* Workaround FreeBSD libusb_get_port_numbers() returning 0. */
338 port_numbers[0] = libusb_get_device_address(dev);
345 len = snprintf(path, path_len, "usb/%d-%d",
346 libusb_get_bus_number(dev), port_numbers[0]);
348 for (i = 1; i < n; i++)
349 len += snprintf(path+len, path_len-len, ".%d", port_numbers[i]);