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