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