Code
·
136 lines
·
2640 bytes
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
136using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace HidApiNet
{
class HidDevice : IDisposable
{
public HidDeviceInfo info;
private IntPtr hid = IntPtr.Zero;
public HidDevice(string path)
{
var res = Interop.hid_init();
if (res != 0)
return;
this.hid = Interop.hid_open_path(path);
}
public HidDevice(ushort vid, ushort pid)
{
var res = Interop.hid_init();
if (res != 0)
return;
//this.hid = HIDApi.hid_open(vid, pid, null);
var ptr = Interop.hid_enumerate(vid, pid);
if (ptr == IntPtr.Zero)
return;
this.info = (HidDeviceInfo)Marshal.PtrToStructure(ptr, typeof(HidDeviceInfo));
this.hid = Interop.hid_open_path(info.path);
}
public bool IsOpen
{
get
{
return this.hid != IntPtr.Zero;
}
}
private enum PropName
{
Unknown,
ProductString,
ManufacturerString,
SerialNumberString,
IndexedString
}
private string GetPropValue(PropName name, int index = 0)
{
int res;
string s = new string('*', 128);
switch (name)
{
case PropName.ProductString:
res = Interop.hid_get_product_string(this.hid, s, s.Length);
break;
case PropName.ManufacturerString:
res = Interop.hid_get_manufacturer_string(this.hid, s, s.Length);
break;
case PropName.SerialNumberString:
res = Interop.hid_get_serial_number_string(this.hid, s, s.Length);
break;
case PropName.IndexedString:
res = Interop.hid_get_indexed_string(this.hid, index, s, s.Length);
break;
default:
return null;
}
if (res != 0)
return null;
else
return s;
}
public string ProductString
{
get
{
return GetPropValue(PropName.ProductString);
}
}
public string ManufacturerString
{
get
{
return GetPropValue(PropName.ManufacturerString);
}
}
public string SerialNumberString
{
get
{
return GetPropValue(PropName.SerialNumberString);
}
}
public string IndexedString(int index)
{
return GetPropValue(PropName.IndexedString, index);
}
public int SetNonBlocking()
{
return Interop.hid_set_nonblocking(this.hid, 1);
}
public int Write(byte[] buffer)
{
return Interop.hid_write(this.hid, buffer, buffer.Length);
}
public int Read(byte[] buffer, int len)
{
return Interop.hid_read(this.hid, buffer, len);
}
public int ReadTimeOut(byte[] buffer, int t)
{
return Interop.hid_read_timeout(this.hid, buffer, buffer.Length, t);
}
public void Dispose()
{
if (this.hid != IntPtr.Zero)
Interop.hid_close(hid);
Interop.hid_exit();
}
}
}