以下为判断usb设备是插入还是拔出状态(热插拔)的测试代码: 在Windows下是不支持的,在Linux是支持的,下一个版本可能会支持Windows下的热插拔:

#include <chrono>
#include <thread>
#include <iostream>
#include <libusb.h>

namespace {

bool running = true;

int LIBUSB_CALL hotplug_callback(libusb_context* ctx, libusb_device* dev, libusb_hotplug_event event, void* user_data)
{
	struct libusb_device_descriptor desc;
	int ret = libusb_get_device_descriptor(dev, &desc);
	if (LIBUSB_SUCCESS != ret) {
		fprintf(stderr, "fail to get device descriptor: %d, %s\n", ret, libusb_error_name(ret));
		//return -1;
	}

	if (event == LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED)
		fprintf(stdout, "device attached: %04x:%04x\n", desc.idVendor, desc.idProduct);
	else if (event == LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT)
		fprintf(stdout, "device detached: %04x:%04x\n", desc.idVendor, desc.idProduct);
	else
		fprintf(stderr, "Error: unsupported hotplug events\n");

	return 0;
}

void run()
{
	for (int i = 0; i < 60; ++i)
		std::this_thread::sleep_for(std::chrono::seconds(1));
	running = false;
}

} // namespace

int test_libusb_hotplug()
{
	// reference: examples/hotplugtest.c
#ifdef _MSC_VER
	const char* platform = "Windows";
#else
	const char* platform = "Linux";
#endif

	int ret = libusb_init(nullptr);
	if (ret != 0) {
		fprintf(stderr, "fail to init: %d, %s\n", ret, libusb_error_name(ret));
		return -1;
	}

	if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
		fprintf(stderr, "hotplug capabilites are not supported on this platform: %s\n", platform);
		libusb_exit(nullptr);
		return -1;
	}

	int vendor_id = 0x046d, product_id = 0x081b;
	libusb_hotplug_callback_handle hp[2];
	ret = libusb_hotplug_register_callback(nullptr, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED, LIBUSB_HOTPLUG_NO_FLAGS, vendor_id,
		product_id, LIBUSB_HOTPLUG_MATCH_ANY, hotplug_callback, nullptr, &hp[0]);
	if (LIBUSB_SUCCESS != ret) {
		fprintf(stderr, "fail to register callback arrived: %d, %s\n", ret, libusb_error_name(ret));
		libusb_exit(nullptr);
		return -1;
	}

	ret = libusb_hotplug_register_callback(nullptr, LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT, LIBUSB_HOTPLUG_NO_FLAGS, vendor_id,
		product_id, LIBUSB_HOTPLUG_MATCH_ANY, hotplug_callback, nullptr, &hp[1]);
	if (LIBUSB_SUCCESS != ret) {
		fprintf(stderr, "fail to register callback left: %d, %s\n", ret, libusb_error_name(ret));
		libusb_exit(nullptr);
		return -1;
	}

	std::thread th(run);

	while (running) {
		//ret = libusb_handle_events(nullptr);
		timeval tv = {1, 0};
		ret = libusb_handle_events_timeout(nullptr, &tv);
		if (ret < 0)
			fprintf(stderr, "fail to libusb_handle_events: %d, %s\n", ret, libusb_error_name(ret));
	}

	libusb_exit(nullptr);
	th.join();

	return 0;
}

在Windows下执行结果如下:

在Linux下执行结果如下:对usb视频设备进行反复插拔

GitHubhttps://github.com//fengbingchun/OpenCV_Test

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