Hid/HidDevice.cs
changeset 79 cdc5f8f1b79e
parent 77 fb9ea5ad8c2d
child 81 baabcd5cdf8c
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/Hid/HidDevice.cs	Sun Mar 15 20:25:58 2015 +0100
     1.3 @@ -0,0 +1,372 @@
     1.4 +//
     1.5 +// Copyright (C) 2014-2015 Stéphane Lenclud.
     1.6 +//
     1.7 +// This file is part of SharpLibHid.
     1.8 +//
     1.9 +// SharpDisplayManager is free software: you can redistribute it and/or modify
    1.10 +// it under the terms of the GNU General Public License as published by
    1.11 +// the Free Software Foundation, either version 3 of the License, or
    1.12 +// (at your option) any later version.
    1.13 +//
    1.14 +// SharpDisplayManager is distributed in the hope that it will be useful,
    1.15 +// but WITHOUT ANY WARRANTY; without even the implied warranty of
    1.16 +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    1.17 +// GNU General Public License for more details.
    1.18 +//
    1.19 +// You should have received a copy of the GNU General Public License
    1.20 +// along with SharpDisplayManager.  If not, see <http://www.gnu.org/licenses/>.
    1.21 +//
    1.22 +
    1.23 +
    1.24 +using System;
    1.25 +using System.Windows.Forms;
    1.26 +using System.Runtime.InteropServices;
    1.27 +using System.Diagnostics;
    1.28 +using System.Text;
    1.29 +using Microsoft.Win32.SafeHandles;
    1.30 +using SharpLib.Win32;
    1.31 +
    1.32 +namespace SharpLib.Hid
    1.33 +{
    1.34 +    /// <summary>
    1.35 +    /// Represent a HID device.
    1.36 +    /// Rename to RawInputDevice?
    1.37 +    /// </summary>
    1.38 +    public class HidDevice: IDisposable
    1.39 +    {
    1.40 +        /// <summary>
    1.41 +        /// Unique name of that HID device.
    1.42 +        /// Notably used as input to CreateFile.
    1.43 +        /// </summary>
    1.44 +        public string Name { get; private set; }
    1.45 +
    1.46 +        /// <summary>
    1.47 +        /// Friendly name that people should be able to read.
    1.48 +        /// </summary>
    1.49 +        public string FriendlyName { get; private set; }
    1.50 +
    1.51 +        //
    1.52 +        public string Manufacturer { get; private set; }
    1.53 +        public string Product { get; private set; }
    1.54 +        public ushort VendorId { get; private set; }
    1.55 +        public ushort ProductId { get; private set; }
    1.56 +        public ushort Version { get; private set; }
    1.57 +        //Pre-parsed HID descriptor
    1.58 +        public IntPtr PreParsedData {get; private set;}
    1.59 +        //Info
    1.60 +        public RID_DEVICE_INFO Info { get {return iInfo;} }
    1.61 +        private RID_DEVICE_INFO iInfo;
    1.62 +        //Capabilities
    1.63 +        public HIDP_CAPS Capabilities { get { return iCapabilities; } }
    1.64 +        private HIDP_CAPS iCapabilities;
    1.65 +        public string InputCapabilitiesDescription { get; private set; }
    1.66 +        //Input Button Capabilities
    1.67 +        public HIDP_BUTTON_CAPS[] InputButtonCapabilities { get { return iInputButtonCapabilities; } }
    1.68 +        private HIDP_BUTTON_CAPS[] iInputButtonCapabilities;
    1.69 +        //Input Value Capabilities
    1.70 +        public HIDP_VALUE_CAPS[] InputValueCapabilities { get { return iInputValueCapabilities; } }
    1.71 +        private HIDP_VALUE_CAPS[] iInputValueCapabilities;
    1.72 +
    1.73 +        //
    1.74 +        public int ButtonCount { get; private set; }
    1.75 +
    1.76 +        /// <summary>
    1.77 +        /// Class constructor will fetch this object properties from HID sub system.
    1.78 +        /// </summary>
    1.79 +        /// <param name="hRawInputDevice">Device Handle as provided by RAWINPUTHEADER.hDevice, typically accessed as rawinput.header.hDevice</param>
    1.80 +        public HidDevice(IntPtr hRawInputDevice)
    1.81 +        {
    1.82 +            //Try construct and rollback if needed
    1.83 +            try
    1.84 +            {
    1.85 +                Construct(hRawInputDevice);
    1.86 +            }
    1.87 +            catch (System.Exception ex)
    1.88 +            {
    1.89 +                //Just rollback and propagate
    1.90 +                Dispose();
    1.91 +                throw ex;
    1.92 +            }
    1.93 +        }
    1.94 +
    1.95 +
    1.96 +        /// <summary>
    1.97 +        /// Make sure dispose is called even if the user forgot about it.
    1.98 +        /// </summary>
    1.99 +        ~HidDevice()
   1.100 +        {
   1.101 +            Dispose();
   1.102 +        }
   1.103 +
   1.104 +        /// <summary>
   1.105 +        /// Private constructor.
   1.106 +        /// </summary>
   1.107 +        /// <param name="hRawInputDevice"></param>
   1.108 +        private void Construct(IntPtr hRawInputDevice)
   1.109 +        {
   1.110 +            PreParsedData = IntPtr.Zero;
   1.111 +            iInputButtonCapabilities = null;
   1.112 +            iInputValueCapabilities = null;
   1.113 +
   1.114 +            //Fetch various information defining the given HID device
   1.115 +            Name = Win32.RawInput.GetDeviceName(hRawInputDevice);
   1.116 +
   1.117 +            //Fetch device info
   1.118 +            iInfo = new RID_DEVICE_INFO();
   1.119 +            if (!Win32.RawInput.GetDeviceInfo(hRawInputDevice, ref iInfo))
   1.120 +            {
   1.121 +                throw new Exception("HidDevice: GetDeviceInfo failed: " + Marshal.GetLastWin32Error().ToString());
   1.122 +            }
   1.123 +
   1.124 +            //Open our device from the device name/path
   1.125 +            SafeFileHandle handle = Win32.Function.CreateFile(Name,
   1.126 +                Win32.FileAccess.NONE,
   1.127 +                Win32.FileShare.FILE_SHARE_READ | Win32.FileShare.FILE_SHARE_WRITE,
   1.128 +                IntPtr.Zero,
   1.129 +                Win32.CreationDisposition.OPEN_EXISTING,
   1.130 +                Win32.FileFlagsAttributes.FILE_FLAG_OVERLAPPED,
   1.131 +                IntPtr.Zero
   1.132 +                );
   1.133 +
   1.134 +            //Check if CreateFile worked
   1.135 +            if (handle.IsInvalid)
   1.136 +            {
   1.137 +                throw new Exception("HidDevice: CreateFile failed: " + Marshal.GetLastWin32Error().ToString());
   1.138 +            }
   1.139 +
   1.140 +            //Get manufacturer string
   1.141 +            StringBuilder manufacturerString = new StringBuilder(256);
   1.142 +            if (Win32.Function.HidD_GetManufacturerString(handle, manufacturerString, manufacturerString.Capacity))
   1.143 +            {
   1.144 +                Manufacturer = manufacturerString.ToString();
   1.145 +            }
   1.146 +
   1.147 +            //Get product string
   1.148 +            StringBuilder productString = new StringBuilder(256);
   1.149 +            if (Win32.Function.HidD_GetProductString(handle, productString, productString.Capacity))
   1.150 +            {
   1.151 +                Product = productString.ToString();
   1.152 +            }
   1.153 +
   1.154 +            //Get attributes
   1.155 +            Win32.HIDD_ATTRIBUTES attributes = new Win32.HIDD_ATTRIBUTES();
   1.156 +            if (Win32.Function.HidD_GetAttributes(handle, ref attributes))
   1.157 +            {
   1.158 +                VendorId = attributes.VendorID;
   1.159 +                ProductId = attributes.ProductID;
   1.160 +                Version = attributes.VersionNumber;
   1.161 +            }
   1.162 +
   1.163 +            handle.Close();
   1.164 +
   1.165 +            SetFriendlyName();            
   1.166 +
   1.167 +            //Get our HID descriptor pre-parsed data
   1.168 +            PreParsedData = Win32.RawInput.GetPreParsedData(hRawInputDevice);
   1.169 +
   1.170 +            if (PreParsedData == IntPtr.Zero)
   1.171 +            {
   1.172 +                //We are done then.
   1.173 +                //Some devices don't have pre-parsed data.
   1.174 +                return;
   1.175 +            }
   1.176 +
   1.177 +            //Get capabilities
   1.178 +            HidStatus status = Win32.Function.HidP_GetCaps(PreParsedData, ref iCapabilities);
   1.179 +            if (status != HidStatus.HIDP_STATUS_SUCCESS)
   1.180 +            {
   1.181 +                throw new Exception("HidDevice: HidP_GetCaps failed: " + status.ToString());
   1.182 +            }
   1.183 +
   1.184 +            SetInputCapabilitiesDescription();
   1.185 +
   1.186 +            //Get input button caps if needed
   1.187 +            if (Capabilities.NumberInputButtonCaps > 0)
   1.188 +            {
   1.189 +                iInputButtonCapabilities = new HIDP_BUTTON_CAPS[Capabilities.NumberInputButtonCaps];
   1.190 +                ushort buttonCapabilitiesLength = Capabilities.NumberInputButtonCaps;
   1.191 +                status = Win32.Function.HidP_GetButtonCaps(HIDP_REPORT_TYPE.HidP_Input, iInputButtonCapabilities, ref buttonCapabilitiesLength, PreParsedData);
   1.192 +                if (status != HidStatus.HIDP_STATUS_SUCCESS || buttonCapabilitiesLength != Capabilities.NumberInputButtonCaps)
   1.193 +                {
   1.194 +                    throw new Exception("HidDevice: HidP_GetButtonCaps failed: " + status.ToString());
   1.195 +                }
   1.196 +
   1.197 +                ComputeButtonCount();
   1.198 +            }
   1.199 +
   1.200 +            //Get input value caps if needed
   1.201 +            if (Capabilities.NumberInputValueCaps > 0)
   1.202 +            {
   1.203 +                iInputValueCapabilities = new HIDP_VALUE_CAPS[Capabilities.NumberInputValueCaps];
   1.204 +                ushort valueCapabilitiesLength = Capabilities.NumberInputValueCaps;
   1.205 +                status = Win32.Function.HidP_GetValueCaps(HIDP_REPORT_TYPE.HidP_Input, iInputValueCapabilities, ref valueCapabilitiesLength, PreParsedData);
   1.206 +                if (status != HidStatus.HIDP_STATUS_SUCCESS || valueCapabilitiesLength != Capabilities.NumberInputValueCaps)
   1.207 +                {
   1.208 +                    throw new Exception("HidDevice: HidP_GetValueCaps failed: " + status.ToString());
   1.209 +                }
   1.210 +            }
   1.211 +        }
   1.212 +
   1.213 +
   1.214 +        /// <summary>
   1.215 +        /// Useful for gamepads.
   1.216 +        /// </summary>
   1.217 +        void ComputeButtonCount()
   1.218 +        {
   1.219 +            ButtonCount = 0;
   1.220 +            foreach (HIDP_BUTTON_CAPS bc in iInputButtonCapabilities)
   1.221 +            {
   1.222 +                if (bc.IsRange)
   1.223 +                {
   1.224 +                    ButtonCount += (bc.Range.UsageMax - bc.Range.UsageMin + 1);
   1.225 +                }
   1.226 +            }            
   1.227 +        }
   1.228 +
   1.229 +
   1.230 +        /// <summary>
   1.231 +        /// 
   1.232 +        /// </summary>
   1.233 +        void SetInputCapabilitiesDescription()
   1.234 +        {
   1.235 +            InputCapabilitiesDescription = "[ Input Capabilities ] Button: " + Capabilities.NumberInputButtonCaps + " - Value: " + Capabilities.NumberInputValueCaps + " - Data indices: " + Capabilities.NumberInputDataIndices;
   1.236 +        }
   1.237 +
   1.238 +        /// <summary>
   1.239 +        /// 
   1.240 +        /// </summary>
   1.241 +        private void SetFriendlyName()
   1.242 +        {
   1.243 +            //Work out proper suffix for our device root node.
   1.244 +            //That allows users to see in a glance what kind of device this is.
   1.245 +            string suffix = "";
   1.246 +            Type usageCollectionType = null;
   1.247 +            if (Info.dwType == RawInputDeviceType.RIM_TYPEHID)
   1.248 +            {
   1.249 +                //Process usage page
   1.250 +                if (Enum.IsDefined(typeof(UsagePage), Info.hid.usUsagePage))
   1.251 +                {
   1.252 +                    //We know this usage page, add its name
   1.253 +                    UsagePage usagePage = (UsagePage)Info.hid.usUsagePage;
   1.254 +                    suffix += " ( " + usagePage.ToString() + ", ";
   1.255 +                    usageCollectionType = Utils.UsageCollectionType(usagePage);
   1.256 +                }
   1.257 +                else
   1.258 +                {
   1.259 +                    //We don't know this usage page, add its value
   1.260 +                    suffix += " ( 0x" + Info.hid.usUsagePage.ToString("X4") + ", ";
   1.261 +                }
   1.262 +
   1.263 +                //Process usage collection
   1.264 +                //We don't know this usage page, add its value
   1.265 +                if (usageCollectionType == null || !Enum.IsDefined(usageCollectionType, Info.hid.usUsage))
   1.266 +                {
   1.267 +                    //Show Hexa
   1.268 +                    suffix += "0x" + Info.hid.usUsage.ToString("X4") + " )";
   1.269 +                }
   1.270 +                else
   1.271 +                {
   1.272 +                    //We know this usage page, add its name
   1.273 +                    suffix += Enum.GetName(usageCollectionType, Info.hid.usUsage) + " )";
   1.274 +                }
   1.275 +            }
   1.276 +            else if (Info.dwType == RawInputDeviceType.RIM_TYPEKEYBOARD)
   1.277 +            {
   1.278 +                suffix = " - Keyboard";
   1.279 +            }
   1.280 +            else if (Info.dwType == RawInputDeviceType.RIM_TYPEMOUSE)
   1.281 +            {
   1.282 +                suffix = " - Mouse";
   1.283 +            }
   1.284 +
   1.285 +            if (Product != null && Product.Length > 1)
   1.286 +            {
   1.287 +                //This device as a proper name, use it
   1.288 +                FriendlyName = Product + suffix;
   1.289 +            }
   1.290 +            else
   1.291 +            {   
   1.292 +                //Extract friendly name from name
   1.293 +                char[] delimiterChars = { '#', '&'};
   1.294 +                string[] words = Name.Split(delimiterChars);
   1.295 +                if (words.Length >= 2)
   1.296 +                {
   1.297 +                    //Use our name sub-string to describe this device
   1.298 +                    FriendlyName = words[1] + " - 0x" + ProductId.ToString("X4") + suffix;
   1.299 +                }
   1.300 +                else
   1.301 +                {
   1.302 +                    //No proper name just use the device ID instead
   1.303 +                    FriendlyName = "0x" + ProductId.ToString("X4") + suffix;
   1.304 +                }
   1.305 +            }
   1.306 +
   1.307 +        }
   1.308 +
   1.309 +        /// <summary>
   1.310 +        /// Dispose is just for unmanaged clean-up.
   1.311 +        /// Make sure calling disposed multiple times does not crash.
   1.312 +        /// See: http://stackoverflow.com/questions/538060/proper-use-of-the-idisposable-interface/538238#538238
   1.313 +        /// </summary>
   1.314 +        public void Dispose()
   1.315 +        {
   1.316 +            Marshal.FreeHGlobal(PreParsedData);
   1.317 +            PreParsedData = IntPtr.Zero;
   1.318 +        }
   1.319 +
   1.320 +        /// <summary>
   1.321 +        /// Provide a description for the given capabilities.
   1.322 +        /// Notably describes axis on a gamepad/joystick.
   1.323 +        /// </summary>
   1.324 +        /// <param name="aCaps"></param>
   1.325 +        /// <returns></returns>
   1.326 +        static public string InputValueCapabilityDescription(HIDP_VALUE_CAPS aCaps)
   1.327 +        {
   1.328 +            if (!aCaps.IsRange && Enum.IsDefined(typeof(UsagePage), aCaps.UsagePage))
   1.329 +            {
   1.330 +                Type usageType = Utils.UsageType((UsagePage)aCaps.UsagePage);
   1.331 +                string name = Enum.GetName(usageType, aCaps.NotRange.Usage);
   1.332 +                if (name == null)
   1.333 +                {
   1.334 +                    //Could not find that usage in our enum.
   1.335 +                    //Provide a relevant warning instead.
   1.336 +                    name = "Usage 0x" + aCaps.NotRange.Usage.ToString("X2") + " not defined in " + usageType.Name;
   1.337 +                }
   1.338 +                else
   1.339 +                {
   1.340 +                    //Prepend our usage type name
   1.341 +                    name = usageType.Name + "." + name;
   1.342 +                }
   1.343 +                return "Input Value: " + name;
   1.344 +            }
   1.345 +
   1.346 +            return null;
   1.347 +        }
   1.348 +
   1.349 +        public bool IsGamePad
   1.350 +        {
   1.351 +            get
   1.352 +            {
   1.353 +                return ((UsagePage)iCapabilities.UsagePage == UsagePage.GenericDesktopControls && (UsageCollection.GenericDesktop)iCapabilities.Usage == UsageCollection.GenericDesktop.GamePad);
   1.354 +            }
   1.355 +        }
   1.356 +
   1.357 +
   1.358 +        /// <summary>
   1.359 +        /// Print information about this device to our debug output.
   1.360 +        /// </summary>
   1.361 +        public void DebugWrite()
   1.362 +        {
   1.363 +            Debug.WriteLine("================ HID =========================================================================================");
   1.364 +            Debug.WriteLine("==== Name: " + Name);
   1.365 +            Debug.WriteLine("==== Manufacturer: " + Manufacturer);
   1.366 +            Debug.WriteLine("==== Product: " + Product);
   1.367 +            Debug.WriteLine("==== VendorID: 0x" + VendorId.ToString("X4"));
   1.368 +            Debug.WriteLine("==== ProductID: 0x" + ProductId.ToString("X4"));
   1.369 +            Debug.WriteLine("==== Version: " + Version.ToString());
   1.370 +            Debug.WriteLine("==============================================================================================================");
   1.371 +        }
   1.372 +
   1.373 +    }
   1.374 +
   1.375 +}
   1.376 \ No newline at end of file