Windows上位机使用HidSharp进行HID通信
HID通信
HID上位机通信库有很多,比如hidsharp,libusbhidnet,cyusb,usbclasslibrary.... 。这里使用hidsharp这个库,此库功能非常强大和稳定
HID 发送接收测试代码
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
public void connect()
{
MyDevice = List.GetHidDevices(0x0480, 0x5850).FirstOrDefault();
if (MyDevice != null && MyDevice.TryOpen(out Stream))
{
uIData.DevSta = "| 设备:已连接";
info();
//Buffer = new byte[65]; // 65
Stream.ReadTimeout = Timeout.Infinite;
//Result = Stream.BeginRead(Buffer, 0, 65, new AsyncCallback(BytesReady), null); // 64
rec = new HidDeviceInputReceiver(MyDevice.GetReportDescriptor());
rec.Received += Rec_Received;
rec.Start(Stream);
//Stream.ReadAsync(Buffer, 0, 64);
//连接时 获取仪器型号数据
string cmd = "*IDN?\r\n";
send_data(CMD_TYPE.GET_INFO_INDS, Encoding.Default.GetBytes(cmd), (byte)cmd.Length);
}
else
{
uIData.DevSta = "| 设备:未连接";
uIData.Manufacturer = "";
uIData.Production = "";
uIData.SerialNum = "";
uIData.Device = "";
}
}
//通信协议
//第一字节表示长度
//第二字节表示类型
//后边表示数据 文本表示
public enum CMD_TYPE
{
GET_INFO_INDS = 0,
GET_REL_VALUE,
GET_MES_VALUE,
SET_AC_VOLTAGE,
SET_DC_VOLTAGE,
SET_RELAY_VALUE,
SET_PARAM_VALUE,
SET_START_REC,
SET_STOP_REC,
};
public void send_data(CMD_TYPE type, byte[] data, byte len)
{
try
{
byte[] buf = new byte[MyDevice.GetMaxOutputReportLength()];
buf[0] = 0; //第一个字节存放Report ID 下位机会自动去掉ID
buf[1] = len; //后边数据长度
buf[2] = (byte)type; //命令类型
Array.Copy(data, 0, buf, 3, len);
Stream.Write(buf);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void List_Changed(object sender, DeviceListChangedEventArgs e)
{
connect();
}
public void info()
{
uIData.Manufacturer = "| " + MyDevice.GetManufacturer();
uIData.Production = "| " + MyDevice.GetProductName();
uIData.SerialNum = "| " + MyDevice.GetSerialNumber();
Console.WriteLine(MyDevice.DevicePath);
//Console.WriteLine(string.Join(",", MyDevice.GetDevicePathHierarchy())); // TODO
Console.WriteLine(MyDevice);
try
{
Console.WriteLine(string.Format("Max Lengths: Input {0}, Output {1}, Feature {2}",
MyDevice.GetMaxInputReportLength(),
MyDevice.GetMaxOutputReportLength(),
MyDevice.GetMaxFeatureReportLength()));
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine(e);
Console.WriteLine();
return;
}
try
{
Console.WriteLine("Serial Ports: {0}", string.Join(",", MyDevice.GetSerialPorts()));
}
catch
{
Console.WriteLine("Serial Ports: Unknown on this platform.");
}
try
{
var rawReportDescriptor = MyDevice.GetRawReportDescriptor();
Console.WriteLine("Report Descriptor:");
Console.WriteLine(" {0} ({1} bytes)", string.Join(" ", rawReportDescriptor.Select(d => d.ToString("X2"))), rawReportDescriptor.Length);
int indent = 0;
foreach (var element in EncodedItem.DecodeItems(rawReportDescriptor, 0, rawReportDescriptor.Length))
{
if (element.ItemType == ItemType.Main && element.TagForMain == MainItemTag.EndCollection) { indent -= 2; }
Console.WriteLine(" {0}{1}", new string(' ', indent), element);
if (element.ItemType == ItemType.Main && element.TagForMain == MainItemTag.Collection) { indent += 2; }
}
var reportDescriptor = MyDevice.GetReportDescriptor();
foreach (var deviceItem in reportDescriptor.DeviceItems)
{
foreach (var usage in deviceItem.Usages.GetAllValues())
{
Console.WriteLine(string.Format("Usage: {0:X4} {1}", usage, (Usage)usage));
}
foreach (var report in deviceItem.Reports)
{
Console.WriteLine(string.Format("{0}: ReportID={1}, Length={2}, Items={3}",
report.ReportType, report.ReportID, report.Length, report.DataItems.Count));
foreach (var dataItem in report.DataItems)
{
Console.WriteLine(string.Format(" {0} Elements x {1} Bits, Units: {2}, Expected Usage Type: {3}, Flags: {4}, Usages: {5}",
dataItem.ElementCount, dataItem.ElementBits, dataItem.Unit.System, dataItem.ExpectedUsageType, dataItem.Flags,
string.Join(", ", dataItem.Usages.GetAllValues().Select(usage => usage.ToString("X4") + " " + ((Usage)usage).ToString()))));
}
}
}
}
catch (Exception)
{ }
}
int num = 0;
private void Rec_Received(object sender, EventArgs e)
{
try
{
byte[] buf = new byte[MyDevice.GetMaxInputReportLength()];
Report report;
rec.TryRead(buf, 0, out report);
foreach (byte b in buf)
{
Console.Write("{0:X2} ", b);
}
Console.WriteLine("\r\n");
switch ((CMD_TYPE)buf[2])
{
case CMD_TYPE.GET_INFO_INDS: //仪器数据
byte[] data = new byte[buf[1]];
Array.Copy(buf, 3, data, 0, buf[1]);
string value = Encoding.Default.GetString(data);
Console.WriteLine(value);
uIData.Device = "| " + value;
break;
case CMD_TYPE.GET_REL_VALUE:
for (int i = 0; i < buf[1] / 4; i++)
{
byte[] b = new byte[4]; //double是8字节
Array.Copy(buf, 3 + i * 4, b, 0, 4);
//Array.Reverse(voltage);//转为大端数据 经过测试不需要转换
//foreach (byte b in b)
//{
// Console.Write("{0:X2} ", b);
//}
//Console.WriteLine("\r\n");
float v = BitConverter.ToSingle(b, 0);
double d = Math.Round(v, 3);
uIData.Voltage = d.ToString();
Console.WriteLine("REL --->:" + d);//保留3位小数
}
break;
case CMD_TYPE.GET_MES_VALUE:
double[] voltage = new double[uIData.IsBridgeOut ? 4 : 8];
for (int i = 0; i < buf[1] / 4; i++)
{
byte[] b = new byte[4]; //double是8字节
Array.Copy(buf, 3 + i * 4, b, 0, 4);
//Array.Reverse(voltage);//转为大端数据 经过测试不需要转换
//foreach (byte b in b)
//{
// Console.Write("{0:X2} ", b);
//}
//Console.WriteLine("\r\n");
float v = BitConverter.ToSingle(b, 0);
double d = Math.Round(v, 3);
voltage[i] = d;
Console.WriteLine("MES--->:" + d);//保留3位小数
}
num++;
if (num >= uIData.SampleNum)
{
//停止采集
StopRec_Click(null, new RoutedEventArgs());
//数据插入数据库中
//导出数据
Export_Excel(uIData.AmpName1, uIData.Barcode1, uIData.YearWeek1, dv1);
Export_Excel(uIData.AmpName2, uIData.Barcode2, uIData.YearWeek2, dv2);
uIData.Barcode1 = "";
uIData.Barcode2 = "";
Barcode1.Focus();
StartRec.IsEnabled = false;
StopRec.IsEnabled = false;
}
break;
}
}
catch (Exception ee)
{
Console.WriteLine(ee.Message);
}
}
//异步读取
private void BytesReady(IAsyncResult result)
{
try
{
string s = ($"Bytes Read = {Stream.EndRead(result)} ");
Console.WriteLine(s);
foreach (byte b in Buffer)
{
Console.WriteLine(b.ToString("X2"));
}
result = Stream.BeginRead(Buffer, 0, 65, new AsyncCallback(BytesReady), null); // 64
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
HID资料
Infineon-AN57294_USB_101_An_Introduction_to_Universal_Serial_Bus_2.0-ApplicationNotes-v09_00-CN
HID调试工具



评论