HidDevice.cs
author StephaneLenclud
Sun, 15 Mar 2015 14:45:40 +0100
changeset 77 fb9ea5ad8c2d
parent 76 831ebeeecfdf
permissions -rw-r--r--
Now using SharpLib.Hid and SharpLib.Win32 as namespaces.
     1 //
     2 // Copyright (C) 2014-2015 Stéphane Lenclud.
     3 //
     4 // This file is part of SharpLibHid.
     5 //
     6 // SharpDisplayManager is free software: you can redistribute it and/or modify
     7 // it under the terms of the GNU General Public License as published by
     8 // the Free Software Foundation, either version 3 of the License, or
     9 // (at your option) any later version.
    10 //
    11 // SharpDisplayManager is distributed in the hope that it will be useful,
    12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
    13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    14 // GNU General Public License for more details.
    15 //
    16 // You should have received a copy of the GNU General Public License
    17 // along with SharpDisplayManager.  If not, see <http://www.gnu.org/licenses/>.
    18 //
    19 
    20 
    21 using System;
    22 using System.Windows.Forms;
    23 using System.Runtime.InteropServices;
    24 using System.Diagnostics;
    25 using System.Text;
    26 using Microsoft.Win32.SafeHandles;
    27 using SharpLib.Win32;
    28 
    29 namespace SharpLib.Hid
    30 {
    31     /// <summary>
    32     /// Represent a HID device.
    33     /// Rename to RawInputDevice?
    34     /// </summary>
    35     public class HidDevice: IDisposable
    36     {
    37         /// <summary>
    38         /// Unique name of that HID device.
    39         /// Notably used as input to CreateFile.
    40         /// </summary>
    41         public string Name { get; private set; }
    42 
    43         /// <summary>
    44         /// Friendly name that people should be able to read.
    45         /// </summary>
    46         public string FriendlyName { get; private set; }
    47 
    48         //
    49         public string Manufacturer { get; private set; }
    50         public string Product { get; private set; }
    51         public ushort VendorId { get; private set; }
    52         public ushort ProductId { get; private set; }
    53         public ushort Version { get; private set; }
    54         //Pre-parsed HID descriptor
    55         public IntPtr PreParsedData {get; private set;}
    56         //Info
    57         public RID_DEVICE_INFO Info { get {return iInfo;} }
    58         private RID_DEVICE_INFO iInfo;
    59         //Capabilities
    60         public HIDP_CAPS Capabilities { get { return iCapabilities; } }
    61         private HIDP_CAPS iCapabilities;
    62         public string InputCapabilitiesDescription { get; private set; }
    63         //Input Button Capabilities
    64         public HIDP_BUTTON_CAPS[] InputButtonCapabilities { get { return iInputButtonCapabilities; } }
    65         private HIDP_BUTTON_CAPS[] iInputButtonCapabilities;
    66         //Input Value Capabilities
    67         public HIDP_VALUE_CAPS[] InputValueCapabilities { get { return iInputValueCapabilities; } }
    68         private HIDP_VALUE_CAPS[] iInputValueCapabilities;
    69 
    70         //
    71         public int ButtonCount { get; private set; }
    72 
    73         /// <summary>
    74         /// Class constructor will fetch this object properties from HID sub system.
    75         /// </summary>
    76         /// <param name="hRawInputDevice">Device Handle as provided by RAWINPUTHEADER.hDevice, typically accessed as rawinput.header.hDevice</param>
    77         public HidDevice(IntPtr hRawInputDevice)
    78         {
    79             //Try construct and rollback if needed
    80             try
    81             {
    82                 Construct(hRawInputDevice);
    83             }
    84             catch (System.Exception ex)
    85             {
    86                 //Just rollback and propagate
    87                 Dispose();
    88                 throw ex;
    89             }
    90         }
    91 
    92 
    93         /// <summary>
    94         /// Make sure dispose is called even if the user forgot about it.
    95         /// </summary>
    96         ~HidDevice()
    97         {
    98             Dispose();
    99         }
   100 
   101         /// <summary>
   102         /// Private constructor.
   103         /// </summary>
   104         /// <param name="hRawInputDevice"></param>
   105         private void Construct(IntPtr hRawInputDevice)
   106         {
   107             PreParsedData = IntPtr.Zero;
   108             iInputButtonCapabilities = null;
   109             iInputValueCapabilities = null;
   110 
   111             //Fetch various information defining the given HID device
   112             Name = Win32.RawInput.GetDeviceName(hRawInputDevice);
   113 
   114             //Fetch device info
   115             iInfo = new RID_DEVICE_INFO();
   116             if (!Win32.RawInput.GetDeviceInfo(hRawInputDevice, ref iInfo))
   117             {
   118                 throw new Exception("HidDevice: GetDeviceInfo failed: " + Marshal.GetLastWin32Error().ToString());
   119             }
   120 
   121             //Open our device from the device name/path
   122             SafeFileHandle handle = Win32.Function.CreateFile(Name,
   123                 Win32.FileAccess.NONE,
   124                 Win32.FileShare.FILE_SHARE_READ | Win32.FileShare.FILE_SHARE_WRITE,
   125                 IntPtr.Zero,
   126                 Win32.CreationDisposition.OPEN_EXISTING,
   127                 Win32.FileFlagsAttributes.FILE_FLAG_OVERLAPPED,
   128                 IntPtr.Zero
   129                 );
   130 
   131             //Check if CreateFile worked
   132             if (handle.IsInvalid)
   133             {
   134                 throw new Exception("HidDevice: CreateFile failed: " + Marshal.GetLastWin32Error().ToString());
   135             }
   136 
   137             //Get manufacturer string
   138             StringBuilder manufacturerString = new StringBuilder(256);
   139             if (Win32.Function.HidD_GetManufacturerString(handle, manufacturerString, manufacturerString.Capacity))
   140             {
   141                 Manufacturer = manufacturerString.ToString();
   142             }
   143 
   144             //Get product string
   145             StringBuilder productString = new StringBuilder(256);
   146             if (Win32.Function.HidD_GetProductString(handle, productString, productString.Capacity))
   147             {
   148                 Product = productString.ToString();
   149             }
   150 
   151             //Get attributes
   152             Win32.HIDD_ATTRIBUTES attributes = new Win32.HIDD_ATTRIBUTES();
   153             if (Win32.Function.HidD_GetAttributes(handle, ref attributes))
   154             {
   155                 VendorId = attributes.VendorID;
   156                 ProductId = attributes.ProductID;
   157                 Version = attributes.VersionNumber;
   158             }
   159 
   160             handle.Close();
   161 
   162             SetFriendlyName();            
   163 
   164             //Get our HID descriptor pre-parsed data
   165             PreParsedData = Win32.RawInput.GetPreParsedData(hRawInputDevice);
   166 
   167             if (PreParsedData == IntPtr.Zero)
   168             {
   169                 //We are done then.
   170                 //Some devices don't have pre-parsed data.
   171                 return;
   172             }
   173 
   174             //Get capabilities
   175             HidStatus status = Win32.Function.HidP_GetCaps(PreParsedData, ref iCapabilities);
   176             if (status != HidStatus.HIDP_STATUS_SUCCESS)
   177             {
   178                 throw new Exception("HidDevice: HidP_GetCaps failed: " + status.ToString());
   179             }
   180 
   181             SetInputCapabilitiesDescription();
   182 
   183             //Get input button caps if needed
   184             if (Capabilities.NumberInputButtonCaps > 0)
   185             {
   186                 iInputButtonCapabilities = new HIDP_BUTTON_CAPS[Capabilities.NumberInputButtonCaps];
   187                 ushort buttonCapabilitiesLength = Capabilities.NumberInputButtonCaps;
   188                 status = Win32.Function.HidP_GetButtonCaps(HIDP_REPORT_TYPE.HidP_Input, iInputButtonCapabilities, ref buttonCapabilitiesLength, PreParsedData);
   189                 if (status != HidStatus.HIDP_STATUS_SUCCESS || buttonCapabilitiesLength != Capabilities.NumberInputButtonCaps)
   190                 {
   191                     throw new Exception("HidDevice: HidP_GetButtonCaps failed: " + status.ToString());
   192                 }
   193 
   194                 ComputeButtonCount();
   195             }
   196 
   197             //Get input value caps if needed
   198             if (Capabilities.NumberInputValueCaps > 0)
   199             {
   200                 iInputValueCapabilities = new HIDP_VALUE_CAPS[Capabilities.NumberInputValueCaps];
   201                 ushort valueCapabilitiesLength = Capabilities.NumberInputValueCaps;
   202                 status = Win32.Function.HidP_GetValueCaps(HIDP_REPORT_TYPE.HidP_Input, iInputValueCapabilities, ref valueCapabilitiesLength, PreParsedData);
   203                 if (status != HidStatus.HIDP_STATUS_SUCCESS || valueCapabilitiesLength != Capabilities.NumberInputValueCaps)
   204                 {
   205                     throw new Exception("HidDevice: HidP_GetValueCaps failed: " + status.ToString());
   206                 }
   207             }
   208         }
   209 
   210 
   211         /// <summary>
   212         /// Useful for gamepads.
   213         /// </summary>
   214         void ComputeButtonCount()
   215         {
   216             ButtonCount = 0;
   217             foreach (HIDP_BUTTON_CAPS bc in iInputButtonCapabilities)
   218             {
   219                 if (bc.IsRange)
   220                 {
   221                     ButtonCount += (bc.Range.UsageMax - bc.Range.UsageMin + 1);
   222                 }
   223             }            
   224         }
   225 
   226 
   227         /// <summary>
   228         /// 
   229         /// </summary>
   230         void SetInputCapabilitiesDescription()
   231         {
   232             InputCapabilitiesDescription = "[ Input Capabilities ] Button: " + Capabilities.NumberInputButtonCaps + " - Value: " + Capabilities.NumberInputValueCaps + " - Data indices: " + Capabilities.NumberInputDataIndices;
   233         }
   234 
   235         /// <summary>
   236         /// 
   237         /// </summary>
   238         private void SetFriendlyName()
   239         {
   240             //Work out proper suffix for our device root node.
   241             //That allows users to see in a glance what kind of device this is.
   242             string suffix = "";
   243             Type usageCollectionType = null;
   244             if (Info.dwType == RawInputDeviceType.RIM_TYPEHID)
   245             {
   246                 //Process usage page
   247                 if (Enum.IsDefined(typeof(UsagePage), Info.hid.usUsagePage))
   248                 {
   249                     //We know this usage page, add its name
   250                     UsagePage usagePage = (UsagePage)Info.hid.usUsagePage;
   251                     suffix += " ( " + usagePage.ToString() + ", ";
   252                     usageCollectionType = Utils.UsageCollectionType(usagePage);
   253                 }
   254                 else
   255                 {
   256                     //We don't know this usage page, add its value
   257                     suffix += " ( 0x" + Info.hid.usUsagePage.ToString("X4") + ", ";
   258                 }
   259 
   260                 //Process usage collection
   261                 //We don't know this usage page, add its value
   262                 if (usageCollectionType == null || !Enum.IsDefined(usageCollectionType, Info.hid.usUsage))
   263                 {
   264                     //Show Hexa
   265                     suffix += "0x" + Info.hid.usUsage.ToString("X4") + " )";
   266                 }
   267                 else
   268                 {
   269                     //We know this usage page, add its name
   270                     suffix += Enum.GetName(usageCollectionType, Info.hid.usUsage) + " )";
   271                 }
   272             }
   273             else if (Info.dwType == RawInputDeviceType.RIM_TYPEKEYBOARD)
   274             {
   275                 suffix = " - Keyboard";
   276             }
   277             else if (Info.dwType == RawInputDeviceType.RIM_TYPEMOUSE)
   278             {
   279                 suffix = " - Mouse";
   280             }
   281 
   282             if (Product != null && Product.Length > 1)
   283             {
   284                 //This device as a proper name, use it
   285                 FriendlyName = Product + suffix;
   286             }
   287             else
   288             {   
   289                 //Extract friendly name from name
   290                 char[] delimiterChars = { '#', '&'};
   291                 string[] words = Name.Split(delimiterChars);
   292                 if (words.Length >= 2)
   293                 {
   294                     //Use our name sub-string to describe this device
   295                     FriendlyName = words[1] + " - 0x" + ProductId.ToString("X4") + suffix;
   296                 }
   297                 else
   298                 {
   299                     //No proper name just use the device ID instead
   300                     FriendlyName = "0x" + ProductId.ToString("X4") + suffix;
   301                 }
   302             }
   303 
   304         }
   305 
   306         /// <summary>
   307         /// Dispose is just for unmanaged clean-up.
   308         /// Make sure calling disposed multiple times does not crash.
   309         /// See: http://stackoverflow.com/questions/538060/proper-use-of-the-idisposable-interface/538238#538238
   310         /// </summary>
   311         public void Dispose()
   312         {
   313             Marshal.FreeHGlobal(PreParsedData);
   314             PreParsedData = IntPtr.Zero;
   315         }
   316 
   317         /// <summary>
   318         /// Provide a description for the given capabilities.
   319         /// Notably describes axis on a gamepad/joystick.
   320         /// </summary>
   321         /// <param name="aCaps"></param>
   322         /// <returns></returns>
   323         static public string InputValueCapabilityDescription(HIDP_VALUE_CAPS aCaps)
   324         {
   325             if (!aCaps.IsRange && Enum.IsDefined(typeof(UsagePage), aCaps.UsagePage))
   326             {
   327                 Type usageType = Utils.UsageType((UsagePage)aCaps.UsagePage);
   328                 string name = Enum.GetName(usageType, aCaps.NotRange.Usage);
   329                 if (name == null)
   330                 {
   331                     //Could not find that usage in our enum.
   332                     //Provide a relevant warning instead.
   333                     name = "Usage 0x" + aCaps.NotRange.Usage.ToString("X2") + " not defined in " + usageType.Name;
   334                 }
   335                 else
   336                 {
   337                     //Prepend our usage type name
   338                     name = usageType.Name + "." + name;
   339                 }
   340                 return "Input Value: " + name;
   341             }
   342 
   343             return null;
   344         }
   345 
   346         public bool IsGamePad
   347         {
   348             get
   349             {
   350                 return ((UsagePage)iCapabilities.UsagePage == UsagePage.GenericDesktopControls && (UsageCollection.GenericDesktop)iCapabilities.Usage == UsageCollection.GenericDesktop.GamePad);
   351             }
   352         }
   353 
   354 
   355         /// <summary>
   356         /// Print information about this device to our debug output.
   357         /// </summary>
   358         public void DebugWrite()
   359         {
   360             Debug.WriteLine("================ HID =========================================================================================");
   361             Debug.WriteLine("==== Name: " + Name);
   362             Debug.WriteLine("==== Manufacturer: " + Manufacturer);
   363             Debug.WriteLine("==== Product: " + Product);
   364             Debug.WriteLine("==== VendorID: 0x" + VendorId.ToString("X4"));
   365             Debug.WriteLine("==== ProductID: 0x" + ProductId.ToString("X4"));
   366             Debug.WriteLine("==== Version: " + Version.ToString());
   367             Debug.WriteLine("==============================================================================================================");
   368         }
   369 
   370     }
   371 
   372 }