libusbdevice.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #include "libusbdevice.h"
  2. #include <libusb-1.0/libusb.h>
  3. #include <iostream>
  4. namespace noolitelib
  5. {
  6. constexpr auto DefaultTimeout = 1000;
  7. LibUsbDevice::LibUsbDevice()
  8. {
  9. auto status = libusb_init(&m_context);
  10. if (status) {
  11. std::cerr << "Error initializing context: " << libusb_strerror(status) << " [" << status << "]" << std::endl;
  12. }
  13. }
  14. LibUsbDevice::~LibUsbDevice()
  15. {
  16. if (m_context) {
  17. libusb_exit(m_context);
  18. }
  19. }
  20. void LibUsbDevice::openDevice(uint16_t vendorId, uint16_t productId)
  21. {
  22. m_device = libusb_open_device_with_vid_pid(m_context, vendorId, productId);
  23. }
  24. void LibUsbDevice::close()
  25. {
  26. if (m_device) {
  27. libusb_close(m_device);
  28. }
  29. }
  30. bool LibUsbDevice::sendDataToDevice(const Data &data)
  31. {
  32. if (!m_device) {
  33. std::cerr << "Device not opened" << std::endl;
  34. return false;
  35. }
  36. auto requestType = LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE;
  37. auto request = LIBUSB_REQUEST_SET_CONFIGURATION;
  38. unsigned char package[data.size()];
  39. std::copy(data.begin(), data.end(), package);
  40. auto status = libusb_control_transfer(m_device, requestType, request, 0, 0, package, data.size(), DefaultTimeout);
  41. if (status) {
  42. std::cerr << "Sending data error: " << libusb_strerror(status) << " [" << status << "]" << std::endl;
  43. return false;
  44. }
  45. return true;
  46. }
  47. }