]> sigrok.org Git - libsigrok.git/blame - src/usb.c
USB: On Windows, block to wait for libusb events
[libsigrok.git] / src / usb.c
CommitLineData
0c632d36 1/*
50985c20 2 * This file is part of the libsigrok project.
0c632d36
UH
3 *
4 * Copyright (C) 2012 Uwe Hermann <uwe@hermann-uwe.de>
5 * Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
6 *
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.
11 *
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.
16 *
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
20 */
21
22#include <stdlib.h>
db156e54 23#include <memory.h>
0c632d36
UH
24#include <glib.h>
25#include <libusb.h>
c1aae900 26#include <libsigrok/libsigrok.h>
0c632d36
UH
27#include "libsigrok-internal.h"
28
1953564a 29/* SR_CONF_CONN takes one of these: */
1eb0a0df 30#define CONN_USB_VIDPID "^([0-9a-z]{4})\\.([0-9a-z]{4})$"
0c632d36
UH
31#define CONN_USB_BUSADDR "^(\\d+)\\.(\\d+)$"
32
3544f848 33#define LOG_PREFIX "usb"
0c632d36 34
7ae6a758
BV
35/**
36 * Find USB devices according to a connection string.
37 *
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>".
41 *
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.
45 */
46SR_PRIV GSList *sr_usb_find(libusb_context *usb_ctx, const char *conn)
0c632d36 47{
7ae6a758 48 struct sr_usb_dev_inst *usb;
0c632d36
UH
49 struct libusb_device **devlist;
50 struct libusb_device_descriptor des;
51 GSList *devices;
52 GRegex *reg;
53 GMatchInfo *match;
54 int vid, pid, bus, addr, b, a, ret, i;
55 char *mstr;
56
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)) {
e7f378fd 60 if ((mstr = g_match_info_fetch(match, 1)))
0c632d36 61 vid = strtoul(mstr, NULL, 16);
0c632d36
UH
62 g_free(mstr);
63
e7f378fd 64 if ((mstr = g_match_info_fetch(match, 2)))
0c632d36 65 pid = strtoul(mstr, NULL, 16);
0c632d36
UH
66 g_free(mstr);
67 sr_dbg("Trying to find USB device with VID:PID = %04x:%04x.",
68 vid, pid);
69 } else {
70 g_match_info_unref(match);
71 g_regex_unref(reg);
72 reg = g_regex_new(CONN_USB_BUSADDR, 0, 0, NULL);
73 if (g_regex_match(reg, conn, 0, &match)) {
e7f378fd 74 if ((mstr = g_match_info_fetch(match, 1)))
1eb0a0df 75 bus = strtoul(mstr, NULL, 10);
0c632d36
UH
76 g_free(mstr);
77
e7f378fd 78 if ((mstr = g_match_info_fetch(match, 2)))
1eb0a0df 79 addr = strtoul(mstr, NULL, 10);
0c632d36
UH
80 g_free(mstr);
81 sr_dbg("Trying to find USB device with bus.address = "
82 "%d.%d.", bus, addr);
83 }
84 }
85 g_match_info_unref(match);
86 g_regex_unref(reg);
87
88 if (vid + pid + bus + addr == 0) {
e7f378fd 89 sr_err("Neither VID:PID nor bus.address was specified.");
0c632d36
UH
90 return NULL;
91 }
92
93 if (bus > 64) {
94 sr_err("Invalid bus specified: %d.", bus);
95 return NULL;
96 }
97
98 if (addr > 127) {
99 sr_err("Invalid address specified: %d.", addr);
100 return NULL;
101 }
102
103 /* Looks like a valid USB device specification, but is it connected? */
104 devices = NULL;
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))) {
d4928d71
PS
108 sr_err("Failed to get device descriptor: %s.",
109 libusb_error_name(ret));
0c632d36
UH
110 continue;
111 }
112
7ae6a758 113 if (vid + pid && (des.idVendor != vid || des.idProduct != pid))
0c632d36 114 continue;
0c632d36 115
7ae6a758
BV
116 b = libusb_get_bus_number(devlist[i]);
117 a = libusb_get_device_address(devlist[i]);
118 if (bus + addr && (b != bus || a != addr))
0c632d36 119 continue;
0c632d36
UH
120
121 sr_dbg("Found USB device (VID:PID = %04x:%04x, bus.address = "
122 "%d.%d).", des.idVendor, des.idProduct, b, a);
123
7ae6a758
BV
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);
0c632d36
UH
127 }
128 libusb_free_device_list(devlist, 1);
129
130 sr_dbg("Found %d device(s).", g_slist_length(devices));
131
132 return devices;
133}
134
135SR_PRIV int sr_usb_open(libusb_context *usb_ctx, struct sr_usb_dev_inst *usb)
136{
137 struct libusb_device **devlist;
138 struct libusb_device_descriptor des;
139 int ret, r, cnt, i, a, b;
140
c5f1a021 141 sr_dbg("Trying to open USB device %d.%d.", usb->bus, usb->address);
0c632d36
UH
142
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));
146 return SR_ERR;
147 }
148
149 ret = SR_ERR;
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));
154 continue;
155 }
156
157 b = libusb_get_bus_number(devlist[i]);
158 a = libusb_get_device_address(devlist[i]);
c5f1a021 159 if (b != usb->bus || a != usb->address)
0c632d36 160 continue;
0c632d36
UH
161
162 if ((r = libusb_open(devlist[i], &usb->devhdl)) < 0) {
163 sr_err("Failed to open device: %s.",
164 libusb_error_name(r));
165 break;
166 }
167
168 sr_dbg("Opened USB device (VID:PID = %04x:%04x, bus.address = "
169 "%d.%d).", des.idVendor, des.idProduct, b, a);
170
171 ret = SR_OK;
172 break;
173 }
174
175 libusb_free_device_list(devlist, 1);
176
177 return ret;
178}
6c60facc 179
67e95ed3
BV
180SR_PRIV void sr_usb_close(struct sr_usb_dev_inst *usb)
181{
182 libusb_close(usb->devhdl);
183 usb->devhdl = NULL;
184 sr_dbg("Closed USB device %d.%d.", usb->bus, usb->address);
185}
186
358c4ed5
DE
187#ifdef G_OS_WIN32
188/*
189 * USB callback wrapper run when the main loop is idle.
190 */
dcc94340 191static int usb_callback(int fd, int revents, void *cb_data)
5321ac6b 192{
358c4ed5
DE
193 int64_t start_time, stop_time, due, timeout;
194 struct timeval tv;
195 struct sr_context *ctx;
5321ac6b
ML
196 int ret;
197
358c4ed5
DE
198 (void)fd;
199 (void)revents;
200 ctx = cb_data;
34ea7f96 201
358c4ed5 202 start_time = g_get_monotonic_time();
f6c30de4 203
358c4ed5
DE
204 due = ctx->usb_due;
205 timeout = MAX(due - start_time, 0);
206 tv.tv_sec = timeout / G_USEC_PER_SEC;
207 tv.tv_usec = timeout % G_USEC_PER_SEC;
5321ac6b 208
358c4ed5
DE
209 sr_spew("libusb_handle_events enter, timeout %g ms", 1e-3 * timeout);
210
211 ret = libusb_handle_events_timeout_completed(ctx->libusb_ctx,
212 (ctx->usb_timeout < 0) ? NULL : &tv, NULL);
213 if (ret != 0) {
214 /* Warn but still invoke the callback, to give the driver
215 * a chance to deal with the problem.
216 */
217 sr_warn("Error handling libusb event (%s)",
218 libusb_error_name(ret));
219 }
220 stop_time = g_get_monotonic_time();
221
222 sr_spew("libusb_handle_events leave, %g ms elapsed",
223 1e-3 * (stop_time - start_time));
224
225 if (ctx->usb_timeout >= 0)
226 ctx->usb_due = stop_time + ctx->usb_timeout;
227 /*
228 * Run registered callback to execute any follow-up activity
229 * to libusb event handling.
230 */
231 return ctx->usb_cb(-1, (stop_time < due) ? G_IO_IN : 0,
232 ctx->usb_cb_data);
5321ac6b
ML
233}
234#endif
235
102f1239
BV
236SR_PRIV int usb_source_add(struct sr_session *session, struct sr_context *ctx,
237 int timeout, sr_receive_data_callback cb, void *cb_data)
6c60facc 238{
92248e78
DE
239 int ret;
240
6640324f
ML
241 if (ctx->usb_source_present) {
242 sr_err("A USB event source is already present.");
243 return SR_ERR;
244 }
245
358c4ed5
DE
246#ifdef G_OS_WIN32
247 if (timeout >= 0) {
248 ctx->usb_timeout = INT64_C(1000) * timeout;
249 ctx->usb_due = g_get_monotonic_time() + ctx->usb_timeout;
250 } else {
251 ctx->usb_timeout = -1;
252 ctx->usb_due = INT64_MAX;
253 }
5321ac6b
ML
254 ctx->usb_cb = cb;
255 ctx->usb_cb_data = cb_data;
358c4ed5
DE
256 /*
257 * TODO: Install an idle source which will fire permanently, and block
258 * in a wrapper callback until any libusb events have been processed.
259 * This will have to do for now, until we implement a proper way to
260 * deal with libusb events on Windows.
261 */
262 ret = sr_session_source_add(session, -2, 0, 0, &usb_callback, ctx);
6c60facc
ML
263#else
264 const struct libusb_pollfd **lupfd;
92248e78
DE
265 GPollFD *pollfds;
266 int i;
267 int num_fds = 0;
6c60facc
ML
268
269 lupfd = libusb_get_pollfds(ctx->libusb_ctx);
92248e78
DE
270 if (!lupfd || !lupfd[0]) {
271 free(lupfd);
272 sr_err("Failed to get libusb file descriptors.");
273 return SR_ERR;
274 }
275 while (lupfd[num_fds])
276 ++num_fds;
277 pollfds = g_new(GPollFD, num_fds);
278
279 for (i = 0; i < num_fds; ++i) {
280 pollfds[i].fd = lupfd[i]->fd;
281 pollfds[i].events = lupfd[i]->events;
282 pollfds[i].revents = 0;
62d7945f 283 }
6c60facc 284 free(lupfd);
92248e78
DE
285 ret = sr_session_source_add_internal(session, pollfds, num_fds,
286 timeout, cb, cb_data, (gintptr)ctx->libusb_ctx);
287 g_free(pollfds);
5321ac6b 288#endif
92248e78 289 ctx->usb_source_present = (ret == SR_OK);
6c60facc 290
92248e78 291 return ret;
6c60facc
ML
292}
293
102f1239 294SR_PRIV int usb_source_remove(struct sr_session *session, struct sr_context *ctx)
6c60facc 295{
92248e78
DE
296 int ret;
297
6640324f
ML
298 if (!ctx->usb_source_present)
299 return SR_OK;
300
358c4ed5
DE
301#ifdef G_OS_WIN32
302 /* Remove our idle source */
303 sr_session_source_remove(session, -2);
6c60facc 304#else
92248e78
DE
305 ret = sr_session_source_remove_internal(session,
306 (gintptr)ctx->libusb_ctx);
5321ac6b 307#endif
6640324f 308 ctx->usb_source_present = FALSE;
6c60facc 309
92248e78 310 return ret;
6c60facc 311}
db156e54 312
76bc5f63 313SR_PRIV int usb_get_port_path(libusb_device *dev, char *path, int path_len)
db156e54 314{
76bc5f63
AJ
315 uint8_t port_numbers[8];
316 int i, n, len;
317
19643b96
UJ
318/*
319 * FreeBSD requires that devices prior to calling libusb_get_port_numbers()
320 * have been opened with libusb_open().
321 */
322#ifdef __FreeBSD__
323 struct libusb_device_handle *devh;
324 if (libusb_open(dev, &devh) != 0)
325 return SR_ERR;
326#endif
76bc5f63 327 n = libusb_get_port_numbers(dev, port_numbers, sizeof(port_numbers));
19643b96
UJ
328#ifdef __FreeBSD__
329 libusb_close(devh);
330#endif
76bc5f63 331
19643b96
UJ
332/* Workaround FreeBSD libusb_get_port_numbers() returning 0. */
333#ifdef __FreeBSD__
334 if (n == 0) {
335 port_numbers[0] = libusb_get_device_address(dev);
336 n = 1;
337 }
338#endif
2f004b4b
VP
339 if (n < 1)
340 return SR_ERR;
341
76bc5f63
AJ
342 len = snprintf(path, path_len, "usb/%d-%d",
343 libusb_get_bus_number(dev), port_numbers[0]);
db156e54 344
76bc5f63
AJ
345 for (i = 1; i < n; i++)
346 len += snprintf(path+len, path_len-len, ".%d", port_numbers[i]);
db156e54
SA
347
348 return SR_OK;
349}