/// <summary> /// This callback only increments the total number of events received and prints it /// /// This method is called whenever the device's state changes and sends a report. Since all input reports share the same event in /// HidDevice, the app needs to get the HidInputReport from eventArgs.Report and compare report ids and usages with the desired /// report. /// </summary> /// <param name="sender">HidDevice that the event is being raised from</param> /// <param name="eventArgs">Contains the HidInputReport that caused the event to raise</param> private async void OnInputReportEvent(HidDevice sender, HidInputReportReceivedEventArgs eventArgs) { // If we navigated away from this page, we don't need to process this event // This also prevents output from spilling into another page if (!navigatedAway) { numInputReportEventsReceived++; // The data from the InputReport HidInputReport inputReport = eventArgs.Report; IBuffer buffer = inputReport.Data; totalNumberBytesReceived += buffer.Length; // Create a DispatchedHandler for the because we are interracting with the UI directly and the // thread that this function is running on may not be the UI thread; if a non-UI thread modifies // the UI, an exception is thrown await rootPage.Dispatcher.RunAsync( CoreDispatcherPriority.Normal, new DispatchedHandler(() => { // If we navigated away from this page, do not print anything. The dispatch may be handled after // we move to a different page. if (!navigatedAway) { rootPage.NotifyUser( "Total number of input report events received: " + numInputReportEventsReceived.ToString() + "\nTotal number of bytes received: " + totalNumberBytesReceived.ToString(), NotifyType.StatusMessage); } })); } }
public async void Run(IBackgroundTaskInstance taskInstance) { var task = GetHidDevices(); task.Wait(); device = task.Result; if (device != null) { var cmd = GetCommandBytes("PIRI"); int requestCount = (cmd.Length / 8) //foreach (var message in Split(cmd, 8)) //{ // DataWriter dataWriter = new DataWriter(); // //dataWriter.WriteBytes(message.ToArray())); // var report = device.CreateOutputReport(); // report.Data = dataWriter.DetachBuffer(); // await device.SendOutputReportAsync(report); //} HidInputReport inReport = await device.GetInputReportAsync(); if (inReport != null) { UInt16 id = inReport.Id; var bytes = new byte[4]; DataReader dataReader = DataReader.FromBuffer(inReport.Data); dataReader.ReadBytes(bytes); //Encoding.ASCII.GetString(report.Data); } } }
private void GetHidReport(HidInputReportReceivedEventArgs args) { // For now there is only one data type HidInputReport rpt = args.Report; IBuffer buff = rpt.Data; DataReader dr = DataReader.FromBuffer(buff); byte[] bytes = new byte[rpt.Data.Length]; dr.ReadBytes(bytes); Motus_1_RawDataPacket packet = new Motus_1_RawDataPacket(); try { // Have to remove a bonus byte on the payload byte[] parsed = new byte[bytes.Length - 1]; for (int i = 0; i < parsed.Length; i++) { parsed[i] = bytes[i + 1]; } packet.Serialize(parsed); byte[] stream = new byte[packet.ExpectedLen + DataPacket.NumOverHeadBytes]; packet.SerializeToStream(stream, 0); SetData(stream); } catch (ArgumentException e0) { LogMessage(e0.Message + e0.StackTrace); } catch (IndexOutOfRangeException e1) { LogMessage(e1.Message + e1.StackTrace); } }
private void Device_InputReportReceived(HidDevice sender, HidInputReportReceivedEventArgs args) { HidInputReport report = args.Report; IBuffer buffer = report.Data; int ms = DateTime.Now.Subtract(now).Milliseconds; Debug.WriteLine("RX - {0} bytes received in {1}ms.", buffer.Length, ms); Debug.WriteLine(BitConverter.ToString(report.Data.ToArray())); }
/// <summary> /// Parses the positions from the report. /// </summary> /// <param name="report">A <see cref="HidInputReport"/> object used on the parsing.</param> /// <returns>The parsed <see cref="GazeHidPositions"/> from the report.</returns> public GazeHidPositions GetGazeHidPositions(HidInputReport report) { return(new GazeHidPositions { LeftEyePosition = this._leftEyePositionParser.GetPosition(report), RightEyePosition = this._rightEyePositionParser.GetPosition(report), HeadPosition = this._headPositionParser.GetPosition(report), HeadRotation = this._headRotationParser.GetRotation(report) }); }
// Find HID devices. private async void EnumerateHidDevices() { // Microsoft Input Configuration Device. ushort vendorId = 0x045E; ushort productId = 0x07CD; ushort usagePage = 0x000D; ushort usageId = 0x000E; // Create the selector. string selector = HidDevice.GetDeviceSelector(usagePage, usageId, vendorId, productId); // Enumerate devices using the selector. var devices = await DeviceInformation.FindAllAsync(selector); if (devices.Any()) { // At this point the device is available to communicate with // So we can send/receive HID reports from it or // query it for control descriptions. CountDevices = "HID devices found: " + devices.Count; // Open the target HID device. HidDevice device = await HidDevice.FromIdAsync(devices.ElementAt(0).Id, FileAccessMode.ReadWrite); if (device != null) { // Input reports contain data from the device. device.InputReportReceived += async(sender, args) => { HidInputReport inputReport = args.Report; IBuffer buffer = inputReport.Data; // Create a DispatchedHandler as we are interracting with the UI directly and the // thread that this function is running on might not be the UI thread; // if a non-UI thread modifies the UI, an exception is thrown. /*await this.Dispatcher.RunAsync( * CoreDispatcherPriority.Normal, * new DispatchedHandler(() => * { * CountDevices += "\nHID Input Report: " + inputReport.ToString() + * "\nTotal number of bytes received: " + buffer.Length.ToString(); * }));*/ }; } } else { // There were no HID devices that met the selector criteria. CountDevices = "HID device not found"; } }
public async Task <Measurement> ReadState() { if (myDevice != null) { // construct a HID output report to send to the device // HidOutputReport outReport = device.CreateOutputReport(); /// Initialize the data buffer and fill it in byte[] buffer = new byte[] { 10, 20, 30, 40 }; DataWriter dataWriter = new DataWriter(); // try { HidInputReport inReport = await myDevice.GetInputReportAsync(05); if (inReport != null) { UInt16 id = inReport.Id; Debug.WriteLine("inReport.Id" + id); var bytes = new byte[32]; DataReader dataReader = DataReader.FromBuffer(inReport.Data); dataReader.ReadBytes(bytes); return(CreateRealMeasurement(bytes)); // Info.Text += Environment.NewLine + "co2 = " + state.co2.ToString(); } else { // this.NotifyUser("Invalid input report received"); Debug.WriteLine("Invalid input report received"); } } catch { myDevice = null; if (Removed != null) { Removed(); } Debug.WriteLine("краааш"); } finally { } return(CreateRandomMeasurement()); } else { //this.NotifyUser("device is NULL"); Debug.WriteLine("device is NULL"); } return(CreateRandomMeasurement()); }
public async void RefreshData() { /* Ensure the descriptors are properly sorted. */ Array.Sort(CyberPowerDesc); string selector = Windows.Devices.HumanInterfaceDevice.HidDevice.GetDeviceSelector(USB_POWER_PAGE, USB_POWER_UPS_ID, CYBER_POWER_VID, CYBER_POWER_PID); // Enumerate devices using the selector. var devices = await DeviceInformation.FindAllAsync(selector); if (devices.Any()) { // Open the target HID device. HidDevice device = await HidDevice.FromIdAsync(devices.ElementAt(0).Id, FileAccessMode.Read); if (device != null) { int desc_num = 0; while (desc_num < CyberPowerDesc.Length) { ushort reportID = CyberPowerDesc[desc_num].ReportID; HidInputReport inputReport = null; inputReport = await device.GetInputReportAsync(reportID); IBuffer buffer = inputReport.Data; byte[] my_bytes = new byte[buffer.Length]; DataReader d = DataReader.FromBuffer(buffer); d.ReadBytes(my_bytes); while ((desc_num < CyberPowerDesc.Length) && (CyberPowerDesc[desc_num].ReportID == reportID)) { CyberPowerDesc[desc_num++].Data = my_bytes; } } } else { throw new Exception("No devices found."); } } else { throw new Exception("No devices found."); } upsDataEvent.Set(); }
private void CurrentDevice_InputReportReceived(HidDevice sender, HidInputReportReceivedEventArgs args) { HidInputReport report = args.Report; try { processReport(report); }catch (Exception e) { #if DEBUG System.Diagnostics.Debug.WriteLine(e.Message); #endif } }
private async void OnGeneralInterruptEvent(HidDevice sender, HidInputReportReceivedEventArgs eventArgs) { // Retrieve the sensor data HidInputReport inputReport = eventArgs.Report; IBuffer buffer = inputReport.Data; DataReader dr = DataReader.FromBuffer(buffer); byte[] BufferIn = new byte[inputReport.Data.Length]; dr.ReadBytes(BufferIn); // Wait for when UI is ready to be updated await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { { // Channel1 byte[] vIn = new byte[] { BufferIn[1], BufferIn[2], BufferIn[3], BufferIn[4] }; long result = BitConverter.ToInt32(vIn, 0); Channel1.Text = Convert.ToString(result); // Channel2 vIn = new byte[] { BufferIn[5], BufferIn[6], BufferIn[7], BufferIn[8] }; result = BitConverter.ToInt32(vIn, 0); Channel2.Text = Convert.ToString(result); // Channel3 vIn = new byte[] { BufferIn[9], BufferIn[10], BufferIn[11], BufferIn[12] }; result = BitConverter.ToInt32(vIn, 0); Channel3.Text = Convert.ToString(result); // Channel4 vIn = new byte[] { BufferIn[13], BufferIn[14], BufferIn[15], BufferIn[16] }; result = BitConverter.ToInt32(vIn, 0); Channel4.Text = Convert.ToString(result); // Channel5 vIn = new byte[] { BufferIn[17], BufferIn[18], BufferIn[19], BufferIn[20] }; result = BitConverter.ToInt32(vIn, 0); Channel5.Text = Convert.ToString(result); // Channel6 vIn = new byte[] { BufferIn[21], BufferIn[22], BufferIn[23], BufferIn[24] }; result = BitConverter.ToInt32(vIn, 0); Channel6.Text = Convert.ToString(result); } }); }
public Vector3?GetPosition(HidInputReport report) { Vector3 result = new Vector3(); if (_X != null && _Y != null && _Z != null && _usage != 0x0000) { result.X = report.GetNumericControlByDescription(_X).Value; result.Y = report.GetNumericControlByDescription(_Y).Value; result.Z = report.GetNumericControlByDescription(_Z).Value; return(result); } return(null); }
private void ProcessInputForMap(HidInputReport report, HIDButtonMap buttonMap, ref ButtonStates newState) { foreach (var mappingItem in buttonMap) { HIDMapping mapping = mappingItem.Value; if (mapping.IsNumeric) { HidNumericControl control = report.GetNumericControl(mapping.UsagePage, mapping.UsageId); ushort value = (ushort)control.Value; if (!this.CheckDeadzone(control.ControlDescription, control)) { continue; } if (mapping.UsagePage == 0x01 && mapping.UsageId == 0x39) { // dpad if ((mapping.Direction == DPadDirection.Down && value >= 3 && value <= 5) || (mapping.Direction == DPadDirection.Left && value >= 5 && value <= 7) || (mapping.Direction == DPadDirection.Up && (value == 7 || value == 0 || value == 1)) || (mapping.Direction == DPadDirection.Right && value >= 1 && value <= 3) ) { this.setButtonState(mappingItem.Key, ref newState); } } else { // axis ushort center = NumericCenters[mapping.UsagePage]; if ((value < center && mapping.Sign < 0) || (value > center && mapping.Sign > 0)) { this.setButtonState(mappingItem.Key, ref newState); } } } else { HidBooleanControl control = report.GetBooleanControl(mapping.UsagePage, mapping.UsageId); if (control.IsActive) { this.setButtonState(mappingItem.Key, ref newState); } } } }
public void Dispose() { if (this.currentDevice != null) { try { this.currentDevice.InputReportReceived -= CurrentDevice_InputReportReceived; }catch (Exception e) { #if DEBUG System.Diagnostics.Debug.WriteLine("INFO: " + e.Message); #endif } this.lastReport = null; this.currentDevice.Dispose(); this.currentDevice = null; } }
public T GetDataFromHidInputReport(HidInputReport HidReport) { var outputData = new T(); foreach (var data in DataMap) { PropertyInfo prop = data.Property; if (prop.PropertyType == typeof(bool)) { prop.SetValue(outputData, HidReport.GetBooleanControl(data.UsagePage, data.UsageId).IsActive); } else if (prop.PropertyType == typeof(float)) { prop.SetValue(outputData, HidReport.GetNumericControl(data.UsagePage, data.UsageId).ScaledValue); } } return(outputData); }
private void Device_InputReportReceived(HidDevice sender, HidInputReportReceivedEventArgs args) { // Retrieve the sensor data HidInputReport inputReport = args.Report; IBuffer buffer = inputReport.Data; DataReader dr = DataReader.FromBuffer(buffer); byte[] bytes = new byte[inputReport.Data.Length]; dr.ReadBytes(bytes); if (bytes.Length <= 0) { return; } lock (this) { // Clear the control states OnUpdate(); // Report button controls foreach (var button in args.Report.ActivatedBooleanControls) { ReportControl((int)button.Id, 1f); } // Report numeric controls int[] specialControls = GetNumericControls(gamepadType); for (int i = 0; i < specialControls.Length; ++i) { HidNumericControl ctrl = args.Report.GetNumericControl(1, (ushort)specialControls[i]); if (ctrl != null) { ReportControl(specialControls[i], ctrl.Value); } } } }
public Vector3?GetRotation(HidInputReport report) { Vector3?result = null; if (_X != null && _Y != null && _Z != null && _usage != 0x0000) { var descX = report.GetNumericControlByDescription(_X); var descY = report.GetNumericControlByDescription(_Y); var descZ = report.GetNumericControlByDescription(_Z); var controlDescX = descX.ControlDescription; var controlDescY = descX.ControlDescription; var controlDescZ = descX.ControlDescription; if ((controlDescX.LogicalMaximum < descX.Value || controlDescX.LogicalMinimum > descX.Value) || (controlDescY.LogicalMaximum < descY.Value || controlDescY.LogicalMinimum > descY.Value) || (controlDescZ.LogicalMaximum < descZ.Value || controlDescZ.LogicalMinimum > descZ.Value)) { // One of the values is outside of the valid range. } else { result = new Vector3 { X = descX.Value, Y = descY.Value, Z = descZ.Value }; } } return(result); }
/// <summary> /// Parses the rotation from the report. /// </summary> /// <param name="report">A <see cref="HidInputReport"/> object used on the parsing.</param> /// <returns>The parsed <see cref="GazeHidPosition"/> from the report.</returns> public GazeHidPosition GetRotation(HidInputReport report) { GazeHidPosition result = null; if (_x != null && _y != null && _z != null && _usage != 0x0000) { var descX = report.GetNumericControlByDescription(_x); var descY = report.GetNumericControlByDescription(_y); var descZ = report.GetNumericControlByDescription(_z); var controlDescX = descX.ControlDescription; var controlDescY = descY.ControlDescription; var controlDescZ = descZ.ControlDescription; if ((controlDescX.LogicalMaximum < descX.ScaledValue || controlDescX.LogicalMinimum > descX.ScaledValue) || (controlDescY.LogicalMaximum < descY.ScaledValue || controlDescY.LogicalMinimum > descY.ScaledValue) || (controlDescZ.LogicalMaximum < descZ.ScaledValue || controlDescZ.LogicalMinimum > descZ.ScaledValue)) { // One of the values is outside of the valid range. } else { result = new GazeHidPosition { X = descX.ScaledValue, Y = descY.ScaledValue, Z = descZ.ScaledValue }; } } return(result); }
private void ReadingFinished(HidDevice sender, HidInputReportReceivedEventArgs args) { NativeDevice.InputReportReceived -= ReadingFinished; ReadReport = args.Report; WaitingOnRead = false; }
/// <summary> /// This method is called each time the motion sensor forwards data to the host. /// /// Note that reading is relatively straight forward and follows the general WinRT paradigm of using events args /// and reading from buffers. /// </summary> /// <param name="sender">The hidDevice that raised the event (the one that received the interrupt)</param> /// <param name="eventArgs">Contains the HidInputReport that caused the interrupt</param> private async void OnGeneralInterruptEvent(HidDevice sender, HidInputReportReceivedEventArgs eventArgs) { // Retrieve the sensor data HidInputReport inputReport = eventArgs.Report; IBuffer buffer = inputReport.Data; DataReader dr = DataReader.FromBuffer(buffer); byte[] bytes = new byte[inputReport.Data.Length]; dr.ReadBytes(bytes); // Set the video length and delay values. TimeSpan length = TimeSpan.FromSeconds(5); // Video length 5 seconds TimeSpan delay = TimeSpan.FromSeconds(15); // Pause or delay 15 seconds TimeSpan radioDelay = TimeSpan.FromMilliseconds(250); // Duration of radio-button highlight await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // Briefly check the radio button to show that an event was fired radio1.IsChecked = true; }); // Create a threadpool timer which toggles the radio button on for the radioDelay interval ThreadPoolTimer RadioButtonTimer = ThreadPoolTimer.CreateTimer( async(source) => { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // Radio button is unchecked once duration expires radio1.IsChecked = false; }); }, radioDelay); // The first byte contains the motion data if ((bytes[1] == 1) && !Capture) { Capture = true; // Create a threadpool timer which stops the video capture after "length" seconds ThreadPoolTimer VideoStopTimer = ThreadPoolTimer.CreateTimer( async(source) => { await CaptureMgr.StopRecordAsync(); await rootPage.Dispatcher.RunAsync( CoreDispatcherPriority.Normal, new DispatchedHandler(() => { rootPage.NotifyUser("Video capture concluded.", NotifyType.StatusMessage); })); }, length); // Create a threadpool timer which prevents false captures by pausing detection for "delay" seconds ThreadPoolTimer CapturePauseTimer = ThreadPoolTimer.CreateTimer( async(source) => { Capture = false; await rootPage.Dispatcher.RunAsync( CoreDispatcherPriority.Normal, new DispatchedHandler(() => { rootPage.NotifyUser("Presence sensor enabled.", NotifyType.StatusMessage); })); }, delay); await rootPage.Dispatcher.RunAsync( CoreDispatcherPriority.Normal, new DispatchedHandler(() => { rootPage.NotifyUser("Video capture started.", NotifyType.StatusMessage); })); String fileName; fileName = VIDEO_FILE_NAME; StorageFile = await Windows.Storage.KnownFolders.VideosLibrary.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.GenerateUniqueName); MediaEncodingProfile recordProfile = MediaEncodingProfile.CreateMp4(Windows.Media.MediaProperties.VideoEncodingQuality.Auto); await CaptureMgr.StartRecordToStorageFileAsync(recordProfile, StorageFile); } }
private void processReport(HidInputReport report) { if (this.lastReport != null) { if (this.SetupMode) { foreach (var boolControl in report.ActivatedBooleanControls) { var lastControl = this.lastReport.GetBooleanControl(boolControl.UsagePage, boolControl.UsageId); if (boolControl.IsActive && !lastControl.IsActive) { HIDMapping mapping = new HIDMapping() { DisplayName = String.Format(this.resources.GetString("hidButtonDescription"), boolControl.Id), UsagePage = boolControl.UsagePage, UsageId = boolControl.UsageId, IsNumeric = false }; this.ControlChanged(mapping); } } foreach (var numControlDesc in this.numControlDescs) { var numControl = report.GetNumericControlByDescription(numControlDesc); var lastNumControl = this.lastReport.GetNumericControlByDescription(numControlDesc); if (numControl != null && lastNumControl != null && numControl.Value != lastNumControl.Value) { if (CheckDeadzone(numControlDesc, numControl) && !CheckDeadzone(lastNumControl.ControlDescription, lastNumControl)) { ushort center = NumericCenters[numControl.UsagePage]; short axisSign = (short)Math.Sign((short)numControl.Value - (short)center); String sign = string.Empty; if (center != 0) { sign = axisSign < 0 ? "-" : "+"; } String displayName = String.Format(this.axisString, sign, numControl.Id); DPadDirection direction = default(DPadDirection); if (numControlDesc.UsagePage == 0x01 && numControlDesc.UsageId == 0x39) { switch (numControl.Value) { case 0: direction = DPadDirection.Up; displayName = this.hidDPadUp; break; case 2: direction = DPadDirection.Right; displayName = this.hidDPadRight; break; case 4: direction = DPadDirection.Down; displayName = this.hidDPadDown; break; case 6: direction = DPadDirection.Left; displayName = this.hidDPadLeft; break; } } HIDMapping mapping = new HIDMapping() { DisplayName = displayName, UsagePage = numControl.UsagePage, UsageId = numControl.UsageId, Sign = axisSign, Direction = direction, IsNumeric = true }; this.ControlChanged(mapping); } } } } else { //ButtonStates newState = new ButtonStates(); //ProcessInputForMap(report, this.mapping, ref newState); //ProcessInputForMap(report, this.mappingAlternative, ref newState); //this.state.buttons = newState; } } this.lastReport = report; }