aboutsummaryrefslogtreecommitdiff
path: root/src/voltronic/usb_device.cc
blob: ffb94d01956441831e235f4a6d4cd69e4033b781 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// SPDX-License-Identifier: BSD-3-Clause

#include <stdexcept>
#include <cstring>
#include <iostream>

#include "../logging.h"
#include "device.h"
#include "exceptions.h"
#include "hexdump/hexdump.h"

namespace voltronic {

USBDevice::USBDevice(u16 vendorId, u16 productId) {
    if (hid_init() != 0)
        throw DeviceError("hidapi initialization failure");

    device_ = hid_open(vendorId, productId, nullptr);
    if (!device_)
        throw DeviceError("failed to create hidapi device");
}

USBDevice::~USBDevice() {
    if (device_)
        hid_close(device_);

    hid_exit();
}

size_t USBDevice::read(u8* buf, size_t bufSize) {
    int timeout = !timeout_ ? -1 : static_cast<int32_t>(getTimeLeft());
    const int bytesRead = hid_read_timeout(device_, buf, GET_HID_REPORT_SIZE(bufSize), timeout);
    if (bytesRead == -1)
        throw DeviceError("hidapi_read_timeout() failed");
    return bytesRead;
}

size_t USBDevice::write(const u8* data, size_t dataSize) {
    const size_t writeSize = GET_HID_REPORT_SIZE(dataSize);

    if (verbose_) {
        myerr << "dataSize=" << dataSize << ", writeSize=" << writeSize;
        std::cerr << hexdump((void*)data, dataSize);
    }

    u8 writeBuffer[HID_REPORT_SIZE+1]{0};
    memcpy(&writeBuffer[1], data, writeSize);

    const int bytesWritten = hid_write(device_, writeBuffer, HID_REPORT_SIZE + 1);
    if (bytesWritten == -1)
        throw DeviceError("hidapi_write() failed");

    return GET_HID_REPORT_SIZE(bytesWritten);
}

u16 USBDevice::GET_HID_REPORT_SIZE(size_t size) {
    return size > HID_REPORT_SIZE ? HID_REPORT_SIZE : size;
}

}