-
Notifications
You must be signed in to change notification settings - Fork 8
/
HIDDeviceInput.cs
103 lines (88 loc) · 1.97 KB
/
HIDDeviceInput.cs
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Threading;
using HidSharp;
namespace Spark
{
public class HIDDeviceInput
{
public struct Device
{
public string name;
public int vendor;
public int product;
}
public class ConnexionState
{
public bool leftClick;
public bool rightClick;
public Vector3 position;
public Vector3 rotation;
public override string ToString()
{
return $"{leftClick}\t{rightClick}\t{position.X:N2}\t{position.Y:N2}\t{position.Z:N2}\t{rotation.X:N2}\t{rotation.Y:N2}\t{rotation.Z:N2}";
}
}
private List<Device> possibleDevices = new List<Device>();
private HidDevice device;
public Action<byte[]> OnChanged;
public bool Running { get; private set; }
public HIDDeviceInput(int vendor, int product)
{
possibleDevices.Add(new Device
{
vendor = vendor,
product = product,
});
}
public HIDDeviceInput(IEnumerable<Device> devices)
{
possibleDevices.AddRange(devices);
}
public void Start()
{
Running = true;
Thread devicePollingThread = new Thread(InputThread);
devicePollingThread.Start();
}
public void Stop()
{
Running = false;
}
private void InputThread()
{
IEnumerable<HidDevice> deviceList = DeviceList.Local.GetHidDevices();
foreach (HidDevice d in deviceList)
{
Logger.Error($"Device: {d}");
foreach (Device m in possibleDevices)
{
if (d.VendorID == m.vendor && d.ProductID == m.product)
{
Logger.Error($"Found device: {m}\t{d}");
device = d;
}
}
}
if (device == null)
{
Logger.Error($"Didn't find device");
return;
}
if (!device.TryOpen(out HidStream hidStream))
{
Logger.Error($"Couldn't open device stream.");
return;
}
hidStream.ReadTimeout = Timeout.Infinite;
using HidStream stream = hidStream;
while (Running)
{
byte[] bytes = hidStream.Read();
OnChanged?.Invoke(bytes);
}
}
}
}