]> sigrok.org Git - libsigrok.git/blob - src/usb.c
Build: Set local include directories in Makefile.am
[libsigrok.git] / src / usb.c
1 /*
2  * This file is part of the libsigrok project.
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>
23 #include <memory.h>
24 #include <glib.h>
25 #include <libusb.h>
26 #include <libsigrok/libsigrok.h>
27 #include "libsigrok-internal.h"
28
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+)$"
32
33 #define LOG_PREFIX "usb"
34
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  */
46 SR_PRIV GSList *sr_usb_find(libusb_context *usb_ctx, const char *conn)
47 {
48         struct sr_usb_dev_inst *usb;
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)) {
60                 if ((mstr = g_match_info_fetch(match, 1)))
61                         vid = strtoul(mstr, NULL, 16);
62                 g_free(mstr);
63
64                 if ((mstr = g_match_info_fetch(match, 2)))
65                         pid = strtoul(mstr, NULL, 16);
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)) {
74                         if ((mstr = g_match_info_fetch(match, 1)))
75                                 bus = strtoul(mstr, NULL, 10);
76                         g_free(mstr);
77
78                         if ((mstr = g_match_info_fetch(match, 2)))
79                                 addr = strtoul(mstr, NULL, 10);
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) {
89                 sr_err("Neither VID:PID nor bus.address was specified.");
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))) {
108                         sr_err("Failed to get device descriptor: %s.",
109                                libusb_error_name(ret));
110                         continue;
111                 }
112
113                 if (vid + pid && (des.idVendor != vid || des.idProduct != pid))
114                         continue;
115
116                 b = libusb_get_bus_number(devlist[i]);
117                 a = libusb_get_device_address(devlist[i]);
118                 if (bus + addr && (b != bus || a != addr))
119                         continue;
120
121                 sr_dbg("Found USB device (VID:PID = %04x:%04x, bus.address = "
122                        "%d.%d).", des.idVendor, des.idProduct, b, a);
123
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);
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
135 SR_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
141         sr_dbg("Trying to open USB device %d.%d.", usb->bus, usb->address);
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]);
159                 if (b != usb->bus || a != usb->address)
160                         continue;
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 }
179
180 #ifdef _WIN32
181 /* Thread used to run libusb_wait_for_event() and set a pollable event. */
182 static gpointer usb_thread(gpointer data)
183 {
184         struct sr_context *ctx = data;
185
186         while (ctx->usb_thread_running) {
187                 /* Acquire event waiters lock, needed for libusb_wait_for_event(). */
188                 libusb_lock_event_waiters(ctx->libusb_ctx);
189                 /* Wait for any libusb event. The main thread can interrupt this wait
190                  * by calling libusb_unlock_events(). */
191                 libusb_wait_for_event(ctx->libusb_ctx, NULL);
192                 /* Release event waiters lock. */
193                 libusb_unlock_event_waiters(ctx->libusb_ctx);
194                 /* Set event that the main loop will be polling on. */
195                 SetEvent(ctx->usb_wait_complete_event);
196                 /* Wait for the main thread to signal us to run again. */
197                 WaitForSingleObject(ctx->usb_wait_request_event, INFINITE);
198                 ResetEvent(ctx->usb_wait_request_event);
199         }
200
201         return NULL;
202 }
203
204 /* Callback wrapper run when main g_poll() gets a USB event or timeout. */
205 static int usb_callback(int fd, int revents, void *cb_data)
206 {
207         struct sr_context *ctx = cb_data;
208         int ret;
209
210         /* Run registered callback to handle libusb events. */
211         ret = ctx->usb_cb(fd, revents, ctx->usb_cb_data);
212
213         /* Were we triggered by an event from the wait thread, rather than by a
214          * timeout? */
215         int triggered_by_event = (revents & G_IO_IN);
216
217         /* If so, and if the USB event source has not been removed from the
218          * session, reset the event that woke us and tell the wait thread to start
219          * waiting for events again. */
220         if (triggered_by_event && ctx->usb_thread_running) {
221                 ResetEvent(ctx->usb_wait_complete_event);
222                 SetEvent(ctx->usb_wait_request_event);
223         }
224
225         return ret;
226 }
227 #endif
228
229 SR_PRIV int usb_source_add(struct sr_session *session, struct sr_context *ctx,
230                 int timeout, sr_receive_data_callback cb, void *cb_data)
231 {
232         if (ctx->usb_source_present) {
233                 sr_err("A USB event source is already present.");
234                 return SR_ERR;
235         }
236
237 #ifdef _WIN32
238         /* Create events used to signal between main and USB wait threads. */
239         ctx->usb_wait_request_event = CreateEvent(NULL, TRUE, FALSE, NULL);
240         ctx->usb_wait_complete_event = CreateEvent(NULL, TRUE, FALSE, NULL);
241         /* Start USB wait thread. */
242         ctx->usb_thread_running = TRUE;
243         ctx->usb_thread = g_thread_new("usb", usb_thread, ctx);
244         /* Add event, set by USB wait thread, to session poll set. */
245         ctx->usb_pollfd.fd = ctx->usb_wait_complete_event;
246         ctx->usb_pollfd.events = G_IO_IN;
247         ctx->usb_cb = cb;
248         ctx->usb_cb_data = cb_data;
249         sr_session_source_add_pollfd(session, &ctx->usb_pollfd, timeout,
250                         usb_callback, ctx);
251 #else
252         const struct libusb_pollfd **lupfd;
253         unsigned int i;
254
255         lupfd = libusb_get_pollfds(ctx->libusb_ctx);
256         for (i = 0; lupfd[i]; i++)
257                 sr_session_source_add(session, lupfd[i]->fd, lupfd[i]->events,
258                                 timeout, cb, cb_data);
259         free(lupfd);
260 #endif
261         ctx->usb_source_present = TRUE;
262
263         return SR_OK;
264 }
265
266 SR_PRIV int usb_source_remove(struct sr_session *session, struct sr_context *ctx)
267 {
268         if (!ctx->usb_source_present)
269                 return SR_OK;
270
271 #ifdef _WIN32
272         /* Signal the USB wait thread to stop, then unblock it so it does. */
273         ctx->usb_thread_running = FALSE;
274         SetEvent(ctx->usb_wait_request_event);
275         libusb_unlock_events(ctx->libusb_ctx);
276         /* Wait for USB wait thread to terminate. */
277         g_thread_join(ctx->usb_thread);
278         /* Remove USB event from session poll set. */
279         sr_session_source_remove_pollfd(session, &ctx->usb_pollfd);
280         /* Close event handles that were used between threads. */
281         CloseHandle(ctx->usb_wait_request_event);
282         CloseHandle(ctx->usb_wait_complete_event);
283 #else
284         const struct libusb_pollfd **lupfd;
285         unsigned int i;
286
287         lupfd = libusb_get_pollfds(ctx->libusb_ctx);
288         for (i = 0; lupfd[i]; i++)
289                 sr_session_source_remove(session, lupfd[i]->fd);
290         free(lupfd);
291 #endif
292         ctx->usb_source_present = FALSE;
293
294         return SR_OK;
295 }
296
297 SR_PRIV int usb_get_port_path(libusb_device *dev, char *path, int path_len)
298 {
299         uint8_t port_numbers[8];
300         int i, n, len;
301
302 /*
303  * FreeBSD requires that devices prior to calling libusb_get_port_numbers()
304  * have been opened with libusb_open().
305  */
306 #ifdef __FreeBSD__
307         struct libusb_device_handle *devh;
308         if (libusb_open(dev, &devh) != 0)
309                 return SR_ERR;
310 #endif
311         n = libusb_get_port_numbers(dev, port_numbers, sizeof(port_numbers));
312 #ifdef __FreeBSD__
313         libusb_close(devh);
314 #endif
315
316 /* Workaround FreeBSD libusb_get_port_numbers() returning 0. */
317 #ifdef __FreeBSD__
318         if (n == 0) {
319                 port_numbers[0] = libusb_get_device_address(dev);
320                 n = 1;
321         }
322 #endif
323         if (n < 1)
324                 return SR_ERR;
325
326         len = snprintf(path, path_len, "usb/%d-%d",
327                        libusb_get_bus_number(dev), port_numbers[0]);
328
329         for (i = 1; i < n; i++)
330                 len += snprintf(path+len, path_len-len, ".%d", port_numbers[i]);
331
332         return SR_OK;
333 }