HidEvent.cs
author StephaneLenclud
Sat, 14 Feb 2015 23:41:12 +0100
changeset 53 e7831b781512
parent 52 2f34ceaf0692
child 54 7647691aa209
permissions -rw-r--r--
Device Info moves where it belongs into our device class.
     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 using System.Collections.Generic;
     9 using System.Timers;
    10 
    11 
    12 namespace Hid
    13 {
    14     /// <summary>
    15     /// Represent a HID event.
    16     /// </summary>
    17     public class HidEvent: IDisposable
    18     {
    19         public bool IsValid { get; private set; }
    20         public bool IsForeground { get; private set; }        
    21         public bool IsBackground { get{return !IsForeground;} }
    22         public bool IsMouse { get; private set; }
    23         public bool IsKeyboard { get; private set; }
    24         public bool IsGeneric { get; private set; }
    25         public bool IsButtonDown { get { return Usages.Count == 1 && Usages[0] != 0; } }
    26         public bool IsButtonUp { get { return Usages.Count == 0; } }
    27         public bool IsRepeat { get { return RepeatCount != 0; } }
    28         public uint RepeatCount { get; private set; }
    29 
    30         public HidDevice Device { get; private set; }
    31 
    32         public ushort UsagePage { get; private set; }
    33         public ushort UsageCollection { get; private set; }
    34         public uint UsageId { get { return ((uint)UsagePage << 16 | (uint)UsageCollection); } }
    35         public List<ushort> Usages { get; private set; }
    36 		public byte[] InputReport { get; private set; }
    37 		//
    38 		public delegate void HidEventRepeatDelegate(HidEvent aHidEvent);
    39         public event HidEventRepeatDelegate OnHidEventRepeat;
    40 
    41         private System.Timers.Timer Timer { get; set; }
    42         public DateTime Time { get; private set; }
    43         public DateTime OriginalTime { get; private set; }
    44 
    45         //Compute repeat delay and speed based on system settings
    46         //Those computations were taken from the Petzold here: ftp://ftp.charlespetzold.com/ProgWinForms/4%20Custom%20Controls/NumericScan/NumericScan/ClickmaticButton.cs
    47         private int iRepeatDelay = 250 * (1 + SystemInformation.KeyboardDelay);
    48         private int iRepeatSpeed = 405 - 12 * SystemInformation.KeyboardSpeed;
    49 
    50         /// <summary>
    51         /// Tells whether this event has already been disposed of.
    52         /// </summary>
    53         public bool IsStray { get { return Timer == null; } }
    54 
    55         /// <summary>
    56         /// We typically dispose of events as soon as we get the corresponding key up signal.
    57         /// </summary>
    58         public void Dispose()
    59         {
    60             Timer.Enabled = false;
    61             Timer.Dispose();
    62             //Mark this event as a stray
    63             Timer = null;
    64         }
    65 
    66         /// <summary>
    67         /// Initialize an HidEvent from a WM_INPUT message
    68         /// </summary>
    69         /// <param name="hRawInputDevice">Device Handle as provided by RAWINPUTHEADER.hDevice, typically accessed as rawinput.header.hDevice</param>
    70         public HidEvent(Message aMessage, HidEventRepeatDelegate aRepeatDelegate)
    71         {
    72             RepeatCount = 0;
    73             IsValid = false;
    74             IsKeyboard = false;
    75             IsGeneric = false;
    76             
    77 
    78             Time = DateTime.Now;
    79             OriginalTime = DateTime.Now;
    80             Timer = new System.Timers.Timer();
    81             Timer.Elapsed += (sender, e) => OnRepeatTimerElapsed(sender, e, this);
    82             Usages = new List<ushort>();
    83             OnHidEventRepeat += aRepeatDelegate;
    84 
    85             if (aMessage.Msg != Const.WM_INPUT)
    86             {
    87                 //Has to be a WM_INPUT message
    88                 return;
    89             }
    90 
    91             if (Macro.GET_RAWINPUT_CODE_WPARAM(aMessage.WParam) == Const.RIM_INPUT)
    92             {
    93                 IsForeground = true;
    94             }
    95             else if (Macro.GET_RAWINPUT_CODE_WPARAM(aMessage.WParam) == Const.RIM_INPUTSINK)
    96             {
    97                 IsForeground = false;
    98             }
    99 
   100             //Declare some pointers
   101             IntPtr rawInputBuffer = IntPtr.Zero;
   102 
   103             try
   104             {
   105                 //Fetch raw input
   106                 RAWINPUT rawInput = new RAWINPUT();
   107                 if (!Win32.Utils.RawInput.GetRawInputData(aMessage.LParam, ref rawInput, ref rawInputBuffer))
   108                 {
   109                     return;
   110                 }
   111 
   112 
   113                 //Get various information about this HID device
   114                 Device = new Hid.HidDevice(rawInput.header.hDevice);                
   115 
   116                 if (rawInput.header.dwType == Const.RIM_TYPEHID)  //Check that our raw input is HID                        
   117                 {
   118                     IsGeneric = true;
   119 
   120                     Debug.WriteLine("WM_INPUT source device is HID.");
   121                     //Get Usage Page and Usage
   122                     //Debug.WriteLine("Usage Page: 0x" + deviceInfo.hid.usUsagePage.ToString("X4") + " Usage ID: 0x" + deviceInfo.hid.usUsage.ToString("X4"));
   123                     UsagePage = Device.Info.hid.usUsagePage;
   124                     UsageCollection = Device.Info.hid.usUsage;
   125 
   126                     if (!(rawInput.hid.dwSizeHid > 1     //Make sure our HID msg size more than 1. In fact the first ushort is irrelevant to us for now
   127                         && rawInput.hid.dwCount > 0))    //Check that we have at least one HID msg
   128                     {
   129                         return;
   130                     }
   131 
   132                     //Allocate a buffer for one HID input
   133 					InputReport = new byte[rawInput.hid.dwSizeHid];
   134 
   135                     Debug.WriteLine("Raw input contains " + rawInput.hid.dwCount + " HID input report(s)");
   136 
   137                     //For each HID input report in our raw input
   138                     for (int i = 0; i < rawInput.hid.dwCount; i++)
   139                     {
   140                         //Compute the address from which to copy our HID input
   141                         int hidInputOffset = 0;
   142                         unsafe
   143                         {
   144                             byte* source = (byte*)rawInputBuffer;
   145                             source += sizeof(RAWINPUTHEADER) + sizeof(RAWHID) + (rawInput.hid.dwSizeHid * i);
   146                             hidInputOffset = (int)source;
   147                         }
   148 
   149                         //Copy HID input into our buffer
   150 						Marshal.Copy(new IntPtr(hidInputOffset), InputReport, 0, (int)rawInput.hid.dwSizeHid);
   151 
   152                         //Print HID input report in our debug output
   153                         //string hidDump = "HID input report: " + InputReportString();
   154                         //Debug.WriteLine(hidDump);
   155 
   156                         //Do proper parsing of our HID report
   157 						//First query our usage count
   158                         uint usageCount = 0; 
   159                         Win32.USAGE_AND_PAGE[] usages = null;
   160 						Win32.HidStatus status = Win32.Function.HidP_GetUsagesEx(Win32.HIDP_REPORT_TYPE.HidP_Input, 0, usages, ref usageCount, Device.PreParsedData, InputReport, (uint)InputReport.Length);
   161 						if (status == Win32.HidStatus.HIDP_STATUS_BUFFER_TOO_SMALL)
   162 						{
   163 							//Allocate a large enough buffer 
   164 							usages = new Win32.USAGE_AND_PAGE[usageCount];
   165 							//...and fetch our usages
   166                             status = Win32.Function.HidP_GetUsagesEx(Win32.HIDP_REPORT_TYPE.HidP_Input, 0, usages, ref usageCount, Device.PreParsedData, InputReport, (uint)InputReport.Length);
   167 							if (status != Win32.HidStatus.HIDP_STATUS_SUCCESS)
   168 							{
   169 								Debug.WriteLine("Second pass could not parse HID data: " + status.ToString());
   170 							}
   171 						}
   172 						else if (status != Win32.HidStatus.HIDP_STATUS_SUCCESS) 
   173 						{
   174 							Debug.WriteLine("First pass could not parse HID data: " + status.ToString());
   175 						}
   176 
   177 						Debug.WriteLine("Usage count: " + usageCount.ToString());
   178 
   179                         //Copy usages into this event
   180 						if (usages != null)
   181 						{
   182 							foreach (USAGE_AND_PAGE up in usages)
   183 							{
   184 								//Debug.WriteLine("UsagePage: 0x" + usages[0].UsagePage.ToString("X4"));
   185 								//Debug.WriteLine("Usage: 0x" + usages[0].Usage.ToString("X4"));
   186 								//Add this usage to our list
   187 								Usages.Add(up.Usage);
   188 							}
   189 						}                       
   190                     }
   191                 }
   192                 else if (rawInput.header.dwType == Const.RIM_TYPEMOUSE)
   193                 {
   194                     IsMouse = true;
   195 
   196                     Debug.WriteLine("WM_INPUT source device is Mouse.");                    
   197                     // do mouse handling...
   198                 }
   199                 else if (rawInput.header.dwType == Const.RIM_TYPEKEYBOARD)
   200                 {
   201                     IsKeyboard = true;
   202 
   203                     Debug.WriteLine("WM_INPUT source device is Keyboard.");
   204                     // do keyboard handling...
   205                     Debug.WriteLine("Type: " + Device.Info.keyboard.dwType.ToString());
   206                     Debug.WriteLine("SubType: " + Device.Info.keyboard.dwSubType.ToString());
   207                     Debug.WriteLine("Mode: " + Device.Info.keyboard.dwKeyboardMode.ToString());
   208                     Debug.WriteLine("Number of function keys: " + Device.Info.keyboard.dwNumberOfFunctionKeys.ToString());
   209                     Debug.WriteLine("Number of indicators: " + Device.Info.keyboard.dwNumberOfIndicators.ToString());
   210                     Debug.WriteLine("Number of keys total: " + Device.Info.keyboard.dwNumberOfKeysTotal.ToString());
   211                 }
   212             }
   213             finally
   214             {
   215                 //Always executed when leaving our try block
   216                 Marshal.FreeHGlobal(rawInputBuffer);
   217             }
   218 
   219             //
   220             if (IsButtonDown)
   221             {
   222 				//TODO: Make this optional
   223                 StartRepeatTimer(iRepeatDelay);
   224             }
   225             
   226             IsValid = true;
   227         }
   228 
   229         public void StartRepeatTimer(double aInterval)
   230         {
   231             if (Timer == null)
   232             {
   233                 return;
   234             }
   235             Timer.Enabled = false;
   236             //Initial delay do not use auto reset
   237             //After our initial delay however we do setup our timer one more time using auto reset
   238             Timer.AutoReset = (RepeatCount!=0);
   239             Timer.Interval = aInterval;         
   240             Timer.Enabled = true;            
   241         }
   242 
   243         static private void OnRepeatTimerElapsed(object sender, ElapsedEventArgs e, HidEvent aHidEvent)
   244         {
   245             if (aHidEvent.IsStray)
   246             {
   247                 //Skip events if canceled
   248                 return;
   249             }
   250 
   251             aHidEvent.RepeatCount++;
   252             aHidEvent.Time = DateTime.Now;
   253             if (aHidEvent.RepeatCount==1)
   254             {
   255                 //Re-Start our timer only after the initial delay 
   256                 aHidEvent.StartRepeatTimer(aHidEvent.iRepeatSpeed);
   257             }
   258 
   259             //Broadcast our repeat event
   260             aHidEvent.OnHidEventRepeat(aHidEvent);
   261         }
   262 
   263 		/// <summary>
   264 		/// Print information about this device to our debug output.
   265 		/// </summary>
   266 		public void DebugWrite()
   267 		{
   268 			if (!IsValid)
   269 			{
   270 				Debug.WriteLine("==== Invalid HidEvent");
   271 				return;
   272 			}
   273 			Device.DebugWrite();
   274 			if (IsGeneric) Debug.WriteLine("==== Generic");
   275 			if (IsKeyboard) Debug.WriteLine("==== Keyboard");
   276 			if (IsMouse) Debug.WriteLine("==== Mouse");
   277 			Debug.WriteLine("==== Foreground: " + IsForeground.ToString());
   278 			Debug.WriteLine("==== UsagePage: 0x" + UsagePage.ToString("X4"));
   279 			Debug.WriteLine("==== UsageCollection: 0x" + UsageCollection.ToString("X4"));
   280 			Debug.WriteLine("==== InputReport: 0x" + InputReportString());
   281 			foreach (ushort usage in Usages)
   282 			{
   283 				Debug.WriteLine("==== Usage: 0x" + usage.ToString("X4"));
   284 			}
   285 		}
   286 
   287 		/// <summary>
   288 		/// 
   289 		/// </summary>
   290 		/// <returns></returns>
   291 		public string InputReportString()
   292 		{
   293 			string hidDump = "";
   294 			foreach (byte b in InputReport)
   295 			{
   296 				hidDump += b.ToString("X2");
   297 			}
   298 			return hidDump;
   299 		}
   300 
   301 
   302 		/// <summary>
   303 		/// Create a list view item describing this HidEvent
   304 		/// </summary>
   305 		/// <returns></returns>
   306         public ListViewItem ToListViewItem()
   307         {
   308             string usageText = "";
   309 
   310 			foreach (ushort usage in Usages)
   311 			{
   312 				if (usageText != "")
   313 				{
   314 					//Add a separator
   315 					usageText += ", ";
   316 				}
   317 
   318 				UsagePage usagePage = (UsagePage)UsagePage;
   319 				switch (usagePage)
   320 				{
   321 					case Hid.UsagePage.Consumer:
   322 						usageText += ((Hid.UsageTables.ConsumerControl)usage).ToString();
   323 						break;
   324 
   325 					case Hid.UsagePage.WindowsMediaCenterRemoteControl:
   326 						usageText += ((Hid.UsageTables.WindowsMediaCenterRemoteControl)usage).ToString();
   327 						break;
   328 
   329 					default:
   330 						usageText += usage.ToString("X2");
   331 						break;
   332 				}				
   333 			}
   334 
   335 			ListViewItem item = new ListViewItem(new[] { usageText, InputReportString(), UsagePage.ToString("X2"), UsageCollection.ToString("X2"), RepeatCount.ToString(), Time.ToString("HH:mm:ss:fff") });
   336             return item;
   337         }
   338 
   339     }
   340 
   341 }