在qt环境中,写出完整libusb 同步传输例程,使用多线程读写操作,使用c++实现,封装成一个类,并在主界面调用,显示发送和接收的数据。并在此基础上,实现热拔插功能
时间: 2024-10-09 10:06:46 浏览: 42
Qt-C++读写NXP、富士通15693标签源码
在Qt环境中,使用libusb库进行同步传输并实现多线程读写操作,首先需要安装Qt和libusb库。以下是使用C++创建一个基本的USB设备通信类(UsbTransfer),包含热拔插功能和数据显示的部分代码:
```cpp
#include <QObject>
#include <QThread>
#include <QMutex>
#include <QPair>
#include <libusb.h>
class UsbDevice : public QObject {
Q_OBJECT
public:
explicit UsbDevice(int deviceIndex, QObject *parent = nullptr);
~UsbDevice();
private slots:
void startReadThread();
void stopReadThread();
void onDataReceived(QByteArray data);
signals:
void newDataAvailable(const QByteArray &data);
private:
int deviceIndex;
libusb_device_handle* devHandle;
QThread readThread;
bool isReading;
QMutex mutex;
std::queue<QPair<QString, QByteArray>> receivedData; // 存储发送和接收的数据
static void* readTransfer(void* arg);
};
// 实现细节...
void UsbDevice::startReadThread() {
if (!isReading && libusb_open(devHandle, &readThreadId)) {
// 开启新线程进行读取操作
isReading = true;
readThread.start(readTransfer, this);
}
}
// 热插拔处理(假设onDeviceConnected和onDeviceDisconnected是外部信号)
void UsbDevice::onDeviceConnected() {
if (devHandle == nullptr) {
if (libusb_open_device_with_vid_pid(deviceIndex, USB_VENDOR_ID, USB_PRODUCT_ID, &devHandle)) {
// 打开设备并启动读取线程
startReadThread();
} else {
qWarning("Failed to open device");
}
}
}
void UsbDevice::onDeviceDisconnected() {
if (devHandle != nullptr) {
isReading = false;
// 关闭设备和线程
libusb_close(devHandle);
devHandle = nullptr;
emit newDataAvailable(receivedData); // 清空数据队列并发出信号
}
}
// 进行同步读取的线程函数
void* UsbDevice::readTransfer(void* arg) {
while (isReading) {
ssize_t bytesRead = libusb_bulk_transfer(devHandle, USB_BULK_IN_EP, nullptr, 0, &transferSize, 5000);
if (bytesRead > 0) {
char* buffer = new char[bytesRead];
libusb_fill_bulk_transfer(&transfer, devHandle, USB_BULK_IN_EP, buffer, bytesRead, NULL, 0, 5000);
libusb_submit_transfer(&transfer);
QMutexLocker locker(&mutex);
receivedData.push({QString("Rx %1").arg(bytesRead), QByteArray(buffer, bytesRead)});
} else if (libusb_error_code() != LIBUSB_ERROR_TIMEOUT) {
qCritical("Error reading from device: %s", libusb_strerror(libusb_error_code()));
break;
}
}
return nullptr;
}
```
要在主界面调用这个类并在适当的地方显示发送和接收的数据,可以这样使用:
```cpp
UsbDevice *device = new UsbDevice(DEVICE_INDEX);
connect(device, &UsbDevice::newDataAvailable, this, [device](const QByteArray &data) {
qDebug() << "Received Data: " << data.toBase64(); // 或者在界面上显示
});
// ...其他界面设置和按钮绑定
device->startReadThread(); // 开始监听数据
```
阅读全文