Now using SharpLib.Hid and SharpLib.Win32 as namespaces.
2 // Copyright (C) 2014-2015 Stéphane Lenclud.
4 // This file is part of SharpLibHid.
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.
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.
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/>.
22 using System.Windows.Forms;
23 using System.Runtime.InteropServices;
24 using System.Diagnostics;
26 using Microsoft.Win32.SafeHandles;
29 namespace SharpLib.Hid
32 /// Represent a HID device.
33 /// Rename to RawInputDevice?
35 public class HidDevice: IDisposable
38 /// Unique name of that HID device.
39 /// Notably used as input to CreateFile.
41 public string Name { get; private set; }
44 /// Friendly name that people should be able to read.
46 public string FriendlyName { get; private set; }
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;}
57 public RID_DEVICE_INFO Info { get {return iInfo;} }
58 private RID_DEVICE_INFO iInfo;
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;
71 public int ButtonCount { get; private set; }
74 /// Class constructor will fetch this object properties from HID sub system.
76 /// <param name="hRawInputDevice">Device Handle as provided by RAWINPUTHEADER.hDevice, typically accessed as rawinput.header.hDevice</param>
77 public HidDevice(IntPtr hRawInputDevice)
79 //Try construct and rollback if needed
82 Construct(hRawInputDevice);
84 catch (System.Exception ex)
86 //Just rollback and propagate
94 /// Make sure dispose is called even if the user forgot about it.
102 /// Private constructor.
104 /// <param name="hRawInputDevice"></param>
105 private void Construct(IntPtr hRawInputDevice)
107 PreParsedData = IntPtr.Zero;
108 iInputButtonCapabilities = null;
109 iInputValueCapabilities = null;
111 //Fetch various information defining the given HID device
112 Name = Win32.RawInput.GetDeviceName(hRawInputDevice);
115 iInfo = new RID_DEVICE_INFO();
116 if (!Win32.RawInput.GetDeviceInfo(hRawInputDevice, ref iInfo))
118 throw new Exception("HidDevice: GetDeviceInfo failed: " + Marshal.GetLastWin32Error().ToString());
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,
126 Win32.CreationDisposition.OPEN_EXISTING,
127 Win32.FileFlagsAttributes.FILE_FLAG_OVERLAPPED,
131 //Check if CreateFile worked
132 if (handle.IsInvalid)
134 throw new Exception("HidDevice: CreateFile failed: " + Marshal.GetLastWin32Error().ToString());
137 //Get manufacturer string
138 StringBuilder manufacturerString = new StringBuilder(256);
139 if (Win32.Function.HidD_GetManufacturerString(handle, manufacturerString, manufacturerString.Capacity))
141 Manufacturer = manufacturerString.ToString();
145 StringBuilder productString = new StringBuilder(256);
146 if (Win32.Function.HidD_GetProductString(handle, productString, productString.Capacity))
148 Product = productString.ToString();
152 Win32.HIDD_ATTRIBUTES attributes = new Win32.HIDD_ATTRIBUTES();
153 if (Win32.Function.HidD_GetAttributes(handle, ref attributes))
155 VendorId = attributes.VendorID;
156 ProductId = attributes.ProductID;
157 Version = attributes.VersionNumber;
164 //Get our HID descriptor pre-parsed data
165 PreParsedData = Win32.RawInput.GetPreParsedData(hRawInputDevice);
167 if (PreParsedData == IntPtr.Zero)
170 //Some devices don't have pre-parsed data.
175 HidStatus status = Win32.Function.HidP_GetCaps(PreParsedData, ref iCapabilities);
176 if (status != HidStatus.HIDP_STATUS_SUCCESS)
178 throw new Exception("HidDevice: HidP_GetCaps failed: " + status.ToString());
181 SetInputCapabilitiesDescription();
183 //Get input button caps if needed
184 if (Capabilities.NumberInputButtonCaps > 0)
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)
191 throw new Exception("HidDevice: HidP_GetButtonCaps failed: " + status.ToString());
194 ComputeButtonCount();
197 //Get input value caps if needed
198 if (Capabilities.NumberInputValueCaps > 0)
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)
205 throw new Exception("HidDevice: HidP_GetValueCaps failed: " + status.ToString());
212 /// Useful for gamepads.
214 void ComputeButtonCount()
217 foreach (HIDP_BUTTON_CAPS bc in iInputButtonCapabilities)
221 ButtonCount += (bc.Range.UsageMax - bc.Range.UsageMin + 1);
230 void SetInputCapabilitiesDescription()
232 InputCapabilitiesDescription = "[ Input Capabilities ] Button: " + Capabilities.NumberInputButtonCaps + " - Value: " + Capabilities.NumberInputValueCaps + " - Data indices: " + Capabilities.NumberInputDataIndices;
238 private void SetFriendlyName()
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.
243 Type usageCollectionType = null;
244 if (Info.dwType == RawInputDeviceType.RIM_TYPEHID)
247 if (Enum.IsDefined(typeof(UsagePage), Info.hid.usUsagePage))
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);
256 //We don't know this usage page, add its value
257 suffix += " ( 0x" + Info.hid.usUsagePage.ToString("X4") + ", ";
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))
265 suffix += "0x" + Info.hid.usUsage.ToString("X4") + " )";
269 //We know this usage page, add its name
270 suffix += Enum.GetName(usageCollectionType, Info.hid.usUsage) + " )";
273 else if (Info.dwType == RawInputDeviceType.RIM_TYPEKEYBOARD)
275 suffix = " - Keyboard";
277 else if (Info.dwType == RawInputDeviceType.RIM_TYPEMOUSE)
282 if (Product != null && Product.Length > 1)
284 //This device as a proper name, use it
285 FriendlyName = Product + suffix;
289 //Extract friendly name from name
290 char[] delimiterChars = { '#', '&'};
291 string[] words = Name.Split(delimiterChars);
292 if (words.Length >= 2)
294 //Use our name sub-string to describe this device
295 FriendlyName = words[1] + " - 0x" + ProductId.ToString("X4") + suffix;
299 //No proper name just use the device ID instead
300 FriendlyName = "0x" + ProductId.ToString("X4") + suffix;
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
311 public void Dispose()
313 Marshal.FreeHGlobal(PreParsedData);
314 PreParsedData = IntPtr.Zero;
318 /// Provide a description for the given capabilities.
319 /// Notably describes axis on a gamepad/joystick.
321 /// <param name="aCaps"></param>
322 /// <returns></returns>
323 static public string InputValueCapabilityDescription(HIDP_VALUE_CAPS aCaps)
325 if (!aCaps.IsRange && Enum.IsDefined(typeof(UsagePage), aCaps.UsagePage))
327 Type usageType = Utils.UsageType((UsagePage)aCaps.UsagePage);
328 string name = Enum.GetName(usageType, aCaps.NotRange.Usage);
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;
337 //Prepend our usage type name
338 name = usageType.Name + "." + name;
340 return "Input Value: " + name;
346 public bool IsGamePad
350 return ((UsagePage)iCapabilities.UsagePage == UsagePage.GenericDesktopControls && (UsageCollection.GenericDesktop)iCapabilities.Usage == UsageCollection.GenericDesktop.GamePad);
356 /// Print information about this device to our debug output.
358 public void DebugWrite()
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("==============================================================================================================");