USB-HID/UsbHidDevEx/hiddev.h

43 lines
1.4 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#ifndef HIDDEV_H
#define HIDDEV_H
#include <libusb-1.0/libusb.h>
#include <thread>
/* USB热拔插支持: USB热拔插通过事件驱动不用频繁查询USB的连接事件减少CPU占用。
部分libusb库不支持热拔插根据实际情况选择是否开启热拔插 */
#define USB_HOT_PLUG_SUPPORT 0
class HIDDev {
public:
HIDDev();
~HIDDev();
bool openDevice(int vendor_id, int product_id);
void closeDevice();
int read(unsigned char *data, int length);
int write(const unsigned char *data, int length);
void handleEvents();
bool isConnected();
private:
#if USB_HOT_PLUG_SUPPORT
// 热拔插回调函数
static int LIBUSB_CALL hotplug_callback(libusb_context *ctx, libusb_device *device,
libusb_hotplug_event event, void *user_data);
#endif
void usbEventHandling();
libusb_device_handle *dev_handle;
libusb_context *ctx;
std::thread usbThread; // USB事件线程处理USB的断开重连事件
bool stopThread = false; // 线程停止标志位,用于程序退出时,线程能正确退出
bool devArrived = false; // USB设备连接标志位表示设备插入待连接
int vendorId;
int productId;
bool connected = false;
bool reconnectFlag = false;
bool tryReconnect();
};
#endif // HIDDEV_H