USB-HID/UsbHidDevEx/hiddev.h

43 lines
1.4 KiB
C
Raw Permalink Normal View History

2024-04-21 14:05:38 +08:00
#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