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