Files
itgmania212121/src/archutils/Common/HidDevice.cpp
T

109 lines
1.7 KiB
C++
Raw Normal View History

2025-03-18 17:40:39 +01:00
#include "global.h"
#include "HidDevice.h"
#include "RageLog.h"
HidDevice::HidDevice(int vid, int pid, int interfaceNum) : path{ GetPath(vid, pid, interfaceNum) }
2025-03-18 17:40:39 +01:00
{
bool result = TryConnect();
if (!result) {
LOG->Warn("HID device with VID/PID %x/%x not found.", vid, pid);
hid_exit();
return;
}
else
{
path = path;
2025-03-18 17:40:39 +01:00
hid_set_nonblocking(handle, 1);
}
}
HidDevice::~HidDevice()
{
if (handle != nullptr)
2025-03-18 17:40:39 +01:00
hid_close(handle);
hid_exit();
}
void HidDevice::Close()
{
hid_close(handle);
handle = nullptr;
}
bool HidDevice::Open()
{
handle = hid_open_path(path);
return handle != nullptr;
}
2025-03-18 17:40:39 +01:00
bool HidDevice::TryConnect()
{
if (path == nullptr)
return false;
2025-03-18 17:40:39 +01:00
return Open();
2025-03-18 17:40:39 +01:00
}
bool HidDevice::IsConnected() {
if (handle == nullptr)
2025-03-18 17:40:39 +01:00
return TryConnect();
return handle != nullptr;
}
char* HidDevice::GetPath(int vid, int pid, int interfaceNumber)
{
struct hid_device_info* devs, * cur_dev;
devs = hid_enumerate(vid, pid);
cur_dev = devs;
if (devs && cur_dev)
{
// Look for the desired devices by iterating connected ones
while (cur_dev)
{
if (cur_dev->vendor_id == vid &&
cur_dev->product_id == pid)
{
if (interfaceNumber == -1)
{
return cur_dev->path;
}
else
{
if(cur_dev->interface_number == interfaceNumber)
return cur_dev->path;
}
}
cur_dev = cur_dev->next;
}
}
return nullptr;
2025-03-18 17:40:39 +01:00
}
void HidDevice::Read(unsigned char* data, size_t length)
{
if (!IsConnected())
return;
hid_read(handle, data, length);
}
void HidDevice::Write(const unsigned char* data, size_t length)
{
if (!IsConnected())
return;
int result = hid_write(handle, data, length);
if (result != length)
Close();
2025-03-18 17:40:39 +01:00
}