#include
class USBListener : public QObject { Q_OBJECT
public: explicit USBListener(QObject *parent = nullptr) : QObject(parent) { // 初始化libusb libusb_init(&context);
// 启动定时器(每隔1秒)检查设备连接状态 connect(&timer, &QTimer::timeout, this, &USBListener::checkDeviceStatus); timer.start(1000);
// 初始时检查设备连接状态 if (isDeviceConnected()) { openDevice(); } }
~USBListener() { closeDevice(); libusb_exit(context); // 关闭libusb }
private: libusb_context *context; QSerialPort serialPort; QTimer timer;
bool isDeviceConnected() { // 检查USB设备是否已连接 libusb_device_handle *handle = libusb_open_device_with_vid_pid(context, VENDOR_ID, PRODUCT_ID); if (handle) { libusb_close(handle); return true; } return false; }
void openDevice() { // 打开USB设备并进行通信设置 serialPort.setPortName("COM1"); // 设置串口名字,根据实际情况修改 serialPort.setBaudRate(QSerialPort::Baud115200); // 设置波特率,根据实际情况修改 serialPort.setDataBits(QSerialPort::Data8); // 设置数据位,根据实际情况修改 serialPort.setParity(QSerialPort::NoParity); // 设置校验位,根据实际情况修改 serialPort.setStopBits(QSerialPort::OneStop); // 设置停止位,根据实际情况修改 serialPort.setFlowControl(QSerialPort::NoFlowControl); // 设置流控制,根据实际情况修改
if (serialPort.open(QIODevice::ReadWrite)) { qDebug() << "USB device opened"; connect(&serialPort, &QSerialPort::readyRead, this, &USBListener::readData); } else { qDebug() << "Failed to open USB device"; } }
void closeDevice() { if (serialPort.isOpen()) { serialPort.close(); qDebug() << "USB device closed"; } }
void readData() { QByteArray data = serialPort.readAll(); qDebug() << "Received data:" << data; }
public slots: void checkDeviceStatus() { if (isDeviceConnected()) { if (!serialPort.isOpen()) { openDevice(); } } else { if (serialPort.isOpen()) { closeDevice(); } } } };
class USBEventFilter : public QObject { Q_OBJECT
public: explicit USBEventFilter(QObject *parent = nullptr) : QObject(parent) { // 安装事件过滤器,监听USB插拔事件 QCoreApplication::instance()->installEventFilter(this); }
bool eventFilter(QObject *obj, QEvent *event) override { if (event->type() == QEvent::DynamicPropertyChange) { // 检测到USB插拔事件 qDebug() << "USB device plugged or unplugged"; // 在这里处理热插拔逻辑 // 例如发送信号或执行其他操作 }
return QObject::eventFilter(obj, event); } };
int main(int argc, char *argv[]) { QCoreApplication a(argc, argv);
USBListener usbListener; USBEventFilter usbEventFilter;
return a.exec(); }
USBListener类负责监听和处理USB设备的连接状态和通信操作。
在构造函数中,我们初始化libusb,并启动一个定时器(每隔1秒)来检查设备的连接状态。isDeviceConnected函数用于检查USB设备是否已连接。openDevice函数用于打开和配置USB设备的通信设置。closeDevice函数用于关闭USB设备。checkDeviceStatus函数是一个槽函数,在定时器触发时调用,用于检查设备的连接状态并执行相应的操作。 USBEventFilter类负责监听USB插拔事件,并在事件发生时执行相应的逻辑。
在构造函数中,我们使用installEventFilter方法将USBEventFilter对象安装为全局事件过滤器。在eventFilter函数中,我们检测到USB插拔事件后,可以在此处处理热插拔逻辑,例如发送信号或执行其他操作。
在main函数中,我们创建了一个USBListener对象和一个USBEventFilter对象,并通过调用a.exec()来启动Qt事件循环。
推荐文章
发表评论