| 201 | #include <libusb-1.0/libusb.h> |
| 202 | |
| 203 | struct libusb_device_handle *open_usb_device( int vid, int pid ) |
| 204 | { |
| 205 | libusb_device **devs; |
| 206 | struct libusb_device_handle *handle = NULL; |
| 207 | struct libusb_device_handle *ret = NULL; |
| 208 | |
| 209 | if ( libusb_init( NULL ) != 0 ) |
| 210 | fprintf( stderr, "libusb_init failed.\n" ); |
| 211 | |
| 212 | size_t count = libusb_get_device_list( NULL, &devs ); |
| 213 | if ( count < 0 ) |
| 214 | fprintf( stderr, "libusb_get_device_list failed.\n" ); |
| 215 | |
| 216 | for ( size_t c = 0; c < count; c++ ) |
| 217 | { |
| 218 | struct libusb_device_descriptor desc; |
| 219 | libusb_device *dev = devs[c]; |
| 220 | |
| 221 | if ( libusb_get_device_descriptor( dev, &desc ) < 0 ) |
| 222 | fprintf( stderr, "libusb_get_device_descriptor failed.\n" ); |
| 223 | |
| 224 | //printf("ID: %04x Product: %04x\n", desc.idVendor, desc.idProduct ); |
| 225 | // Not correct device |
| 226 | if ( desc.idVendor != vid || desc.idProduct != pid ) |
| 227 | continue; |
| 228 | |
| 229 | // Attempt to open the device |
| 230 | if ( libusb_open( dev, &handle ) != 0 ) |
| 231 | { |
| 232 | fprintf( stderr, "Found device but unable to open\n" ); |
| 233 | continue; |
| 234 | } |
| 235 | |
| 236 | // Only required on Linux, other platforms will just ignore this call |
| 237 | libusb_detach_kernel_driver( handle, 0 ); |
| 238 | |
| 239 | // Mac OS-X - removing this call to usb_claim_interface() might allow |
| 240 | // this to work, even though it is a clear misuse of the libusb API. |
| 241 | // normally Apple's IOKit should be used on Mac OS-X |
| 242 | // XXX Is this still valid with libusb-1.0? |
| 243 | |
| 244 | // Attempt to claim interface |
| 245 | int err = libusb_claim_interface( handle, 0 ); |
| 246 | if ( err < 0 ) |
| 247 | { |
| 248 | libusb_close( handle ); |
| 249 | fprintf( stderr, "Unable to claim interface, check USB permissions: %d\n", err ); |
| 250 | continue; |
| 251 | } |
| 252 | |
| 253 | ret = handle; |
| 254 | break; |
| 255 | } |
| 256 | |
| 257 | libusb_free_device_list( devs, 1 ); |
| 258 | |
| 259 | return ret; |
| 260 | } |
no test coverage detected
searching dependent graphs…