67 lines
1.5 KiB
C++
67 lines
1.5 KiB
C++
#include "libusbdevice.h"
|
|
|
|
#include <libusb-1.0/libusb.h>
|
|
#include <iostream>
|
|
|
|
namespace noolitelib
|
|
{
|
|
|
|
constexpr auto DefaultTimeout = 1000;
|
|
|
|
LibUsbDevice::LibUsbDevice()
|
|
{
|
|
auto status = libusb_init(&m_context);
|
|
if (status < LIBUSB_SUCCESS) {
|
|
std::cerr << "Error initializing context: " << libusb_strerror(status) << " [" << status << "]" << std::endl;
|
|
}
|
|
}
|
|
|
|
LibUsbDevice::~LibUsbDevice()
|
|
{
|
|
if (m_context) {
|
|
libusb_exit(m_context);
|
|
}
|
|
}
|
|
|
|
void LibUsbDevice::openDevice(uint16_t vendorId, uint16_t productId)
|
|
{
|
|
if (!m_context) {
|
|
std::cerr << "Context not initialized! Unable to open device";
|
|
return;
|
|
}
|
|
|
|
m_device = libusb_open_device_with_vid_pid(m_context, vendorId, productId);
|
|
}
|
|
|
|
void LibUsbDevice::close()
|
|
{
|
|
if (m_device) {
|
|
libusb_close(m_device);
|
|
}
|
|
}
|
|
|
|
bool LibUsbDevice::sendDataToDevice(const Data &data)
|
|
{
|
|
if (!m_device) {
|
|
std::cerr << "Device not opened" << std::endl;
|
|
return false;
|
|
}
|
|
|
|
auto requestType = LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE;
|
|
auto request = LIBUSB_REQUEST_SET_CONFIGURATION;
|
|
|
|
unsigned char package[data.size()];
|
|
std::copy(data.begin(), data.end(), package);
|
|
|
|
auto status = libusb_control_transfer(m_device, requestType, request, 0, 0, package, data.size(), DefaultTimeout);
|
|
|
|
if (status < LIBUSB_SUCCESS) {
|
|
std::cerr << "Sending data error: " << libusb_strerror(status) << " [" << status << "]" << std::endl;
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
}
|