test_com.c
2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <libusb-1.0/libusb.h>
#include <stdio.h>
#include <stdlib.h>
// gcc file.c -l usb-1.0
int main(){
// init
libusb_context *context;
int status = libusb_init(&context);
if(status != 0){perror("libusb_init"); exit(-1);}
// devices list
libusb_device **devices;
ssize_t devices_count = libusb_get_device_list(context, &devices);
if(devices_count < 0){perror("libusb_get_device_list"); exit(-1);}
for(int i=0; i<devices_count; i++){
libusb_device *device = devices[i];
// device description
struct libusb_device_descriptor desc;
int status = libusb_get_device_descriptor(device, &desc);
if(status != 0) continue;
// search for device
if(desc.idVendor != 0x0951
|| desc.idProduct != 0x01666)
continue;
// open connection
libusb_device_handle *handle;
status = libusb_open(device, &handle);
if(status != 0){ perror("libusb_open"); exit(-1); }
// prepare config
struct libusb_config_descriptor *config_desc;
status = libusb_get_config_descriptor(device, 0, &config_desc);
if(status != 0){ perror("libusb_get_config_descriptor"); exit(-1); }
int configuration = config_desc->bConfigurationValue;
// detach kernel
for(int j=0; j<config_desc->bNumInterfaces; j++){
for(int k=0; k<config_desc->interface[j].num_altsetting; k++){
int interface = config_desc->interface[j].altsetting[k].bInterfaceNumber;
if(libusb_kernel_driver_active(handle, interface)){
status = libusb_detach_kernel_driver(handle, interface);
if(status != 0){ perror("libusb_detach_kernel_driver"); exit(-1); }
}
}
}
// use config
status = libusb_set_configuration(handle, configuration);
if(status != 0){ perror("libusb_set_configuration"); exit(-1); }
// claim interfaces
for(int j=0; j<config_desc->bNumInterfaces; j++){
for(int k=0; k<config_desc->interface[j].num_altsetting; k++){
int interface = config_desc->interface[j].altsetting[k].bInterfaceNumber;
status = libusb_claim_interface(handle, interface);
if(status != 0){ perror("libusb_claim_interface"); exit(-1); }
}
}
/* ... some code ... */
// TODO endpoints
// release interfaces
for(int j=0; j<config_desc->bNumInterfaces; j++){
for(int k=0; k<config_desc->interface[j].num_altsetting; k++){
int interface = config_desc->interface[j].altsetting[k].bInterfaceNumber;
status = libusb_release_interface(handle, interface);
if(status != 0){ perror("libusb_release_interface"); exit(-1); }
}
}
// free config
libusb_free_config_descriptor(config_desc);
// close connection
libusb_close(handle);
}
libusb_free_device_list(devices, 1);
libusb_exit(context);
}