use a smart pointer with custom deleter inside HIDDevice, so instances can be copied
--- a/src/cadMousePro.cpp Sat Aug 17 18:51:35 2019 +0200
+++ b/src/cadMousePro.cpp Sun Aug 18 00:10:30 2019 +0200
@@ -3,6 +3,7 @@
#include <vector>
#include <hidapi/hidapi.h>
+#include <memory>
class HIDException {
private:
@@ -23,48 +24,44 @@
class HIDDevice {
private:
- hid_device* handle;
-
- HIDDevice(const HIDDevice& other) : handle(other.handle) {
- }
+ std::shared_ptr<hid_device> 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 = hid_open(vendorId, productId, serialNumber);
+ handle.reset(hid_open(vendorId, productId, serialNumber), hid_close);
if (handle == nullptr) throw HIDException(L"Unable to open HID device. Are you root? Is mouse present?");
}
virtual ~HIDDevice() {
- hid_close(handle);
hid_exit(); // TODO: move to HIDContext class?
}
const std::wstring getManufacturerName() const {
std::array<wchar_t, 200 > buffer;
- int error = hid_get_manufacturer_string(handle, buffer.data(), buffer.size());
+ 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<wchar_t, 200 > buffer;
- int error = hid_get_product_string(handle, buffer.data(), buffer.size());
+ 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<wchar_t, 200 > buffer;
- int error = hid_get_serial_number_string(handle, buffer.data(), buffer.size());
+ 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(std::vector<unsigned char> data) {
- int written = hid_send_feature_report(handle, data.data(), data.size());
+ int written = hid_send_feature_report(handle.get(), data.data(), data.size());
if (written < 0) throw HIDException(L"Unable to send feature report.");
}