写出完整libusb 异步传输例程,使用多线程读写操作,使用c++实现,封装成一个类
时间: 2024-10-09 17:05:40 浏览: 60
在C++中,我们可以创建一个类来封装libusb的异步传输功能,采用多线程读写操作。以下是一个基本的示例,展示了一个名为`UsbAsyncTransfer`的类,包含了设备打开、关闭以及异步读写的方法:
```cpp
#include <iostream>
#include <vector>
#include <thread>
#include "libusb.h"
class UsbAsyncTransfer {
private:
libusb_context* context;
libusb_device* device;
uint8_t in_endpoint;
uint8_t out_endpoint;
public:
UsbAsyncTransfer(uint16_t vendor_id, uint16_t product_id)
: context(libusb_init(nullptr)), device(nullptr), in_endpoint(...), out_endpoint(...) {
if ((device = libusb_open_device_with_vid_pid(context, vendor_id, product_id)) == nullptr) {
std::cerr << "Failed to open device: " << libusb_strerror(libusb_get_errno()) << std::endl;
return;
}
}
~UsbAsyncTransfer() {
if (device) {
libusb_close(device);
libusb_exit(context);
}
}
void startRead(std::vector<uint8_t>& buffer, std::function<void(const std::vector<uint8_t>& received)> callback) {
std::unique_ptr<libusb_transfer, decltype(&libusb_free_transfer)> transfer(new libusb_transfer());
std::thread readerThread([this, transfer, buffer, callback]() {
libusb_fill_bulk_transfer(
transfer.get(), device, in_endpoint, buffer.data(), buffer.size(),
[](libusb_transfer* trans, unsigned char* user_data) {
auto buffer = static_cast<std::vector<uint8_t>*>(user_data);
callback(*buffer);
},
&buffer, LIBUSB_TRANSFER_TIMEOUT_USEC(1000)
);
int result = libusb_submit_transfer(transfer.get());
if (result < 0) {
std::cerr << "Error submitting read transfer: " << libusb_strerror(result) << std::endl;
} else {
std::cout << "Reading started." << std::endl;
}
});
readerThread.detach();
}
void startWrite(const std::vector<uint8_t>& data, const std::function<void(bool success)> callback) {
std::unique_ptr<libusb_transfer, decltype(&libusb_free_transfer)> transfer(new libusb_transfer());
libusb_fill_bulk_transfer(
transfer.get(), device, out_endpoint, data.data(), data.size(),
nullptr, nullptr, LIBUSB_TRANSFER_TIMEOUT_USEC(1000)
);
int result = libusb_submit_transfer(transfer.get());
if (result < 0) {
std::cerr << "Error submitting write transfer: " << libusb_strerror(result) << std::endl;
callback(false);
} else {
std::cout << "Writing started." << std::endl;
callback(true);
}
}
};
阅读全文