-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathHidDevice.cs
657 lines (574 loc) · 25.5 KB
/
HidDevice.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ODIF;
namespace DualShock4
{
public class HidDevice : IDisposable
{
public enum ReadStatus
{
Success = 0,
WaitTimedOut = 1,
WaitFail = 2,
NoDataRead = 3,
ReadError = 4,
NotConnected = 5
}
private readonly string _description;
private readonly string _devicePath;
private readonly HidDeviceAttributes _deviceAttributes;
private readonly HidDeviceCapabilities _deviceCapabilities;
private bool _monitorDeviceEvents;
private string serial = null;
internal HidDevice(string devicePath, string description = null)
{
_devicePath = devicePath;
_description = description;
try
{
var hidHandle = OpenHandle(_devicePath, false);
_deviceAttributes = GetDeviceAttributes(hidHandle);
_deviceCapabilities = GetDeviceCapabilities(hidHandle);
hidHandle.Close();
}
catch (Exception exception)
{
System.Diagnostics.Trace.TraceError(exception.Message);
throw new Exception(string.Format("Error querying HID device '{0}'.", devicePath), exception);
}
}
public SafeFileHandle safeReadHandle { get; private set; }
public FileStream fileStream { get; private set; }
public bool IsOpen { get; private set; }
public bool IsExclusive { get; private set; }
public bool IsConnected { get { return HidDevices.IsConnected(_devicePath); } }
public string Description { get { return _description; } }
public HidDeviceCapabilities Capabilities { get { return _deviceCapabilities; } }
public HidDeviceAttributes Attributes { get { return _deviceAttributes; } }
public string DevicePath { get { return _devicePath; } }
public override string ToString()
{
return string.Format("VendorID={0}, ProductID={1}, Version={2}, DevicePath={3}",
_deviceAttributes.VendorHexId,
_deviceAttributes.ProductHexId,
_deviceAttributes.Version,
_devicePath);
}
public void OpenDevice(bool isExclusive)
{
if (IsOpen) return;
try
{
if (safeReadHandle == null || safeReadHandle.IsInvalid)
safeReadHandle = OpenHandle(_devicePath, isExclusive);
}
catch (Exception exception)
{
IsOpen = false;
throw new Exception("Error opening HID device.", exception);
}
IsOpen = !safeReadHandle.IsInvalid;
IsExclusive = isExclusive;
}
public void CloseDevice()
{
if (!IsOpen) return;
closeFileStreamIO();
IsOpen = false;
}
public void Dispose()
{
CancelIO();
CloseDevice();
}
public void CancelIO()
{
if (IsOpen)
NativeMethods.CancelIoEx(safeReadHandle.DangerousGetHandle(), IntPtr.Zero);
}
public bool ReadInputReport(byte[] data)
{
if (safeReadHandle == null)
safeReadHandle = OpenHandle(_devicePath, true);
return NativeMethods.HidD_GetInputReport(safeReadHandle, data, data.Length);
}
private static HidDeviceAttributes GetDeviceAttributes(SafeFileHandle hidHandle)
{
var deviceAttributes = default(NativeMethods.HIDD_ATTRIBUTES);
deviceAttributes.Size = Marshal.SizeOf(deviceAttributes);
NativeMethods.HidD_GetAttributes(hidHandle.DangerousGetHandle(), ref deviceAttributes);
return new HidDeviceAttributes(deviceAttributes);
}
private static HidDeviceCapabilities GetDeviceCapabilities(SafeFileHandle hidHandle)
{
var capabilities = default(NativeMethods.HIDP_CAPS);
var preparsedDataPointer = default(IntPtr);
if (NativeMethods.HidD_GetPreparsedData(hidHandle.DangerousGetHandle(), ref preparsedDataPointer))
{
NativeMethods.HidP_GetCaps(preparsedDataPointer, ref capabilities);
NativeMethods.HidD_FreePreparsedData(preparsedDataPointer);
}
return new HidDeviceCapabilities(capabilities);
}
private void closeFileStreamIO()
{
if (fileStream != null)
fileStream.Close();
fileStream = null;
System.Diagnostics.Trace.WriteLine("Close device filestream");
if (safeReadHandle != null && !safeReadHandle.IsInvalid)
{
safeReadHandle.Close();
System.Diagnostics.Trace.WriteLine("Close device handle");
}
safeReadHandle = null;
System.Diagnostics.Trace.WriteLine("IO closed");
}
public void flush_Queue()
{
if (safeReadHandle != null)
{
NativeMethods.HidD_FlushQueue(safeReadHandle);
}
}
private ReadStatus ReadWithFileStreamTask(byte[] inputBuffer)
{
try
{
if (fileStream.Read(inputBuffer, 0, inputBuffer.Length) > 0)
{
return ReadStatus.Success;
}
else
{
return ReadStatus.NoDataRead;
}
}
catch (Exception)
{
return ReadStatus.ReadError;
}
}
public ReadStatus ReadFile(byte[] inputBuffer)
{
if (safeReadHandle == null)
safeReadHandle = OpenHandle(_devicePath, true);
try
{
uint bytesRead;
if (NativeMethods.ReadFile(safeReadHandle.DangerousGetHandle(), inputBuffer, (uint)inputBuffer.Length, out bytesRead, IntPtr.Zero))
{
return ReadStatus.Success;
}
else
{
return ReadStatus.NoDataRead;
}
}
catch (Exception)
{
return ReadStatus.ReadError;
}
}
protected Byte m_IntIn = 0xFF;
protected Byte m_IntOut = 0xFF;
protected Byte m_BulkIn = 0xFF;
protected Byte m_BulkOut = 0xFF;
public virtual Boolean ReadIntPipe(Byte[] Buffer, Int32 Length, ref Int32 Transfered)
{
try { return NativeMethods.WinUsb_ReadPipe(safeReadHandle.DangerousGetHandle(), m_IntIn, Buffer, Length, ref Transfered, IntPtr.Zero); }
catch { return false; }
}
public ReadStatus ReadWithFileStream(byte[] inputBuffer, int timeout)
{
try
{
if (safeReadHandle == null)
safeReadHandle = OpenHandle(_devicePath, true);
if (fileStream == null && !safeReadHandle.IsInvalid)
fileStream = new FileStream(safeReadHandle, FileAccess.ReadWrite, inputBuffer.Length, false);
if (!safeReadHandle.IsInvalid && fileStream.CanRead)
{
Task<ReadStatus> readFileTask = new Task<ReadStatus>(() => ReadWithFileStreamTask(inputBuffer));
readFileTask.Start();
bool success = readFileTask.Wait(timeout);
if (success)
{
if (readFileTask.Result == ReadStatus.Success)
{
return ReadStatus.Success;
}
else if (readFileTask.Result == ReadStatus.ReadError)
{
return ReadStatus.ReadError;
}
else if (readFileTask.Result == ReadStatus.NoDataRead)
{
return ReadStatus.NoDataRead;
}
}
else
return ReadStatus.WaitTimedOut;
}
}
catch (Exception e)
{
if (e is AggregateException)
{
System.Diagnostics.Trace.TraceError(e.Message);
return ReadStatus.WaitFail;
}
else
{
return ReadStatus.ReadError;
}
}
return ReadStatus.ReadError;
}
public bool WriteOutputReportViaControl(byte[] outputBuffer)
{
try
{
//if (safeReadHandle == null)
//{
// safeReadHandle = OpenHandle(_devicePath, true);
//}
if (NativeMethods.HidD_SetOutputReport(safeReadHandle, outputBuffer, outputBuffer.Length))
return true;
else
return false;
}
catch
{
return false;
}
}
private bool WriteOutputReportViaInterruptTask(byte[] outputBuffer)
{
try
{
fileStream.Write(outputBuffer, 0, outputBuffer.Length);
return true;
}
catch (Exception e)
{
System.Diagnostics.Trace.TraceError(e.Message);
return false;
}
}
public bool WriteOutputReportViaInterrupt(byte[] outputBuffer, int timeout)
{
try
{
if (safeReadHandle == null)
{
safeReadHandle = OpenHandle(_devicePath, true);
}
if (fileStream == null && !safeReadHandle.IsInvalid)
{
fileStream = new FileStream(safeReadHandle, FileAccess.ReadWrite, outputBuffer.Length, false);
}
if (fileStream != null && fileStream.CanWrite && !safeReadHandle.IsInvalid)
{
fileStream.Write(outputBuffer, 0, outputBuffer.Length);
return true;
}
else
{
return false;
}
}
catch (Exception)
{
return false;
}
}
private SafeFileHandle OpenHandle(String devicePathName, Boolean isExclusive)
{
SafeFileHandle hidHandle;
try
{
if (isExclusive)
{
hidHandle = NativeMethods.CreateFile(devicePathName, NativeMethods.GENERIC_READ | NativeMethods.GENERIC_WRITE, 0, IntPtr.Zero, NativeMethods.OpenExisting, 0, 0);
}
else
{
hidHandle = NativeMethods.CreateFile(devicePathName, NativeMethods.GENERIC_READ | NativeMethods.GENERIC_WRITE, NativeMethods.FILE_SHARE_READ | NativeMethods.FILE_SHARE_WRITE, IntPtr.Zero, NativeMethods.OpenExisting, 0, 0);
}
}
catch (Exception)
{
throw;
}
return hidHandle;
}
public bool readFeatureData(byte[] inputBuffer)
{
return NativeMethods.HidD_GetFeature(safeReadHandle.DangerousGetHandle(), inputBuffer, inputBuffer.Length);
}
public string readSerial()
{
try
{
if (serial != null)
return serial;
if (Capabilities.InputReportByteLength == 64)
{
byte[] buffer = new byte[16];
buffer[0] = 18;
readFeatureData(buffer);
serial = String.Format("{0:X02}:{1:X02}:{2:X02}:{3:X02}:{4:X02}:{5:X02}", buffer[6], buffer[5], buffer[4], buffer[3], buffer[2], buffer[1]);
return serial;
}
else
{
byte[] buffer = new byte[126];
if (NativeMethods.HidD_GetSerialNumberString(safeReadHandle.DangerousGetHandle(), buffer, (uint)buffer.Length))
{
string MACAddr = System.Text.Encoding.Unicode.GetString(buffer).Replace("\0", string.Empty).ToUpper();
MACAddr = String.Format("{0}{1}:{2}{3}:{4}{5}:{6}{7}:{8}{9}:{10}{11}",
MACAddr[0], MACAddr[1], MACAddr[2], MACAddr[3], MACAddr[4],
MACAddr[5], MACAddr[6], MACAddr[7], MACAddr[8],
MACAddr[9], MACAddr[10], MACAddr[11]);
serial = MACAddr;
return serial;
}
else
{
System.Diagnostics.Trace.TraceWarning("The bluetooth adapter or bluetooth drivers being used may not be compatible with this software.");
string FakeMAC;
using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
{
FakeMAC = BitConverter.ToString(
md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(DevicePath))
).Replace("-", String.Empty);
}
FakeMAC = String.Format("99:{0}{1}:{2}{3}:{4}{5}:{6}{7}:{8}{9}",
FakeMAC[0], FakeMAC[1], FakeMAC[2], FakeMAC[3], FakeMAC[4],
FakeMAC[5], FakeMAC[6], FakeMAC[7], FakeMAC[8], FakeMAC[9]);
return FakeMAC;
}
}
}
catch (Exception err)
{
if (err.GetType() == typeof(IndexOutOfRangeException))
{
System.Diagnostics.Trace.TraceWarning("The bluetooth adapter or bluetooth drivers being used may not be compatible with this software.");
string FakeMAC;
using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
{
FakeMAC = BitConverter.ToString(
md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(DevicePath))
).Replace("-", String.Empty);
}
FakeMAC = String.Format("99:{0}{1}:{2}{3}:{4}{5}:{6}{7}:{8}{9}",
FakeMAC[0], FakeMAC[1], FakeMAC[2], FakeMAC[3], FakeMAC[4],
FakeMAC[5], FakeMAC[6], FakeMAC[7], FakeMAC[8], FakeMAC[9]);
return FakeMAC;
}
}
System.Diagnostics.Trace.TraceWarning("The bluetooth adapter being used may not be compatible with this software.");
return serial;
}
}
public class HidDevices
{
private static Guid _hidClassGuid = Guid.Empty;
public static bool IsConnected(string devicePath)
{
return EnumerateDevices().Any(x => x.Path == devicePath);
}
public static HidDevice GetDevice(string devicePath)
{
return Enumerate(devicePath).FirstOrDefault();
}
public static IEnumerable<HidDevice> Enumerate()
{
return EnumerateDevices().Select(x => new HidDevice(x.Path, x.Description));
}
public static IEnumerable<HidDevice> Enumerate(string devicePath)
{
return EnumerateDevices().Where(x => x.Path == devicePath).Select(x => new HidDevice(x.Path, x.Description));
}
public static IEnumerable<HidDevice> Enumerate(Guid deviceGUID)
{
return EnumerateDevices().Where(x => x.Path.Contains(deviceGUID.ToString())).Select(x => new HidDevice(x.Path, x.Description));
}
public static IEnumerable<HidDevice> Enumerate(int vendorId, params int[] productIds)
{
return EnumerateDevices().Select(x => new HidDevice(x.Path, x.Description)).Where(x => x.Attributes.VendorId == vendorId &&
productIds.Contains(x.Attributes.ProductId) );
}
public static IEnumerable<HidDevice> Enumerate(int vendorId)
{
return EnumerateDevices().Select(x => new HidDevice(x.Path, x.Description)).Where(x => x.Attributes.VendorId == vendorId);
}
private class DeviceInfo { public string Path { get; set; } public string Description { get; set; } }
private static IEnumerable<DeviceInfo> EnumerateDevices()
{
var devices = new List<DeviceInfo>();
var hidClass = HidClassGuid;
var deviceInfoSet = NativeMethods.SetupDiGetClassDevs(ref hidClass, null, 0, NativeMethods.DIGCF_PRESENT | NativeMethods.DIGCF_DEVICEINTERFACE);
if (deviceInfoSet.ToInt64() != NativeMethods.INVALID_HANDLE_VALUE)
{
var deviceInfoData = CreateDeviceInfoData();
var deviceIndex = 0;
while (NativeMethods.SetupDiEnumDeviceInfo(deviceInfoSet, deviceIndex, ref deviceInfoData))
{
deviceIndex += 1;
var deviceInterfaceData = new NativeMethods.SP_DEVICE_INTERFACE_DATA();
deviceInterfaceData.cbSize = Marshal.SizeOf(deviceInterfaceData);
var deviceInterfaceIndex = 0;
while (NativeMethods.SetupDiEnumDeviceInterfaces(deviceInfoSet, ref deviceInfoData, ref hidClass, deviceInterfaceIndex, ref deviceInterfaceData))
{
deviceInterfaceIndex++;
var devicePath = GetDevicePath(deviceInfoSet, deviceInterfaceData);
var description = GetBusReportedDeviceDescription(deviceInfoSet, ref deviceInfoData) ??
GetDeviceDescription(deviceInfoSet, ref deviceInfoData);
devices.Add(new DeviceInfo { Path = devicePath, Description = description });
}
}
NativeMethods.SetupDiDestroyDeviceInfoList(deviceInfoSet);
}
return devices;
}
private static NativeMethods.SP_DEVINFO_DATA CreateDeviceInfoData()
{
var deviceInfoData = new NativeMethods.SP_DEVINFO_DATA();
deviceInfoData.cbSize = Marshal.SizeOf(deviceInfoData);
deviceInfoData.DevInst = 0;
deviceInfoData.ClassGuid = Guid.Empty;
deviceInfoData.Reserved = IntPtr.Zero;
return deviceInfoData;
}
private static string GetDevicePath(IntPtr deviceInfoSet, NativeMethods.SP_DEVICE_INTERFACE_DATA deviceInterfaceData)
{
var bufferSize = 0;
var interfaceDetail = new NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA { Size = IntPtr.Size == 4 ? 4 + Marshal.SystemDefaultCharSize : 8 };
NativeMethods.SetupDiGetDeviceInterfaceDetailBuffer(deviceInfoSet, ref deviceInterfaceData, IntPtr.Zero, 0, ref bufferSize, IntPtr.Zero);
return NativeMethods.SetupDiGetDeviceInterfaceDetail(deviceInfoSet, ref deviceInterfaceData, ref interfaceDetail, bufferSize, ref bufferSize, IntPtr.Zero) ?
interfaceDetail.DevicePath : null;
}
private static Guid HidClassGuid
{
get
{
if (_hidClassGuid.Equals(Guid.Empty)) NativeMethods.HidD_GetHidGuid(ref _hidClassGuid);
return _hidClassGuid;
}
}
private static string GetDeviceDescription(IntPtr deviceInfoSet, ref NativeMethods.SP_DEVINFO_DATA devinfoData)
{
var descriptionBuffer = new byte[1024];
var requiredSize = 0;
var type = 0;
NativeMethods.SetupDiGetDeviceRegistryProperty(deviceInfoSet,
ref devinfoData,
NativeMethods.SPDRP_DEVICEDESC,
ref type,
descriptionBuffer,
descriptionBuffer.Length,
ref requiredSize);
return descriptionBuffer.ToUTF8String();
}
private static string GetBusReportedDeviceDescription(IntPtr deviceInfoSet, ref NativeMethods.SP_DEVINFO_DATA devinfoData)
{
var descriptionBuffer = new byte[1024];
if (Environment.OSVersion.Version.Major > 5)
{
ulong propertyType = 0;
var requiredSize = 0;
var _continue = NativeMethods.SetupDiGetDeviceProperty(deviceInfoSet,
ref devinfoData,
ref NativeMethods.DEVPKEY_Device_BusReportedDeviceDesc,
ref propertyType,
descriptionBuffer,
descriptionBuffer.Length,
ref requiredSize,
0);
if (_continue) return descriptionBuffer.ToUTF16String();
}
return null;
}
}
public class HidDeviceAttributes
{
internal HidDeviceAttributes(NativeMethods.HIDD_ATTRIBUTES attributes)
{
VendorId = attributes.VendorID;
ProductId = attributes.ProductID;
Version = attributes.VersionNumber;
VendorHexId = "0x" + attributes.VendorID.ToString("X4");
ProductHexId = "0x" + attributes.ProductID.ToString("X4");
}
public int VendorId { get; private set; }
public int ProductId { get; private set; }
public int Version { get; private set; }
public string VendorHexId { get; set; }
public string ProductHexId { get; set; }
}
public class HidDeviceCapabilities
{
internal HidDeviceCapabilities(NativeMethods.HIDP_CAPS capabilities)
{
Usage = capabilities.Usage;
UsagePage = capabilities.UsagePage;
InputReportByteLength = capabilities.InputReportByteLength;
OutputReportByteLength = capabilities.OutputReportByteLength;
FeatureReportByteLength = capabilities.FeatureReportByteLength;
Reserved = capabilities.Reserved;
NumberLinkCollectionNodes = capabilities.NumberLinkCollectionNodes;
NumberInputButtonCaps = capabilities.NumberInputButtonCaps;
NumberInputValueCaps = capabilities.NumberInputValueCaps;
NumberInputDataIndices = capabilities.NumberInputDataIndices;
NumberOutputButtonCaps = capabilities.NumberOutputButtonCaps;
NumberOutputValueCaps = capabilities.NumberOutputValueCaps;
NumberOutputDataIndices = capabilities.NumberOutputDataIndices;
NumberFeatureButtonCaps = capabilities.NumberFeatureButtonCaps;
NumberFeatureValueCaps = capabilities.NumberFeatureValueCaps;
NumberFeatureDataIndices = capabilities.NumberFeatureDataIndices;
}
public short Usage { get; private set; }
public short UsagePage { get; private set; }
public short InputReportByteLength { get; private set; }
public short OutputReportByteLength { get; private set; }
public short FeatureReportByteLength { get; private set; }
public short[] Reserved { get; private set; }
public short NumberLinkCollectionNodes { get; private set; }
public short NumberInputButtonCaps { get; private set; }
public short NumberInputValueCaps { get; private set; }
public short NumberInputDataIndices { get; private set; }
public short NumberOutputButtonCaps { get; private set; }
public short NumberOutputValueCaps { get; private set; }
public short NumberOutputDataIndices { get; private set; }
public short NumberFeatureButtonCaps { get; private set; }
public short NumberFeatureValueCaps { get; private set; }
public short NumberFeatureDataIndices { get; private set; }
}
static class Extensions
{
public static string ToUTF8String(this byte[] buffer)
{
var value = Encoding.UTF8.GetString(buffer);
return value.Remove(value.IndexOf((char)0));
}
public static string ToUTF16String(this byte[] buffer)
{
var value = Encoding.Unicode.GetString(buffer);
return value.Remove(value.IndexOf((char)0));
}
public static ConnectionTypes HidConnectionType(this HidDevice hidDevice)
{
return hidDevice.Capabilities.InputReportByteLength == 64 ? ConnectionTypes.USB : ConnectionTypes.BT;
}
}
}