#include "libusbwrapper.h" #include #include UsbDevice::UsbDevice(libusb_device *device) { int res; this->dev = device; res = libusb_get_device_descriptor(device, &this->devdesc); this->device_handle = nullptr; if (res == 0) { this->vendor_id = devdesc.idVendor; this->product_id = devdesc.idProduct; } } UsbDevice::UsbDevice(UsbDevice &&d) { vendor_id = std::move(d.vendor_id); product_id = std::move(d.product_id); dev = d.dev; devdesc = d.devdesc; device_handle = std::move(d.device_handle); } UsbDevice::~UsbDevice() { /* Nothing to do here. Our device handle will be automatically closed once the shared pointer is released */ } std::vector UsbDevice::find_devices(uint16_t vendor_id, uint16_t product_id) { auto ret_vector = std::vector(); libusb_device **devlist; int res = libusb_get_device_list(NULL, &devlist); if (res > 0) { for (int idx = 0; idx < res; idx++) { auto d = UsbDevice(devlist[idx]); if (d.get_product_id() == product_id && d.get_vendor_id() == vendor_id) ret_vector.push_back(std::move(d)); } } return ret_vector; } bool UsbDevice::opened() { return !!(this->device_handle != nullptr); } int UsbDevice::open() { int ret; libusb_device_handle *handle; if (this->dev) { ret = libusb_open(this->dev, &handle); } else { handle = libusb_open_device_with_vid_pid(NULL, this->vendor_id, this->product_id); if (!handle) ret = -1; else ret = 0; } device_handle = std::make_shared(handle); return ret; } uint16_t UsbDevice::get_vendor_id() { return this->vendor_id; } uint16_t UsbDevice::get_product_id() { return this->product_id; } int UsbDevice::control_transfer(uint8_t request_type, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, unsigned char *data, uint16_t wLength, unsigned int timeout) { if (!opened()) return -1000; return libusb_control_transfer(this->device_handle->m_handle, request_type, bRequest, wValue, wIndex, data, wLength, timeout); } const std::string &UsbDevice::get_serial_number() { char buffer[256] = {0}; if (!opened()) return serial; if (devdesc.iSerialNumber == 0) return serial; if (serial.length() > 0) { return serial; } int res = libusb_get_string_descriptor_ascii(device_handle->m_handle, devdesc.iSerialNumber, (unsigned char *)buffer, 255); if (res > 0) { serial = std::string(buffer); return serial; } else { return serial; } } void LibUsbInit() { libusb_init(NULL); } void LibUsbDeInit() { libusb_exit(NULL); } UsbDeviceHandle::UsbDeviceHandle(libusb_device_handle *handle) { m_handle = handle; } UsbDeviceHandle::~UsbDeviceHandle() { if (m_handle) libusb_close(m_handle); m_handle = NULL; }