GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — libusb/examples/hotplugtest.c at master · Raghuvardhan-Reddy78/libusb

Expand file tree

/

hotplugtest.c

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
489 lines (413 loc) · 13.8 KB
/

hotplugtest.c

Copy path

File metadata and controls

489 lines (413 loc) · 13.8 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
/* -*- Mode: C; indent-tabs-mode:t ; c-basic-offset:8 -*- */
/*
* libusb example program for hotplug API
* Copyright © 2012-2013 Nathan Hjelm <[email protected]>
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <config.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
/* Solaris implements FD_ZERO() as a memset() call, so <string.h> is required
* even though this file makes no direct use of it. */
#include <string.h>
#include <signal.h>
#include <inttypes.h>
/* Cygwin defines PLATFORM_WINDOWS but does not provide <conio.h>;
* it provides the POSIX terminal APIs instead. */
#if defined(PLATFORM_POSIX) || defined(__CYGWIN__)
#define USE_POSIX_TERMINAL
#endif
#if defined(USE_POSIX_TERMINAL)
#include <errno.h>
#include <unistd.h>
#include <termios.h>
#include <sys/select.h>
#elif defined(PLATFORM_WINDOWS)
#include <conio.h>
#endif
#include "libusb.h"
struct hotplug_state {
uint64_t arrived;
uint64_t departed;
volatile sig_atomic_t quit;
};
static volatile sig_atomic_t signal_exit_requested = 0;
#if defined(USE_POSIX_TERMINAL)
static bool terminal_configured = false;
static struct termios terminal_saved;
#endif
static void handle_signal(int signum)
{
(void)signum;
signal_exit_requested = 1;
}
static const char *speed_name(int speed)
{
switch (speed) {
case LIBUSB_SPEED_LOW:
return "1.5M";
case LIBUSB_SPEED_FULL:
return "12M";
case LIBUSB_SPEED_HIGH:
return "480M";
case LIBUSB_SPEED_SUPER:
return "5G";
case LIBUSB_SPEED_SUPER_PLUS:
return "10G";
case LIBUSB_SPEED_SUPER_PLUS_X2:
return "20G";
case LIBUSB_SPEED_UNKNOWN:
default:
return "unknown";
}
}
static void print_counters(const struct hotplug_state *state)
{
int64_t difference = (int64_t)state->arrived - (int64_t)state->departed;
printf("[arrived=%" PRIu64 " departed=%" PRIu64 " delta=%" PRId64"]\n",
state->arrived, state->departed, difference);
}
static void print_device_event(const char *event_name, libusb_device *dev, const struct hotplug_state *state)
{
struct libusb_device_descriptor desc;
char string_buffer[LIBUSB_DEVICE_STRING_BYTES_MAX];
uint8_t path[8];
int rc;
int i;
rc = libusb_get_device_descriptor(dev, &desc);
if (LIBUSB_SUCCESS == rc) {
printf("%s: %04x:%04x (bus %d, device %d)",
event_name, desc.idVendor, desc.idProduct,
libusb_get_bus_number(dev), libusb_get_device_address(dev));
rc = libusb_get_port_numbers(dev, path, sizeof(path));
if (rc > 0) {
printf(" path: %d", path[0]);
for (i = 1; i < rc; i++)
printf(".%d", path[i]);
}
printf("\n speed = %s", speed_name(libusb_get_device_speed(dev)));
rc = libusb_get_device_string(dev, LIBUSB_DEVICE_STRING_SERIAL_NUMBER,
string_buffer, sizeof(string_buffer));
if (rc >= 0)
printf("\n serial_number = %s", string_buffer);
printf("\n");
} else {
printf("%s\n", event_name);
fprintf(stderr, "Error getting device descriptor: %s\n",
libusb_strerror((enum libusb_error)rc));
}
print_counters(state);
}
static bool check_for_quit_key(void)
{
#if defined(USE_POSIX_TERMINAL)
fd_set read_fds;
struct timeval timeout = { 0, 0 };
char c;
int rc;
FD_ZERO(&read_fds);
FD_SET(STDIN_FILENO, &read_fds);
rc = select(STDIN_FILENO + 1, &read_fds, NULL, NULL, &timeout);
if (rc < 0) {
if (errno == EINTR)
return false;
return false;
}
if (rc > 0 && FD_ISSET(STDIN_FILENO, &read_fds) && read(STDIN_FILENO, &c, 1) == 1)
return c == 'q' || c == 'Q';
return false;
#elif defined(PLATFORM_WINDOWS)
if (_kbhit()) {
int c = _getch();
return c == 'q' || c == 'Q';
}
return false;
#else
return false;
#endif
}
#if defined(USE_POSIX_TERMINAL)
static int setup_terminal(void)
{
struct termios new_termios;
if (!isatty(STDIN_FILENO))
return 0;
if (tcgetattr(STDIN_FILENO, &terminal_saved) != 0)
return -1;
new_termios = terminal_saved;
new_termios.c_lflag &= (tcflag_t)~(ICANON | ECHO);
new_termios.c_cc[VMIN] = 0;
new_termios.c_cc[VTIME] = 0;
if (tcsetattr(STDIN_FILENO, TCSANOW, &new_termios) != 0)
return -1;
terminal_configured = true;
return 0;
}
static void restore_terminal(void)
{
if (terminal_configured) {
(void)tcsetattr(STDIN_FILENO, TCSANOW, &terminal_saved);
terminal_configured = false;
}
}
#else
static int setup_terminal(void)
{
return 0;
}
static void restore_terminal(void)
{
}
#endif
static int ask_hotplug_enumerate_flag(void)
{
char line[16];
for (;;) {
printf("Use LIBUSB_HOTPLUG_ENUMERATE for already-connected devices? [Y/n]: ");
fflush(stdout);
if (NULL == fgets(line, sizeof(line), stdin)) {
printf("\nNo input received; defaulting to yes.\n");
return LIBUSB_HOTPLUG_ENUMERATE;
}
if ('\n' == line[0] || 'y' == line[0] || 'Y' == line[0])
return LIBUSB_HOTPLUG_ENUMERATE;
if ('n' == line[0] || 'N' == line[0])
return 0;
printf("Please answer y or n.\n");
}
}
/* When enabled (-o on command line), each arrival is probed for actual usability:
* open the device and try to claim (then immediately release) every interface of the
* active configuration, printing the outcome of each call. This makes issues
* where DEVICE_ARRIVED fires for a not-yet-usable device directly visible. */
static bool open_on_arrival = false;
static void open_and_claim(libusb_device *dev)
{
struct libusb_config_descriptor *config;
libusb_device_handle *handle;
uint8_t i;
int rc;
rc = libusb_open(dev, &handle);
printf(" open = %s\n",
(LIBUSB_SUCCESS == rc) ? "OK" : libusb_strerror((enum libusb_error)rc));
if (LIBUSB_SUCCESS != rc)
return;
rc = libusb_get_active_config_descriptor(dev, &config);
if (LIBUSB_SUCCESS != rc) {
printf(" get active config = %s\n", libusb_strerror((enum libusb_error)rc));
libusb_close(handle);
return;
}
for (i = 0; i < config->bNumInterfaces; i++) {
const int interface_number = config->interface[i].altsetting[0].bInterfaceNumber;
rc = libusb_claim_interface(handle, interface_number);
printf(" claim interface %d = %s\n", interface_number,
(LIBUSB_SUCCESS == rc) ? "OK" : libusb_strerror((enum libusb_error)rc));
if (LIBUSB_SUCCESS == rc)
libusb_release_interface(handle, interface_number);
}
libusb_free_config_descriptor(config);
libusb_close(handle);
}
static int LIBUSB_CALL hotplug_callback(libusb_context *ctx, libusb_device *dev, libusb_hotplug_event event, void *user_data)
{
struct hotplug_state *state = (struct hotplug_state *)user_data;
(void)ctx;
(void)event;
state->arrived++;
print_device_event("\nDevice attached", dev, state);
if (open_on_arrival)
open_and_claim(dev);
return 0;
}
static int LIBUSB_CALL hotplug_callback_detach(libusb_context *ctx, libusb_device *dev, libusb_hotplug_event event, void *user_data)
{
struct hotplug_state *state = (struct hotplug_state *)user_data;
(void)ctx;
(void)event;
state->departed++;
print_device_event("\nDevice detached", dev, state);
return 0;
}
static void print_usage(FILE *out, const char *program_name)
{
fprintf(out, "Usage: %s [-o] [-c class] [vid[:pid]]\n", program_name);
fprintf(out, " -h print this help text and exit\n");
fprintf(out, " -o on each arrival, open the device and try to claim each\n");
fprintf(out, " interface of its active configuration, printing the outcome\n");
fprintf(out, " -c class only match devices of this class (hexadecimal)\n");
fprintf(out, "vid and pid are hexadecimal, e.g. 04b4:8613; vid alone matches any\n");
fprintf(out, "product of that vendor. Without filters, all devices are monitored.\n");
}
/* Parse one id of a rejected command line so that a hint with the new
* syntax can be offered when the old "vendor product [class]" form is
* used. Base 0 recovers the ids of scripts written against the old
* strtol-based parsing; base 16 recovers hex-style ids such as 04b4. */
static bool parse_id_base(const char *s, int base, long max, long *value)
{
char *end;
*value = strtol(s, &end, base);
return '\0' == *end && 0 <= *value && *value <= max;
}
int main(int argc, const char *argv[])
{
libusb_context *ctx = NULL;
struct hotplug_state state = { 0, 0, 0 };
libusb_hotplug_callback_handle hp[2];
bool callback_registered[2] = { false, false };
int vendor_id = LIBUSB_HOTPLUG_MATCH_ANY;
int product_id = LIBUSB_HOTPLUG_MATCH_ANY;
int class_id = LIBUSB_HOTPLUG_MATCH_ANY;
int arrival_flags;
const char *first_positional = NULL;
int nb_positional = 0;
int arg;
int rc;
for (arg = 1; arg < argc; arg++) {
if (0 == strcmp(argv[arg], "-o")) {
open_on_arrival = true;
} else if (0 == strcmp(argv[arg], "-h") || 0 == strcmp(argv[arg], "--help") ||
0 == strcmp(argv[arg], "-?")) {
print_usage(stdout, argv[0]);
return EXIT_SUCCESS;
} else if (0 == strcmp(argv[arg], "-c")) {
char *end;
long value;
if (arg + 1 >= argc) {
fprintf(stderr, "Option -c requires an argument\n");
print_usage(stderr, argv[0]);
return EXIT_FAILURE;
}
arg++;
value = strtol(argv[arg], &end, 16);
if (end == argv[arg] || '\0' != *end || value < 0 || value > 0xff) {
fprintf(stderr, "Invalid class: %s\n", argv[arg]);
print_usage(stderr, argv[0]);
return EXIT_FAILURE;
}
class_id = (int)value;
} else if ('-' == argv[arg][0]) {
fprintf(stderr, "Unknown option: %s\n", argv[arg]);
print_usage(stderr, argv[0]);
return EXIT_FAILURE;
} else if (0 == nb_positional) {
unsigned int vid, pid;
int consumed = 0;
if (2 == sscanf(argv[arg], "%x:%x%n", &vid, &pid, &consumed) &&
'\0' == argv[arg][consumed] && vid <= 0xffff && pid <= 0xffff) {
vendor_id = (int)vid;
product_id = (int)pid;
} else if (1 == sscanf(argv[arg], "%x%n", &vid, &consumed) &&
'\0' == argv[arg][consumed] && vid <= 0xffff) {
vendor_id = (int)vid;
} else {
fprintf(stderr, "Invalid vid[:pid]: %s\n", argv[arg]);
print_usage(stderr, argv[0]);
return EXIT_FAILURE;
}
first_positional = argv[arg];
nb_positional++;
} else {
long id1 = 0, id2 = 0, id3 = 0;
fprintf(stderr, "Too many arguments: %s\n", argv[arg]);
if (NULL != strchr(first_positional, ':')) {
if (parse_id_base(argv[arg], 16, 0xff, &id3))
fprintf(stderr, "The class must be given with -c; the equivalent is: \"%s -c %lx\"\n",
first_positional, id3);
} else {
/* looks like the old "vendor product [class]" form; use one
* coherent base for all ids when reconstructing the intent */
const char *class_str = (arg + 1 < argc) ? argv[arg + 1] : NULL;
bool ok = parse_id_base(first_positional, 0, 0xffff, &id1) &&
parse_id_base(argv[arg], 0, 0xffff, &id2) &&
(NULL == class_str || parse_id_base(class_str, 0, 0xff, &id3));
if (!ok)
ok = parse_id_base(first_positional, 16, 0xffff, &id1) &&
parse_id_base(argv[arg], 16, 0xffff, &id2) &&
(NULL == class_str || parse_id_base(class_str, 16, 0xff, &id3));
if (ok) {
fprintf(stderr, "Separate vendor and product ids are no longer accepted; the equivalent is: \"%04lx:%04lx",
id1, id2);
if (NULL != class_str)
fprintf(stderr, " -c %lx", id3);
fprintf(stderr, "\"\n");
}
}
print_usage(stderr, argv[0]);
return EXIT_FAILURE;
}
}
/* Keep stdout unbuffered so that captured events (to file or pipe)
* interleave correctly with libusb's stderr debug output and nothing
* is lost if the process is terminated externally. */
setvbuf(stdout, NULL, _IONBF, 0);
rc = libusb_init_context(&ctx, /*options=*/NULL, /*num_options=*/0);
if (LIBUSB_SUCCESS != rc)
{
printf ("failed to initialise libusb: %s\n",
libusb_strerror((enum libusb_error)rc));
return EXIT_FAILURE;
}
if (!libusb_has_capability (LIBUSB_CAP_HAS_HOTPLUG)) {
printf ("Hotplug capabilities are not supported on this platform\n");
libusb_exit (ctx);
return EXIT_FAILURE;
}
arrival_flags = ask_hotplug_enumerate_flag();
if (setup_terminal() != 0)
fprintf(stderr, "Warning: failed to setup terminal for q/Q input\n");
(void)signal(SIGINT, handle_signal);
printf("Monitoring hotplug events. Press q or Q to quit, or Ctrl-C.\n");
rc = libusb_hotplug_register_callback (ctx, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED,
arrival_flags, vendor_id, product_id, class_id,
hotplug_callback, &state, &hp[0]);
if (LIBUSB_SUCCESS != rc) {
fprintf (stderr, "Error registering callback 0\n");
restore_terminal();
libusb_exit (ctx);
return EXIT_FAILURE;
}
callback_registered[0] = true;
rc = libusb_hotplug_register_callback (ctx, LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT, 0, vendor_id,
product_id,class_id, hotplug_callback_detach, &state, &hp[1]);
if (LIBUSB_SUCCESS != rc) {
fprintf (stderr, "Error registering callback 1\n");
libusb_hotplug_deregister_callback(ctx, hp[0]);
restore_terminal();
libusb_exit (ctx);
return EXIT_FAILURE;
}
callback_registered[1] = true;
while (!state.quit) {
struct timeval tv = { 0, 50000 };
rc = libusb_handle_events_timeout_completed(ctx, &tv, NULL);
if (LIBUSB_SUCCESS != rc && LIBUSB_ERROR_INTERRUPTED != rc)
printf ("libusb_handle_events_timeout_completed() failed: %s\n",
libusb_strerror((enum libusb_error)rc));
if (signal_exit_requested || check_for_quit_key())
state.quit = 1;
}
if (callback_registered[1])
libusb_hotplug_deregister_callback(ctx, hp[1]);
if (callback_registered[0])
libusb_hotplug_deregister_callback(ctx, hp[0]);
restore_terminal();
libusb_exit (ctx);
return EXIT_SUCCESS;
}
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.