码迷,mamicode.com
首页 > 其他好文 > 详细

USB HID通讯流程

时间:2017-11-06 13:49:44      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:tail   import   create   文件   override   pap   creation   error   output   

创建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通讯流程

标签:tail   import   create   文件   override   pap   creation   error   output   

原文地址:http://www.cnblogs.com/hdsong/p/7792694.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!