原文:C#与USB HID间的通信

C#与USBHID接口的通讯相对于与串口间的通讯较为复杂,其中需要多次调用到Windows的一些API。其原理编者尚未全部理清,以下提供简单的USBHID通讯流程。(参考网友资料)

一、获取所有连接HID的设备信息。

1.通过一个空的GUID来获取HID的全局GUID。

Guid
HIDGuid = Guid.Empty;

///

/// The
HidD_GetHidGuid routine returns the device interface GUID for
HIDClass devices.

///

/// a
caller-allocated GUID buffer that the routine uses to return the
device interface GUID for HIDClass devices.

[DllImport("hid.dll")]

private static extern
void HidD_GetHidGuid(ref Guid
HidGuid);

2.通过获取到的HID全局GUID来获取包含所有HID接口信息集合的句柄。

IntPtr
HIDInfoSet= SetupDiGetClassDevs(ref HIDGuid,0,IntPtr.Zero,DIGCF.DIGCF_PRESENT|DIGCF.DIGCF_DEVICEINTERFACE);

///

/// The
SetupDiGetClassDevs function returns a handle to a device
information set that contains requested device information elements
for a local machine.

///

/// GUID
for a device setup class or a device interface
class.

/// A
pointer to a NULL-terminated string that supplies the name of a PnP
enumerator or a PnP device instance identifier.

/// A
handle of the top-level window to be used for a user
interface

/// A
variable  that specifies control options that
filter the device information elements that are added to the device
information set.

///

/// a
handle to a device information set

[DllImport("setupapi.dll", SetLastError = true)]

private static extern
IntPtr
SetupDiGetClassDevs(ref
Guid ClassGuid, uint Enumerator, IntPtr HwndParent, USBHIDEnum.DIGCF Flags);

相关枚举:

public enum DIGCF

{

DIGCF_DEFAULT = 0x00000001,

DIGCF_PRESENT = 0x00000002,

DIGCF_ALLCLASSES = 0x00000004,

DIGCF_PROFILE = 0x00000008,

DIGCF_DEVICEINTERFACE = 0x00000010

}

3.获取接口信息。

///

/// The
SetupDiEnumDeviceInterfaces function enumerates the device
interfaces that are contained in a device information
set.

///

/// A
pointer to a device information set that contains the device
interfaces for which to return information

/// A
pointer to an SP_DEVINFO_DATA structure that specifies a device
information element in DeviceInfoSet

/// a
GUID that specifies the device interface class for the requested
interface

/// A
zero-based index into the list of interfaces in the device
information set

/// a
caller-allocated buffer that contains a completed
SP_DEVICE_INTERFACE_DATA structure that identifies an interface
that meets the search parameters

///

