HidDevice.cs
author StephaneLenclud
Sun, 15 Feb 2015 18:15:41 +0100
changeset 60 687cace560d2
parent 58 7ef0f9dc229c
child 61 60bfe5083721
permissions -rw-r--r--
Adding most basic raw device list.
     1 using System;
     2 using System.Windows.Forms;
     3 using System.Runtime.InteropServices;
     4 using System.Diagnostics;
     5 using System.Text;
     6 using Microsoft.Win32.SafeHandles;
     7 using Win32;
     8 
     9 namespace Hid
    10 {
    11     /// <summary>
    12     /// Represent a HID device.
    13     /// Rename to RawInputDevice?
    14     /// </summary>
    15     public class HidDevice: IDisposable
    16     {
    17         public string Name { get; private set; }
    18         public string Manufacturer { get; private set; }
    19         public string Product { get; private set; }
    20         public ushort VendorId { get; private set; }
    21         public ushort ProductId { get; private set; }
    22         public ushort Version { get; private set; }
    23         //Pre-parsed HID descriptor
    24         public IntPtr PreParsedData {get; private set;}
    25         //Info
    26         public RID_DEVICE_INFO Info { get {return iInfo;} }
    27         private RID_DEVICE_INFO iInfo;
    28         //Capabilities
    29         public HIDP_CAPS Capabilities { get { return iCapabilities; } }
    30         private HIDP_CAPS iCapabilities;
    31         //Input Button Capabilities
    32         public HIDP_BUTTON_CAPS[] InputButtonCapabilities { get { return iInputButtonCapabilities; } }
    33         private HIDP_BUTTON_CAPS[] iInputButtonCapabilities;
    34         //Input Value Capabilities
    35         public HIDP_VALUE_CAPS[] InputValueCapabilities { get { return iInputValueCapabilities; } }
    36         private HIDP_VALUE_CAPS[] iInputValueCapabilities;
    37 
    38         
    39         
    40 
    41         /// <summary>
    42         /// Class constructor will fetch this object properties from HID sub system.
    43         /// </summary>
    44         /// <param name="hRawInputDevice">Device Handle as provided by RAWINPUTHEADER.hDevice, typically accessed as rawinput.header.hDevice</param>
    45         public HidDevice(IntPtr hRawInputDevice)
    46         {
    47             //Try construct and rollback if needed
    48             try
    49             {
    50                 Construct(hRawInputDevice);
    51             }
    52             catch (System.Exception ex)
    53             {
    54                 //Just rollback and propagate
    55                 Dispose();
    56                 throw ex;
    57             }
    58         }
    59 
    60 
    61         /// <summary>
    62         /// Make sure dispose is called even if the user forgot about it.
    63         /// </summary>
    64         ~HidDevice()
    65         {
    66             Dispose();
    67         }
    68 
    69         /// <summary>
    70         /// Private constructor.
    71         /// </summary>
    72         /// <param name="hRawInputDevice"></param>
    73         private void Construct(IntPtr hRawInputDevice)
    74         {
    75             PreParsedData = IntPtr.Zero;
    76             iInputButtonCapabilities = null;
    77             iInputValueCapabilities = null;
    78 
    79             //Fetch various information defining the given HID device
    80             Name = Win32.RawInput.GetDeviceName(hRawInputDevice);
    81 
    82             //Get our HID descriptor pre-parsed data
    83             PreParsedData = Win32.RawInput.GetPreParsedData(hRawInputDevice);
    84             if (PreParsedData == IntPtr.Zero)
    85             {
    86                 throw new Exception("HidDevice: GetPreParsedData failed: " + Marshal.GetLastWin32Error().ToString());
    87             }
    88 
    89             //Fetch device info
    90             iInfo = new RID_DEVICE_INFO();
    91             if (!Win32.RawInput.GetDeviceInfo(hRawInputDevice, ref iInfo))
    92             {
    93                 throw new Exception("HidDevice: GetDeviceInfo failed: " + Marshal.GetLastWin32Error().ToString());
    94             }
    95 
    96             //Open our device from the device name/path
    97             SafeFileHandle handle = Win32.Function.CreateFile(Name,
    98                 Win32.FileAccess.NONE,
    99                 Win32.FileShare.FILE_SHARE_READ | Win32.FileShare.FILE_SHARE_WRITE,
   100                 IntPtr.Zero,
   101                 Win32.CreationDisposition.OPEN_EXISTING,
   102                 Win32.FileFlagsAttributes.FILE_FLAG_OVERLAPPED,
   103                 IntPtr.Zero
   104                 );
   105 
   106             //Check if CreateFile worked
   107             if (handle.IsInvalid)
   108             {
   109                 throw new Exception("HidDevice: CreateFile failed: " + Marshal.GetLastWin32Error().ToString());
   110             }
   111 
   112             //Get manufacturer string
   113             StringBuilder manufacturerString = new StringBuilder(256);
   114             if (Win32.Function.HidD_GetManufacturerString(handle, manufacturerString, manufacturerString.Capacity))
   115             {
   116                 Manufacturer = manufacturerString.ToString();
   117             }
   118 
   119             //Get product string
   120             StringBuilder productString = new StringBuilder(256);
   121             if (Win32.Function.HidD_GetProductString(handle, productString, productString.Capacity))
   122             {
   123                 Product = productString.ToString();
   124             }
   125 
   126             //Get attributes
   127             Win32.HIDD_ATTRIBUTES attributes = new Win32.HIDD_ATTRIBUTES();
   128             if (Win32.Function.HidD_GetAttributes(handle, ref attributes))
   129             {
   130                 VendorId = attributes.VendorID;
   131                 ProductId = attributes.ProductID;
   132                 Version = attributes.VersionNumber;
   133             }
   134 
   135             handle.Close();
   136 
   137             //Get capabilities
   138             HidStatus status = Win32.Function.HidP_GetCaps(PreParsedData, ref iCapabilities);
   139             if (status != HidStatus.HIDP_STATUS_SUCCESS)
   140             {
   141                 throw new Exception("HidDevice: HidP_GetCaps failed: " + status.ToString());
   142             }
   143 
   144             //Get input button caps if needed
   145             if (Capabilities.NumberInputButtonCaps > 0)
   146             {
   147                 iInputButtonCapabilities = new HIDP_BUTTON_CAPS[Capabilities.NumberInputButtonCaps];
   148                 ushort buttonCapabilitiesLength = Capabilities.NumberInputButtonCaps;
   149                 status = Win32.Function.HidP_GetButtonCaps(HIDP_REPORT_TYPE.HidP_Input, iInputButtonCapabilities, ref buttonCapabilitiesLength, PreParsedData);
   150                 if (status != HidStatus.HIDP_STATUS_SUCCESS || buttonCapabilitiesLength != Capabilities.NumberInputButtonCaps)
   151                 {
   152                     throw new Exception("HidDevice: HidP_GetButtonCaps failed: " + status.ToString());
   153                 }
   154             }
   155 
   156             //Get input value caps if needed
   157             if (Capabilities.NumberInputValueCaps > 0)
   158             {
   159                 iInputValueCapabilities = new HIDP_VALUE_CAPS[Capabilities.NumberInputValueCaps];
   160                 ushort valueCapabilitiesLength = Capabilities.NumberInputValueCaps;
   161                 status = Win32.Function.HidP_GetValueCaps(HIDP_REPORT_TYPE.HidP_Input, iInputValueCapabilities, ref valueCapabilitiesLength, PreParsedData);
   162                 if (status != HidStatus.HIDP_STATUS_SUCCESS || valueCapabilitiesLength != Capabilities.NumberInputValueCaps)
   163                 {
   164                     throw new Exception("HidDevice: HidP_GetValueCaps failed: " + status.ToString());
   165                 }
   166             }
   167 
   168 
   169         }
   170 
   171         /// <summary>
   172         /// Dispose is just for unmanaged clean-up.
   173         /// Make sure calling disposed multiple times does not crash.
   174         /// See: http://stackoverflow.com/questions/538060/proper-use-of-the-idisposable-interface/538238#538238
   175         /// </summary>
   176         public void Dispose()
   177         {
   178             Marshal.FreeHGlobal(PreParsedData);
   179             PreParsedData = IntPtr.Zero;
   180         }
   181 
   182         /// <summary>
   183         /// Print information about this device to our debug output.
   184         /// </summary>
   185         public void DebugWrite()
   186         {
   187             Debug.WriteLine("================ HID =========================================================================================");
   188             Debug.WriteLine("==== Name: " + Name);
   189             Debug.WriteLine("==== Manufacturer: " + Manufacturer);
   190             Debug.WriteLine("==== Product: " + Product);
   191             Debug.WriteLine("==== VendorID: 0x" + VendorId.ToString("X4"));
   192             Debug.WriteLine("==== ProductID: 0x" + ProductId.ToString("X4"));
   193             Debug.WriteLine("==== Version: " + Version.ToString());
   194             Debug.WriteLine("==============================================================================================================");
   195         }
   196 
   197     }
   198 
   199 }