首页 > 解决方案 > 发送 HidOutputReport 失败

问题描述

我想通过隐藏将输出报告发送到设备。

var device = await HidDevice.FromIdAsync(deviceDescriptor.Id, Windows.Storage.FileAccessMode.ReadWrite);
HidOutputReport outReport = device.CreateOutputReport();
byte[] buffer = new byte[] { 10, 20, 30, 40 };
DataWriter dataWriter = new DataWriter();
dataWriter.WriteBytes(buffer);
outReport.Data = dataWriter.DetachBuffer();

但它异常失败。

Message: 
    System.ArgumentException : Value does not fall within the expected range.
  Stack Trace: 
    HidOutputReport.put_Data(IBuffer value)

它有什么问题?代码是从文档中的示例复制而来的。

如果新的缓冲区长度与旧的 outReport.Data.Length 匹配,那么我在

await device.SendOutputReportAsync(outReport); 

// System.ArgumentException: 'Value does not fall within the expected range.'
 StackTrace:
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at MyMethod()

我正在尝试在 xunit 测试中运行此方法。

标签: c#uwp

解决方案


原来缓冲区中的第一个字节是reportId,它不能是随机的。将第一个字节设置为更正 Id 后,一切正常。

此外,buffer.Length 必须与 outReport.Data 的容量完全相同。


推荐阅读