[DllImport("setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]

private static extern
Boolean
SetupDiEnumDeviceInterfaces(IntPtr deviceInfoSet, IntPtr deviceInfoData, ref Guid
interfaceClassGuid, UInt32
memberIndex, ref DEVICE_INTERFACE_DATA
deviceInterfaceData);

接口信息定义为:

public struct DEVICE_INTERFACE_DATA

{

public int cbSize;

public Guid interfaceClassGuid;

public int flags;

public int reserved;

}

4.获取接口详细信息,在第一次主要是读取缓存信息

int
requiredSize =0;

///

/// The
SetupDiGetDeviceInterfaceDetail function returns details about a
device interface.

///

/// A
pointer to the device information set that contains the interface
for which to retrieve details

/// A
pointer to an SP_DEVICE_INTERFACE_DATA structure that specifies the
interface in DeviceInfoSet for which to retrieve
details

/// A
pointer to an SP_DEVICE_INTERFACE_DETAIL_DATA structure to receive
information about the specified interface

/// The
size of the DeviceInterfaceDetailData buffer

/// A
pointer to a variable that receives the required size of the
DeviceInterfaceDetailData buffer

/// A
pointer buffer to receive information about the device that
supports the requested interface

///

[DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)]

private static extern
bool
SetupDiGetDeviceInterfaceDetail(IntPtr deviceInfoSet, ref DEVICE_INTERFACE_DATA deviceInterfaceData,
IntPtr
deviceInterfaceDetailData, int
deviceInterfaceDetailDataSize, ref
int requiredSize, DEVINFO_DATA deviceInfoData);

接口信息定义:

[StructLayout(LayoutKind.Sequential)]

public class DEVINFO_DATA

{

public int cbSize = Marshal.SizeOf(typeof(DEVINFO_DATA));

public Guid classGuid = Guid.Empty;

public
int devInst = 0;

public int reserved = 0;

}

5.第二次获取详细信息,与第一相同。

若Windows
API SetupDiGetDeviceInterfaceDetail返回数值为true则添加设备信息

ListdeviceList=new List();

deviceList.Add(Marshal.PtrToStringAuto((IntPtr)((int)pDetail + 4)));

6.删除设备信息并释放内存。

///

/// The
SetupDiDestroyDeviceInfoList function deletes a device information
set and frees all associated memory.

///

/// A
handle to the device information set to delete.

/// returns TRUE if it is successful. Otherwise, it
returns FALSE

[DllImport("setupapi.dll", CharSet = CharSet.Auto, SetLastError = true)]

private static extern
Boolean
SetupDiDestroyDeviceInfoList(IntPtr HIDInfoSet);

到此便获取到所有的设备。

二、通过获取到的设备信息打开指定的HID设备。

1.创建,打开设备信息。

///

/// This
function creates, opens, or truncates a file, COM port, device,
service, or console.

///

/// a
null-terminated string that specifies the name of the
object

/// Type
of access to the object

/// Share
mode for object

/// Ignored; set to NULL

/// Action to take on files that exist, and which action
to take when files do not exist

/// File
attributes and flags for the file

/// Ignored

/// An
open handle to the specified file indicates
success

[DllImport("kernel32.dll", SetLastError = true)]

//private static extern IntPtr
CreateFile(string fileName, uint desiredAccess, uint shareMode,
uint securityAttributes, uint creationDisposition, uint
flagsAndAttributes, uint templateFile);

static extern IntPtr CreateFile(

string
FileName,               
//
文件名

uint
DesiredAccess,            
//
访问模式

uint
ShareMode,                
//
共享模式

uint
SecurityAttributes,       
//
安全属性

uint
CreationDisposition,      
//
如何创建

uint
FlagsAndAttributes,       
//
文件属性

int
hTemplateFile              
//
模板文件的句柄

);

其中文件名为相对应的设备名deviceList[index]

2.获取设备属性

///

/// The
HidD_GetAttributes routine returns the attributes of a specified
top-level collection.

///

/// Specifies an open handle to a top-level
collection

/// a
caller-allocated HIDD_ATTRIBUTES structure that returns the
attributes of the collection specified by
HidDeviceObject

///

[DllImport("hid.dll")]

private static extern
Boolean
HidD_GetAttributes(IntPtr
hidDevice, out HID_ATTRIBUTES attributes);

相关HID属性:

public struct
HID_ATTRIBUTES

{

public int Size;

public ushort VendorID;

public ushort ProductID;

public ushort VersionNumber;

}

3.Get PreparsedData

///

/// The
HidD_GetPreparsedData routine returns a top-level collection's
preparsed data.

///

/// Specifies an open handle to a top-level
collection.

/// Pointer to the address of a routine-allocated buffer
that contains a collection's preparsed data in a
_HIDP_PREPARSED_DATA structure.

/// HidD_GetPreparsedData returns TRUE if it succeeds;
otherwise, it returns FALSE.

[DllImport("hid.dll")]

private static extern
Boolean
HidD_GetPreparsedData(IntPtr
hidDeviceObject, out IntPtr PreparsedData);

4. GetCaps

[DllImport("hid.dll")]

private static extern
uint HidP_GetCaps(IntPtr PreparsedData, out HIDP_CAPS Capabilities);

5. FreePreparsedData

[DllImport("hid.dll")]

private static extern
Boolean
HidD_FreePreparsedData(IntPtr
PreparsedData);

6.获取长度:

outputReportLength = caps.OutputReportByteLength;

inputReportLength = caps.InputReportByteLength;

7.最终得到相应的设备

hidDevice = new FileStream(new SafeFileHandle(device, false), FileAccess.ReadWrite, inputReportLength,
true);

三、设备读取,写入

通过最终获取到的设备可对设备进行读取和写入。

BeginRead,Read,Write,BeginWrite等。

以上便能实现对想要的USBHID设备进行简单的操作。

简单串口例子:http://blog.sina.com.cn/s/blog_6267db160102v53m.html

示例代码下载地址:http://download.csdn.net/detail/zhezizhang/8155795

C#与USB HID间的通信的更多相关文章

  1. android usb Host模式下与usb Hid 设备的通信

    做android 与USB HID设备的通信有段时间了,总结一下遇到的问题和解决方法: 1,第一次遇到的问题:android 版本低不支持usb hid, 被要求做相关项目的时候,就从mUsbMana ...

  2. Windows与自定义USB HID设备通信说明.

    1 .   所使用的典型 Windows API CreateFile ReadFile WriteFile 以下函数是 DDK 的内容: HidD_SetFeature HidD_GetFeatur ...

  3. USB HID介绍【转】

    本文转载自:http://blog.csdn.net/leo_wonty/article/details/6721214 HID是一种USB通信协议,无需安装驱动就能进行交互,在学习HID之前,先来复 ...

  4. USB HID 协议入门

    转载请注明来源:cuixiaolei的技术博客 USB HID设备类的应用场合 USB HID类是USB设备的一个标准设备类,包括的设备非常多.HID类设备定义它属于人机交互操作的设备,用于控制计算机 ...

  5. USB HID介绍

    HID是一种USB通信协议,无需安装驱动就能进行交互,在学习HID之前,先来复习一下USB协议的相关内容. USB设备描述符-概述 当插入USB设备后,主机会向设备请求各种描述符来识别设备.那什么是设 ...

  6. PIC32MZ 通过USB在线升级 -- USB HID bootloader

    了解 bootloader 的实现, 请加QQ: 1273623966(验证填bootloader); 欢迎咨询或定制bootloader; 我的博客主页 www.cnblogs.com/geekyg ...

  7. USB HID设备报告描述符详解(转)

    转自:http://group.ednchina.com/93/198.aspx. 参考:USB HID usage table 概述:   报告在这里意思是数据传输(data transfer),而 ...

  8. 史上最全USB HID开发资料

    史上最全USB HID开发资料 史上最全USB HID开发资料,悉心整理一个月,亲自测试. 涉及STM32 C51 8051F例子都有源码,VC上位机例子以及源码,USB协议,HID协议,USB抓包工 ...

  9. STC8H开发(九): STC8H8K64U模拟USB HID外设

    目录 STC8H开发(一): 在Keil5中配置和使用FwLib_STC8封装库(图文详解) STC8H开发(二): 在Linux VSCode中配置和使用FwLib_STC8封装库(图文详解) ST ...

随机推荐

  1. JPA学习---第十一节:JPA中的多对多双向关联实体定义与注解设置及操作

    1.定义实体类,代码如下: (1).学生实体类: package learn.jpa.entity; import java.util.HashSet; import java.util.Set; i ...

  2. dd面试经历

     HR面:看了我的简历,说fe做的简历就是不一样哈哈好吧,然后随便问了点项目,又问了什么时候可以去实习,就没了.三面:基本数据结构.冒泡排序.数组去重.ie与主流浏览器事件绑定.垂直居中的css实现方 ...

  3. php调用微信发送自定义模版接口

     function sendWechatmodel($openid,$data,$go_url)//接受消息的用户openid,发送的消息,点击详情跳转的url        {           ...

  4. 【Construct Binary Tree from Preorder and Inorder Traversal】cpp

    题目: Given preorder and inorder traversal of a tree, construct the binary tree. Note:You may assume t ...

  5. 基于AutoCAD的空间数据共享平台雏形

    好久没有更新博客了,今天先透露一个新的产品——AutoMap.我自己对于这个产品的定位是“基于AutoCAD的空间数据共享平台”.用一句话来概括AutoMap的功能:为用户提供一个在AutoCAD下访 ...

  6. Angular 2 Quickstart

    写一个Angular 2的应用最基本的步骤概括为三步:写root组件,启动它(Boostrap),写index.html. 一些关于命名空间的基本知识 把所有代码放入一个立即调用函数中,通过传入一个空 ...

  7. 01.JSP基础语法

        本章主要讲解Java Web与JSP的入门内容,适合有JSP或Java Web基础的读者学习. 1.Web应用与web.xml文件 (1)Java Web应用程序的结构     Java We ...

  8. IDA*

    模拟退火 基本思路(Main Thoughts): IDA*是一种优秀的搜索法,在一般的实际问题中,它比普通的搜索更快. 通过迭代加深和估价函数剪枝来搜索. 通常处理没有层数上界或上界很多大的搜索. ...

  9. 【BZOJ】【3004】吊灯

    思路题 要将整棵树分成大小相等的连通块,那么首先我们可以肯定的是每块大小x一定是n的约数,且恰好分成$\frac{n}{x}$块,所以我有了这样一个思路:向下深搜,如果一个节点的size=x,就把这个 ...

  10. NYOJ-655 光棍的YY AC 分类: NYOJ 2013-12-29 19:24 224人阅读 评论(0) 收藏

    #include<stdio.h> #include<string.h> char str[210]; int max[210][52]={0}; int sum(int n, ...