Skip to content

Commit

Permalink
examples/hotplugtest: Allow multiple devices attaching
Browse files Browse the repository at this point in the history
If no device ID is specified, and for instance a hub is plugged, many
devices will be attached (and later detached) at the same time. The old
code counting only 2 events would then exit prematurely.

By counting attach and detach events separately, we preserve the old
behaviour in the single-device case, but also allow more complex
sequences to be handled in a way that mostly appears intuitive.

This is not fool-proof, and we can still end up leaving after a surprise
detachment of a "pre-existing" device while we have one of the "new"
devices open. In this case print a warning.

References libusb#1455

Signed-off-by: Tormod Volden <[email protected]>
  • Loading branch information
tormodvolden committed Aug 12, 2024
1 parent 467b6a8 commit 32e063d
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions examples/hotplugtest.c
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@

#include "libusb.h"

int done = 0;
int done_attach = 0;
int done_detach = 0;
libusb_device_handle *handle = NULL;

static int LIBUSB_CALL hotplug_callback(libusb_context *ctx, libusb_device *dev, libusb_hotplug_event event, void *user_data)
Expand Down Expand Up @@ -56,7 +57,7 @@ static int LIBUSB_CALL hotplug_callback(libusb_context *ctx, libusb_device *dev,
libusb_strerror((enum libusb_error)rc));
}

done++;
done_attach++;

return 0;
}
Expand Down Expand Up @@ -85,7 +86,7 @@ static int LIBUSB_CALL hotplug_callback_detach(libusb_context *ctx, libusb_devic
handle = NULL;
}

done++;
done_detach++;

return 0;
}
Expand Down Expand Up @@ -130,14 +131,15 @@ int main(int argc, char *argv[])
return EXIT_FAILURE;
}

while (done < 2) {
while (done_detach < done_attach || done_attach == 0) {
rc = libusb_handle_events (NULL);
if (LIBUSB_SUCCESS != rc)
printf ("libusb_handle_events() failed: %s\n",
libusb_strerror((enum libusb_error)rc));
}

if (handle) {
printf ("Warning: Closing left-over open handle\n");
libusb_close (handle);
}

Expand Down

0 comments on commit 32e063d

Please sign in to comment.