diff -r 405aa9de65d2 -r 6799cec5c2f8 src/HID.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/HID.h Sun Aug 18 23:30:01 2019 +0200 @@ -0,0 +1,74 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include + +using Packet = std::vector; +static_assert(sizeof (uint8_t) == sizeof (unsigned char)); // unsigned char is used in the HID API library + +class HIDException { +private: + std::wstring message; +public: + + HIDException(std::wstring message) : message(message) { + } + + virtual ~HIDException() { + } + + const std::wstring getMessage() const { + return message; + } + +}; + +class HIDDevice { +private: + std::shared_ptr handle; + +public: + + HIDDevice(unsigned short vendorId, unsigned short productId, const wchar_t *serialNumber) { + int initError = hid_init(); // TODO: move to HIDContext class? + if (initError) throw HIDException(L"Unable to init HID API."); + handle.reset(hid_open(vendorId, productId, serialNumber), hid_close); + if (handle == nullptr) throw HIDException(L"Unable to open HID device. Are you root? Is the device present?"); + } + + virtual ~HIDDevice() { + hid_exit(); // TODO: move to HIDContext class? + } + + const std::wstring getManufacturerName() const { + std::array buffer; + int error = hid_get_manufacturer_string(handle.get(), buffer.data(), buffer.size()); + if (error) throw HIDException(L"Unable to get manufacturer name."); + return buffer.data(); + } + + const std::wstring getProductName() const { + std::array buffer; + int error = hid_get_product_string(handle.get(), buffer.data(), buffer.size()); + if (error) throw HIDException(L"Unable to get product name."); + return buffer.data(); + } + + const std::wstring getSerialNumber() const { + std::array buffer; + int error = hid_get_serial_number_string(handle.get(), buffer.data(), buffer.size()); + if (error) throw HIDException(L"Unable to get serial number."); + return buffer.data(); + } + + void sendFeatureReport(Packet data) { + int written = hid_send_feature_report(handle.get(), data.data(), data.size()); + if (written < 0) throw HIDException(L"Unable to send feature report."); + } + +};