USB HID通訊流程
創建C# USB hid通訊類
1. 讀取Hid設備全局id
[DllImport("hid.dll")]
private static extern void HidD_GetHidGuid(ref Guid HidGuid);
2. 取得一個包含所有HID接口信息集合的句柄
[DllImport("setupapi.dll", SetLastError = true)]
private static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid, uint Enumerator, IntPtr HwndParent, DIGCF Flags);
3.遍歷信息集合,得到每個設備的接口信息
[DllImport("setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern Boolean SetupDiEnumDeviceInterfaces(IntPtr deviceInfoSet, IntPtr deviceInfoData, ref Guid interfaceClassGuid, UInt32 memberIndex, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData);
4. 取得接口詳細信息:第一次讀取錯誤,但可以取得信息緩沖區的大小
SetupDiGetDeviceInterfaceDetail(hidInfoSet, ref interfaceInfo, IntPtr.Zero, buffsize, ref buffsize, null);
5. 取得接口詳細信息: 第二次可以讀取內容(內容包括VID,PID)
SetupDiGetDeviceInterfaceDetail(hidInfoSet, ref interfaceInfo, IntPtr.Zero, buffsize, ref buffsize, null);
6. 利用上一步讀取的設備路徑信息,使用CreateFile打開設備
[DllImport("kernel32.dll", SetLastError = true)]
protected static extern SafeFileHandle CreateFile(string strName, uint nAccess, uint nShareMode, uint lpSecurity, uint nCreationFlags, uint nAttributes, uint lpTemplate);
7. 根據文件句柄,讀取設備屬性信息
[DllImport("hid.dll")]
private static extern Boolean HidD_GetAttributes(SafeFileHandle hidDeviceObject, out HIDD_ATTRIBUTES attributes);
8. 根據屬性信息, 判斷VID和PID和下位機設備相同,得到此設備
根據得到的匹配設備, 得到準備數據
[DllImport("hid.dll")]
private static extern Boolean HidD_GetPreparsedData(SafeFileHandle hidDeviceObject, out IntPtr PreparsedData);
[DllImport("hid.dll")]
private static extern Boolean HidD_FreePreparsedData(IntPtr PreparsedData);
[DllImport("hid.dll")]
private static extern uint HidP_GetCaps(IntPtr PreparsedData, out HIDP_CAPS Capabilities);
9.創建文件流
hidDevice = new FileStream(device, FileAccess.ReadWrite, inputReportLength, true);
10. 根據文件流讀寫數據
從流中讀取字節塊並將該數據寫入給定緩沖區中。
public override int Read(byte[] array, int offset, int count);
使用從緩沖區讀取的數據將字節塊寫入該流。
public override void Write(byte[] array, int offset, int count);
發送內容的時候需要發送outputReportLength長度的內容,其中第一個字節是reportid=0x00,發送內容從第二個字節開始,這裏的獲取到下位機設置的outputReportLength為65
接收下位機內容時,下位機需要發inputReportLength長度的內容, 這裏的長度為64
USB HID通訊流程