FileStream ReadAsync fails on HID device while synchronous Read works

  .net, f#, hid, windows

I’m trying to read data from an USB device (a Dualshock4 controller) in F# and I am encountering some issues when trying to use ReadAsync; this is a minimized example of the code:

module Example =
  let ds4ReadBufSize = 64

  let read device =
    let buffer = Array.zeroCreate ds4ReadBufSize
    async {
      use file = File.OpenHandle(device, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite, FileOptions.Asynchronous ||| FileOptions.SequentialScan)
      use fileStream = new FileStream(file, FileAccess.Read)
      let! d = fileStream.ReadAsync(buffer, 0, buffer.Length) |> Async.AwaitTask
      printfn "%d" read
    }

When I run this code passing my device id in the form ?HID#VID_... (see below for full id) this code fails with the following error:

The parameter is incorrect. : '?HID#VID_054C&PID_09CC&MI_03#7&1F856D05&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}'
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.IO.Strategies.BufferedFileStreamStrategy.<ReadFromNonSeekableAsync>d__38.MoveNext()

If I replace the ReadAsync line with this and use the synchronous Read instead it works and I get the expected data from the controller.

let d = fileStream.Read(buffer, 0, buffer.Length)

I’m on latest Windows 10 with all updates and using .NET6. Anyone can help me with what I am missing?

Source: Windows Questions

LEAVE A COMMENT