#include <QObject>
#include <QCoreApplication>
#include <QtSerialPort/QSerialPort>
#include <QUsbDevice>
#include <QUsbDeviceWatcher>
#include <QByteArray>
#include <QDebug>
class UsbSerialBridge : public QObject
{
Q_OBJECT
public:
explicit UsbSerialBridge(QObject *parent = nullptr) : QObject(parent)
{
// 创建USB设备监视器
usbWatcher = new QUsbDeviceWatcher(this);
// 连接USB设备监视器的设备变更信号
connect(usbWatcher, &QUsbDeviceWatcher::deviceAdded, this, &UsbSerialBridge::handleDeviceAdded);
connect(usbWatcher, &QUsbDeviceWatcher::deviceRemoved, this, &UsbSerialBridge::handleDeviceRemoved);
// 开始监听USB设备变更
usbWatcher->start();
// 创建串口对象
serialPort = new QSerialPort(this);
// 设置串口参数
serialPort->setPortName("/dev/ttyUSB0");
serialPort->setBaudRate(QSerialPort::Baud9600);
serialPort->setDataBits(QSerialPort::Data8);
serialPort->setParity(QSerialPort::NoParity);
serialPort->setStopBits(QSerialPort::OneStop);
serialPort->setFlowControl(QSerialPort::NoFlowControl);
// 连接串口数据读取信号
connect(serialPort, &QSerialPort::readyRead, this, &UsbSerialBridge::readData);
// 打开串口
if (!serialPort->open(QIODevice::ReadWrite))
{
qDebug() << "Failed to open serial port";
return;
}
// 程序主循环
QCoreApplication::processEvents();
// 关闭串口
serialPort->close();
}
private:
QUsbDeviceWatcher *usbWatcher;
QSerialPort *serialPort;
private slots:
// 槽函数:处理USB设备添加事件
void handleDeviceAdded(const QUsbDevice &device)
{
qDebug() << "USB device added:";
qDebug() << " Vendor ID:" << device.vendorId();
qDebug() << " Product ID:" << device.productId();
// 检查是否是目标USB设备
if (device.vendorId() == 0x1234 && device.productId() == 0x5678)
{
// 关闭当前已打开的串口
serialPort->close();
// 设置新的串口名称
serialPort->setPortName(device.systemLocation());
// 打开新的串口
if (!serialPort->open(QIODevice::ReadWrite))
{
qDebug() << "Failed to open serial port";
return;
}
}
}
// 槽函数:处理USB设备移除事件
void handleDeviceRemoved(const QUsbDevice &device)
{
qDebug() << "USB device removed:";
qDebug() << " Vendor ID:" << device.vendorId();
qDebug() << " Product ID:" << device.productId();
// 检查是否是目标USB设备
if (device.vendorId() == 0x1234 && device.productId() == 0x5678)
{
// 关闭当前已打开的串口
serialPort->close();
}
}
// 槽函数:接收数据并转发到串口
void readData()
{
QByteArray data = serialPort->readAll();
// 处理数据
// ...
// 发送数据到USB设备
// ...
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 创建UsbSerialBridge对象
UsbSerialBridge bridge;
return a.exec();
}