]> sigrok.org Git - libsigrok.git/blob - hardware/common/usb.c
0de54b90653d86f56bb1d58cf8f890ba6bdc1d2a
[libsigrok.git] / hardware / common / 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 <glib.h>
24 #include <libusb.h>
25 #include "libsigrok.h"
26 #include "libsigrok-internal.h"
27
28 /* SR_CONF_CONN takes one of these: */
29 #define CONN_USB_VIDPID  "^([0-9a-z]{4})\\.([0-9a-z]{4})$"
30 #define CONN_USB_BUSADDR "^(\\d+)\\.(\\d+)$"
31
32 /* Some USBTMC-specific enums, as defined in the USBTMC standard. */
33 #define SUBCLASS_USBTMC 0x03
34 #define USBTMC_USB488   0x01
35
36 /* Message logging helpers with subsystem-specific prefix string. */
37 #define LOG_PREFIX "usb: "
38 #define sr_log(l, s, args...) sr_log(l, LOG_PREFIX s, ## args)
39 #define sr_spew(s, args...) sr_spew(LOG_PREFIX s, ## args)
40 #define sr_dbg(s, args...) sr_dbg(LOG_PREFIX s, ## args)
41 #define sr_info(s, args...) sr_info(LOG_PREFIX s, ## args)
42 #define sr_warn(s, args...) sr_warn(LOG_PREFIX s, ## args)
43 #define sr_err(s, args...) sr_err(LOG_PREFIX s, ## args)
44
45 /**
46  * Find USB devices according to a connection string.
47  *
48  * @param usb_ctx libusb context to use while scanning.
49  * @param conn Connection string specifying the device(s) to match. This
50  * can be of the form "<bus>.<address>", or "<vendorid>.<productid>".
51  *
52  * @return A GSList of struct sr_usb_dev_inst, with bus and address fields
53  * matching the device that matched the connection string. The GSList and
54  * its contents must be freed by the caller.
55  */
56 SR_PRIV GSList *sr_usb_find(libusb_context *usb_ctx, const char *conn)
57 {
58         struct sr_usb_dev_inst *usb;
59         struct libusb_device **devlist;
60         struct libusb_device_descriptor des;
61         GSList *devices;
62         GRegex *reg;
63         GMatchInfo *match;
64         int vid, pid, bus, addr, b, a, ret, i;
65         char *mstr;
66
67         vid = pid = bus = addr = 0;
68         reg = g_regex_new(CONN_USB_VIDPID, 0, 0, NULL);
69         if (g_regex_match(reg, conn, 0, &match)) {
70                 if ((mstr = g_match_info_fetch(match, 1)))
71                         vid = strtoul(mstr, NULL, 16);
72                 g_free(mstr);
73
74                 if ((mstr = g_match_info_fetch(match, 2)))
75                         pid = strtoul(mstr, NULL, 16);
76                 g_free(mstr);
77                 sr_dbg("Trying to find USB device with VID:PID = %04x:%04x.",
78                        vid, pid);
79         } else {
80                 g_match_info_unref(match);
81                 g_regex_unref(reg);
82                 reg = g_regex_new(CONN_USB_BUSADDR, 0, 0, NULL);
83                 if (g_regex_match(reg, conn, 0, &match)) {
84                         if ((mstr = g_match_info_fetch(match, 1)))
85                                 bus = strtoul(mstr, NULL, 10);
86                         g_free(mstr);
87
88                         if ((mstr = g_match_info_fetch(match, 2)))
89                                 addr = strtoul(mstr, NULL, 10);
90                         g_free(mstr);
91                         sr_dbg("Trying to find USB device with bus.address = "
92                                "%d.%d.", bus, addr);
93                 }
94         }
95         g_match_info_unref(match);
96         g_regex_unref(reg);
97
98         if (vid + pid + bus + addr == 0) {
99                 sr_err("Neither VID:PID nor bus.address was specified.");
100                 return NULL;
101         }
102
103         if (bus > 64) {
104                 sr_err("Invalid bus specified: %d.", bus);
105                 return NULL;
106         }
107
108         if (addr > 127) {
109                 sr_err("Invalid address specified: %d.", addr);
110                 return NULL;
111         }
112
113         /* Looks like a valid USB device specification, but is it connected? */
114         devices = NULL;
115         libusb_get_device_list(usb_ctx, &devlist);
116         for (i = 0; devlist[i]; i++) {
117                 if ((ret = libusb_get_device_descriptor(devlist[i], &des))) {
118                         sr_err("Failed to get device descriptor: %s.",
119                                libusb_error_name(ret));
120                         continue;
121                 }
122
123                 if (vid + pid && (des.idVendor != vid || des.idProduct != pid))
124                         continue;
125
126                 b = libusb_get_bus_number(devlist[i]);
127                 a = libusb_get_device_address(devlist[i]);
128                 if (bus + addr && (b != bus || a != addr))
129                         continue;
130
131                 sr_dbg("Found USB device (VID:PID = %04x:%04x, bus.address = "
132                        "%d.%d).", des.idVendor, des.idProduct, b, a);
133
134                 usb = sr_usb_dev_inst_new(libusb_get_bus_number(devlist[i]),
135                                 libusb_get_device_address(devlist[i]), NULL);
136                 devices = g_slist_append(devices, usb);
137         }
138         libusb_free_device_list(devlist, 1);
139
140         sr_dbg("Found %d device(s).", g_slist_length(devices));
141         
142         return devices;
143 }
144
145 /**
146  * Find USB devices supporting the USBTMC class
147  *
148  * @param usb_ctx libusb context to use while scanning.
149  *
150  * @return A GSList of struct sr_usb_dev_inst, with bus and address fields
151  * indicating devices with USBTMC support.
152  */
153 SR_PRIV GSList *sr_usb_find_usbtmc(libusb_context *usb_ctx)
154 {
155         struct sr_usb_dev_inst *usb;
156         struct libusb_device **devlist;
157         struct libusb_device_descriptor des;
158         struct libusb_config_descriptor *confdes;
159         const struct libusb_interface_descriptor *intfdes;
160         GSList *devices;
161         int confidx, intfidx, ret, i;
162
163         devices = NULL;
164         libusb_get_device_list(usb_ctx, &devlist);
165         for (i = 0; devlist[i]; i++) {
166                 if ((ret = libusb_get_device_descriptor(devlist[i], &des))) {
167                         sr_err("Failed to get device descriptor: %s.",
168                                libusb_error_name(ret));
169                         continue;
170                 }
171
172                 for (confidx = 0; confidx < des.bNumConfigurations; confidx++) {
173                         if (libusb_get_config_descriptor(devlist[i], confidx, &confdes) != 0) {
174                                 sr_err("Failed to get configuration descriptor.");
175                                 break;
176                         }
177                         for (intfidx = 0; intfidx < confdes->bNumInterfaces; intfidx++) {
178                                 intfdes = confdes->interface[intfidx].altsetting;
179                                 if (intfdes->bInterfaceClass != LIBUSB_CLASS_APPLICATION
180                                                 || intfdes->bInterfaceSubClass != SUBCLASS_USBTMC
181                                                 || intfdes->bInterfaceProtocol != USBTMC_USB488)
182                                         continue;
183                                 sr_dbg("Found USBTMC device (VID:PID = %04x:%04x, bus.address = "
184                                            "%d.%d).", des.idVendor, des.idProduct,
185                                            libusb_get_bus_number(devlist[i]),
186                                            libusb_get_device_address(devlist[i]));
187
188                                 usb = sr_usb_dev_inst_new(libusb_get_bus_number(devlist[i]),
189                                                 libusb_get_device_address(devlist[i]), NULL);
190                                 devices = g_slist_append(devices, usb);
191                         }
192                         libusb_free_config_descriptor(confdes);
193                 }
194         }
195         libusb_free_device_list(devlist, 1);
196
197         sr_dbg("Found %d device(s).", g_slist_length(devices));
198
199         return devices;
200 }
201
202 SR_PRIV int sr_usb_open(libusb_context *usb_ctx, struct sr_usb_dev_inst *usb)
203 {
204         struct libusb_device **devlist;
205         struct libusb_device_descriptor des;
206         int ret, r, cnt, i, a, b;
207
208         sr_dbg("Trying to open USB device %d.%d.", usb->bus, usb->address);
209
210         if ((cnt = libusb_get_device_list(usb_ctx, &devlist)) < 0) {
211                 sr_err("Failed to retrieve device list: %s.",
212                        libusb_error_name(cnt));
213                 return SR_ERR;
214         }
215
216         ret = SR_ERR;
217         for (i = 0; i < cnt; i++) {
218                 if ((r = libusb_get_device_descriptor(devlist[i], &des)) < 0) {
219                         sr_err("Failed to get device descriptor: %s.",
220                                libusb_error_name(r));
221                         continue;
222                 }
223
224                 b = libusb_get_bus_number(devlist[i]);
225                 a = libusb_get_device_address(devlist[i]);
226                 if (b != usb->bus || a != usb->address)
227                         continue;
228
229                 if ((r = libusb_open(devlist[i], &usb->devhdl)) < 0) {
230                         sr_err("Failed to open device: %s.",
231                                libusb_error_name(r));
232                         break;
233                 }
234
235                 sr_dbg("Opened USB device (VID:PID = %04x:%04x, bus.address = "
236                        "%d.%d).", des.idVendor, des.idProduct, b, a);
237
238                 ret = SR_OK;
239                 break;
240         }
241
242         libusb_free_device_list(devlist, 1);
243
244         return ret;
245 }
246
247 #ifdef _WIN32
248 SR_PRIV gpointer usb_thread(gpointer data)
249 {
250         struct sr_context *ctx = data;
251
252         while (ctx->usb_thread_running) {
253                 g_mutex_lock(&ctx->usb_mutex);
254                 libusb_wait_for_event(ctx->libusb_ctx, NULL);
255                 SetEvent(ctx->usb_event);
256                 g_mutex_unlock(&ctx->usb_mutex);
257                 g_thread_yield();
258         }
259
260         return NULL;
261 }
262
263 SR_PRIV int usb_callback(int fd, int revents, void *cb_data)
264 {
265         struct sr_context *ctx = cb_data;
266         int ret;
267
268         g_mutex_lock(&ctx->usb_mutex);
269         ret = ctx->usb_cb(fd, revents, ctx->usb_cb_data);
270
271         if (ctx->usb_thread_running) {
272                 ResetEvent(ctx->usb_event);
273                 g_mutex_unlock(&ctx->usb_mutex);
274         }
275
276         return ret;
277 }
278 #endif
279
280 SR_PRIV int usb_source_add(struct sr_context *ctx, int timeout,
281                 sr_receive_data_callback_t cb, void *cb_data)
282 {
283         if (ctx->usb_source_present) {
284                 sr_err("A USB event source is already present.");
285                 return SR_ERR;
286         }
287
288 #ifdef _WIN32
289         ctx->usb_event = CreateEvent(NULL, TRUE, FALSE, NULL);
290         g_mutex_init(&ctx->usb_mutex);
291         ctx->usb_thread_running = TRUE;
292         ctx->usb_thread = g_thread_new("usb", usb_thread, ctx);
293         ctx->usb_pollfd.fd = ctx->usb_event;
294         ctx->usb_pollfd.events = G_IO_IN;
295         ctx->usb_cb = cb;
296         ctx->usb_cb_data = cb_data;
297         sr_session_source_add_pollfd(&ctx->usb_pollfd, timeout, usb_callback, ctx);
298 #else
299         const struct libusb_pollfd **lupfd;
300         unsigned int i;
301
302         lupfd = libusb_get_pollfds(ctx->libusb_ctx);
303         for (i = 0; lupfd[i]; i++)
304                 sr_source_add(lupfd[i]->fd, lupfd[i]->events, timeout, cb, cb_data);
305         free(lupfd);
306 #endif
307         ctx->usb_source_present = TRUE;
308
309         return SR_OK;
310 }
311
312 SR_PRIV int usb_source_remove(struct sr_context *ctx)
313 {
314         if (!ctx->usb_source_present)
315                 return SR_OK;
316
317 #ifdef _WIN32
318         ctx->usb_thread_running = FALSE;
319         g_mutex_unlock(&ctx->usb_mutex);
320         libusb_unlock_events(ctx->libusb_ctx);
321         g_thread_join(ctx->usb_thread);
322         g_mutex_clear(&ctx->usb_mutex);
323         sr_session_source_remove_pollfd(&ctx->usb_pollfd);
324         CloseHandle(ctx->usb_event);
325 #else
326         const struct libusb_pollfd **lupfd;
327         unsigned int i;
328
329         lupfd = libusb_get_pollfds(ctx->libusb_ctx);
330         for (i = 0; lupfd[i]; i++)
331                 sr_source_remove(lupfd[i]->fd);
332         free(lupfd);
333 #endif
334         ctx->usb_source_present = FALSE;
335
336         return SR_OK;
337 }