RemoteControlDevice.cs
author sl
Sat, 06 Dec 2014 01:09:32 +0100
changeset 20 f2b65a8318e9
parent 19 d066e3999973
child 21 fb4f80d5cf57
permissions -rw-r--r--
Cleaning up app command stuff.
     1 using System;
     2 using System.Windows.Forms;
     3 using System.Runtime.InteropServices;
     4 using System.Diagnostics;
     5 using Hid.UsageTables;
     6 using Win32;
     7 
     8 namespace Devices.RemoteControl
     9 {
    10 
    11 	public enum InputDevice
    12 	{
    13 		Key,
    14 		Mouse,
    15 		OEM
    16 	}
    17 
    18 
    19 	public enum RemoteControlButton
    20 	{
    21 		Clear,
    22 		Down,
    23 		Left,
    24 		Digit0,
    25 		Digit1,
    26 		Digit2,
    27 		Digit3,
    28 		Digit4,
    29 		Digit5,
    30 		Digit6,
    31 		Digit7,
    32 		Digit8,
    33 		Digit9,
    34 		Enter,
    35 		Right,
    36 		Up,
    37 
    38 		Back,
    39 		ChannelDown,
    40 		ChannelUp,
    41 		FastForward,
    42 		VolumeMute,
    43 		Pause,
    44 		Play,
    45         PlayPause,
    46 		Record,
    47 		PreviousTrack,
    48 		Rewind,
    49 		NextTrack,
    50 		Stop,
    51 		VolumeDown,
    52 		VolumeUp,
    53 
    54 		RecordedTV,
    55 		Guide,
    56 		LiveTV,
    57 		MoreInfo,
    58         Print,
    59 		DVDMenu,
    60 		DVDAngle,
    61 		DVDAudio,
    62 		DVDSubtitle,
    63 		MyMusic,
    64 		MyPictures,
    65 		MyVideos,
    66 		MyTV,
    67 		OEM1,
    68 		OEM2,
    69 		StandBy,
    70 		TVJump,
    71 
    72 		Unknown
    73 	}
    74 
    75 
    76 	#region RemoteControlEventArgs
    77 
    78 	public class RemoteControlEventArgs : EventArgs
    79 	{
    80         RemoteControlButton _rcb;
    81 		InputDevice _device;
    82         MceButton iMceButton;
    83         ConsumerControl iConsumerControl;
    84 
    85         public RemoteControlEventArgs(RemoteControlButton rcb, InputDevice device)
    86 		{
    87             SetNullButtons();
    88             //
    89 			_rcb = rcb;
    90 			_device = device;            
    91 		}
    92 
    93         public RemoteControlEventArgs(ConsumerControl aConsumerControl, InputDevice device)
    94         {
    95             SetNullButtons();
    96             //
    97             iConsumerControl = aConsumerControl;            
    98             _device = device;
    99         }
   100 
   101 
   102         public RemoteControlEventArgs(MceButton mce, InputDevice device)
   103         {
   104             SetNullButtons();
   105             //
   106             iMceButton = mce;            
   107             _device = device;
   108         }
   109 
   110         private void SetNullButtons()
   111         {
   112             iConsumerControl = ConsumerControl.Null;
   113             iMceButton = MceButton.Null;
   114             _rcb = RemoteControlButton.Unknown;
   115         }
   116 
   117 		public RemoteControlEventArgs()
   118 		{
   119             iMceButton = MceButton.Null;
   120 			_rcb = RemoteControlButton.Unknown;
   121 			_device = InputDevice.Key;
   122 		}
   123 
   124 		public RemoteControlButton Button
   125 		{
   126 			get { return _rcb;  }
   127 			set { _rcb = value; }
   128 		}
   129 
   130         public MceButton MceButton
   131         {
   132             get { return iMceButton; }
   133             set { iMceButton = value; }
   134         }
   135 
   136         public ConsumerControl ConsumerControl
   137         {
   138             get { return iConsumerControl; }
   139             set { iConsumerControl = value; }
   140         }
   141 
   142 		public InputDevice Device
   143 		{
   144 			get { return _device;  }
   145 			set { _device = value; }
   146 		}
   147 	}
   148 
   149 	#endregion RemoteControlEventArgs
   150 
   151 
   152 	public sealed class RemoteControlDevice
   153 	{
   154 		public delegate bool RemoteControlDeviceEventHandler(object sender, RemoteControlEventArgs e);
   155 		public event RemoteControlDeviceEventHandler ButtonPressed;
   156 
   157         /// <summary>
   158         /// Return true if the usage was processed.
   159         /// </summary>
   160         /// <param name="aUsage"></param>
   161         /// <returns></returns>
   162         public delegate bool HidUsageHandler(ushort aUsage);
   163         
   164 
   165 		//-------------------------------------------------------------
   166 		// constructors
   167 		//-------------------------------------------------------------
   168 
   169 		public RemoteControlDevice(IntPtr aHWND)
   170 		{
   171 			// Register the input device to receive the commands from the
   172 			// remote device. See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwmt/html/remote_control.asp
   173 			// for the vendor defined usage page.
   174 
   175 			RAWINPUTDEVICE[] rid = new RAWINPUTDEVICE[3];
   176 
   177 			rid[0].usUsagePage = 0xFFBC;
   178 			rid[0].usUsage = 0x88;
   179             rid[0].dwFlags = Const.RIDEV_EXINPUTSINK;
   180             rid[0].hwndTarget = aHWND;
   181 
   182 			rid[1].usUsagePage = 0x0C;
   183 			rid[1].usUsage = 0x01;
   184             rid[1].dwFlags = Const.RIDEV_EXINPUTSINK;
   185             rid[1].hwndTarget = aHWND;
   186 
   187 			rid[2].usUsagePage = 0x0C;
   188 			rid[2].usUsage = 0x80;
   189             rid[2].dwFlags = Const.RIDEV_EXINPUTSINK;
   190             rid[2].hwndTarget = aHWND;
   191 
   192 			if (!Function.RegisterRawInputDevices(rid,(uint) rid.Length,(uint) Marshal.SizeOf(rid[0])))
   193 			{
   194                 throw new ApplicationException("Failed to register raw input devices: " + Marshal.GetLastWin32Error().ToString());
   195 			}
   196 		}
   197 
   198 
   199 		//-------------------------------------------------------------
   200 		// methods
   201 		//-------------------------------------------------------------
   202 
   203 		public void ProcessMessage(Message message)
   204 		{
   205 			switch (message.Msg)
   206 			{
   207 				case Const.WM_KEYDOWN:
   208                     ProcessKeyDown(message.WParam);
   209 					break;
   210                 case Const.WM_INPUT:
   211                     //Returning zero means we processed that message.
   212                     message.Result = new IntPtr(0);
   213 					ProcessInputCommand(ref message);
   214 					break;
   215 			}
   216 
   217 		}
   218 
   219 
   220 		//-------------------------------------------------------------
   221 		// methods (helpers)
   222 		//-------------------------------------------------------------
   223 
   224 		private void ProcessKeyDown(IntPtr wParam)
   225 		{
   226 			RemoteControlButton rcb = RemoteControlButton.Unknown;
   227 
   228             switch (wParam.ToInt32())
   229 			{
   230 				case (int) Keys.Escape:
   231 					rcb = RemoteControlButton.Clear;
   232 					break;
   233 				case (int) Keys.Down:
   234 					rcb = RemoteControlButton.Down;
   235 					break;
   236 				case (int) Keys.Left:
   237 					rcb = RemoteControlButton.Left;
   238 					break;
   239 				case (int) Keys.D0:
   240 					rcb = RemoteControlButton.Digit0;
   241 					break;
   242 				case (int) Keys.D1:
   243 					rcb = RemoteControlButton.Digit1;
   244 					break;
   245 				case (int) Keys.D2:
   246 					rcb = RemoteControlButton.Digit2;
   247 					break;
   248 				case (int) Keys.D3:
   249 					rcb = RemoteControlButton.Digit3;
   250 					break;
   251 				case (int) Keys.D4:
   252 					rcb = RemoteControlButton.Digit4;
   253 					break;
   254 				case (int) Keys.D5:
   255 					rcb = RemoteControlButton.Digit5;
   256 					break;
   257 				case (int) Keys.D6:
   258 					rcb = RemoteControlButton.Digit6;
   259 					break;
   260 				case (int) Keys.D7:
   261 					rcb = RemoteControlButton.Digit7;
   262 					break;
   263 				case (int) Keys.D8:
   264 					rcb = RemoteControlButton.Digit8;
   265 					break;
   266 				case (int) Keys.D9:
   267 					rcb = RemoteControlButton.Digit9;
   268 					break;
   269 				case (int) Keys.Enter:
   270 					rcb = RemoteControlButton.Enter;
   271 					break;
   272 				case (int) Keys.Right:
   273 					rcb = RemoteControlButton.Right;
   274 					break;
   275 				case (int) Keys.Up:
   276 					rcb = RemoteControlButton.Up;
   277 					break;
   278 			}
   279 
   280 			if (this.ButtonPressed != null && rcb != RemoteControlButton.Unknown)
   281                 this.ButtonPressed(this, new RemoteControlEventArgs(rcb, InputDevice.Key));
   282 		}
   283 
   284 
   285         /// <summary>
   286         /// 
   287         /// </summary>
   288         /// <param name="aUsage"></param>
   289         private bool HidConsumerDeviceHandler(ushort aUsage)
   290         {
   291             if (aUsage == 0)
   292             {
   293                 //Just skip those
   294                 return false;
   295             }
   296 
   297             if (Enum.IsDefined(typeof(ConsumerControl), aUsage) && aUsage != 0) //Our button is a known consumer control
   298             {
   299                 if (this.ButtonPressed != null)
   300                 {
   301                     return this.ButtonPressed(this, new RemoteControlEventArgs((ConsumerControl)aUsage, InputDevice.OEM));
   302                 }
   303                 return false;
   304             }
   305             else
   306             {
   307                 Debug.WriteLine("Unknown Consumer Control!");
   308                 return false;
   309             }
   310         }
   311 
   312         /// <summary>
   313         /// 
   314         /// </summary>
   315         /// <param name="aUsage"></param>
   316         private bool HidMceRemoteHandler(ushort aUsage)
   317         {
   318             if (aUsage == 0)
   319             {
   320                 //Just skip those
   321                 return false;
   322             }
   323 
   324 
   325             if (Enum.IsDefined(typeof(MceButton), aUsage) && aUsage != 0) //Our button is a known MCE button
   326             {
   327                 if (this.ButtonPressed != null)
   328                 {
   329                     return this.ButtonPressed(this, new RemoteControlEventArgs((MceButton)aUsage, InputDevice.OEM));                    
   330                 }
   331                 return false;
   332             }
   333             else
   334             {
   335                 Debug.WriteLine("Unknown MCE button!");
   336                 return false;
   337             }
   338         }
   339 
   340 
   341 		private void ProcessInputCommand(ref Message message)
   342 		{
   343             //We received a WM_INPUT message
   344             Debug.WriteLine("================WM_INPUT================");
   345 
   346             //Check if we received this message while in background or foreground
   347             if (Macro.GET_RAWINPUT_CODE_WPARAM(message.WParam) == Const.RIM_INPUT)
   348             {
   349                 Debug.WriteLine("================FOREGROUND");
   350             }
   351             else if (Macro.GET_RAWINPUT_CODE_WPARAM(message.WParam) == Const.RIM_INPUTSINK)
   352             {
   353                 Debug.WriteLine("================BACKGROUND");
   354             }
   355 
   356             //Declare some pointers
   357             IntPtr rawInputBuffer = IntPtr.Zero;
   358             //My understanding is that this is basically our HID descriptor
   359             IntPtr preParsedData = IntPtr.Zero;
   360 
   361             try
   362             {
   363                 //Fetch raw input
   364                 RAWINPUT rawInput = new RAWINPUT();
   365                 if (!RawInput.GetRawInputData(message.LParam, ref rawInput, ref rawInputBuffer))
   366                 {
   367                     return;
   368                 }
   369 
   370                 //Fetch device info
   371                 RID_DEVICE_INFO deviceInfo = new RID_DEVICE_INFO();
   372                 if (!RawInput.GetDeviceInfo(rawInput.header.hDevice, ref deviceInfo))
   373                 {
   374                     return;
   375                 }
   376                
   377 
   378                 if (rawInput.header.dwType == Const.RIM_TYPEHID)  //Check that our raw input is HID                        
   379                 {
   380                     Debug.WriteLine("WM_INPUT source device is HID.");
   381                     //Get Usage Page and Usage
   382                     Debug.WriteLine("Usage Page: 0x" + deviceInfo.hid.usUsagePage.ToString("X4") + " Usage ID: 0x" + deviceInfo.hid.usUsage.ToString("X4"));
   383 
   384 
   385                     preParsedData = RawInput.GetPreParsedData(rawInput.header.hDevice);
   386 
   387                     //
   388                     HidUsageHandler usagePageHandler=null;
   389 
   390                     //Check if this an MCE remote HID message
   391                     if (deviceInfo.hid.usUsagePage == (ushort)Hid.UsagePage.MceRemote && deviceInfo.hid.usUsage == (ushort)Hid.UsageId.MceRemoteUsage)
   392                     {                        
   393                         usagePageHandler = HidMceRemoteHandler;
   394                     }
   395                     //Check if this is a consumer control HID message
   396                     else if (deviceInfo.hid.usUsagePage == (ushort)Hid.UsagePage.Consumer && deviceInfo.hid.usUsage == (ushort)Hid.UsageId.ConsumerControl)
   397                     {
   398                         usagePageHandler = HidConsumerDeviceHandler;
   399                     }
   400                     //Unknown HID message
   401                     else
   402                     {
   403                         Debug.WriteLine("Unknown HID message.");
   404                         return;
   405                     }
   406 
   407                     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
   408                         && rawInput.hid.dwCount > 0))    //Check that we have at least one HID msg
   409                     {
   410                         return;
   411                     }
   412 
   413 
   414                     //Allocate a buffer for one HID input
   415                     byte[] hidInputReport = new byte[rawInput.hid.dwSizeHid];
   416 
   417                     Debug.WriteLine("Raw input contains " + rawInput.hid.dwCount + " HID input report(s)");
   418 
   419                     //For each HID input report in our raw input
   420                     for (int i = 0; i < rawInput.hid.dwCount; i++)
   421                     {
   422                         //Compute the address from which to copy our HID input
   423                         int hidInputOffset = 0;
   424                         unsafe
   425                         {
   426                             byte* source = (byte*)rawInputBuffer;
   427                             source += sizeof(RAWINPUTHEADER) + sizeof(RAWHID) + (rawInput.hid.dwSizeHid * i);
   428                             hidInputOffset = (int)source;
   429                         }
   430 
   431                         //Copy HID input into our buffer
   432                         Marshal.Copy(new IntPtr(hidInputOffset), hidInputReport, 0, (int)rawInput.hid.dwSizeHid);
   433 
   434                         //Print HID input report in our debug output
   435                         string hidDump = "HID input report: ";
   436                         foreach (byte b in hidInputReport)
   437                         {
   438                             hidDump += b.ToString("X2");
   439                         }
   440                         Debug.WriteLine(hidDump);
   441                         
   442                         //Proper parsing now
   443                         uint usageCount = 1; //Assuming a single usage per input report. Is that correct?
   444                         Win32.USAGE_AND_PAGE[] usages = new Win32.USAGE_AND_PAGE[usageCount];
   445                         Win32.HidStatus status = Win32.Function.HidP_GetUsagesEx(Win32.HIDP_REPORT_TYPE.HidP_Input, 0, usages, ref usageCount, preParsedData, hidInputReport, (uint)hidInputReport.Length);
   446                         if (status != Win32.HidStatus.HIDP_STATUS_SUCCESS)
   447                         {
   448                             Debug.WriteLine("Could not parse HID data!");
   449                         }
   450                         else
   451                         {
   452                             Debug.WriteLine("UsagePage: 0x" + usages[0].UsagePage.ToString("X4"));
   453                             Debug.WriteLine("Usage: 0x" + usages[0].Usage.ToString("X4"));
   454                             //Call on our Usage Page handler
   455                             usagePageHandler(usages[0].Usage);
   456                         }
   457                     }
   458 
   459                 }
   460                 else if (rawInput.header.dwType == Const.RIM_TYPEMOUSE)
   461                 {
   462                     Debug.WriteLine("WM_INPUT source device is Mouse.");
   463                     // do mouse handling...
   464                 }
   465                 else if (rawInput.header.dwType == Const.RIM_TYPEKEYBOARD)
   466                 {
   467                     Debug.WriteLine("WM_INPUT source device is Keyboard.");
   468                     // do keyboard handling...
   469 
   470                 }
   471             }
   472             finally
   473             {
   474                 //Always executed when leaving our try block
   475                 Marshal.FreeHGlobal(rawInputBuffer);
   476                 Marshal.FreeHGlobal(preParsedData);
   477             }
   478 		}
   479 	}
   480 }