C# – Unable to Write to a USB HID device

chidusb

I'm trying to write to a USB HID device.

My code used to work on 32bit XP, but for badness I'm trying on 64bit Windows 7. I can find the device, get it's path, use CreateFile win32 API function to open a handle & pass this to FileStream. Everything seems fine so far. I then write the data to the stream & the USB device does nothing.

How can I find out why it's not doing anything & then hopefully make it do something?

This is my import signature:

    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern SafeFileHandle CreateFile(
        [MarshalAs(UnmanagedType.LPStr)] string name,
        uint access,
        int shareMode,
        IntPtr security,
        int creationFlags,
        int attributes,
        IntPtr template);

Calling the function:

var handle = usb.Win32Wrapper.CreateFile(path, usb.Win32Wrapper.GENERIC_READ | usb.Win32Wrapper.GENERIC_WRITE, 0, IntPtr.Zero, usb.Win32Wrapper.OPEN_EXISTING, usb.Win32Wrapper.FILE_FLAG_OVERLAPPED, IntPtr.Zero);

Opening the FileStream to the device:

_main = new FileStream(handle, FileAccess.Write, 1, true);

and finally writing to the file:

_main.Write(buffer,0,buffer.Length);

Best Answer

It's hard to say without knowing the specifics of your device.

Have you confirmed you can communicate with the device (hidapi, HIDSharp, etc.)? There's nothing saying a USB HID device can't reply with NAKs until the end of time, in which case your send will never finish.

The issues I ran into when I first trying to communicate over HID (I've been using Windows 7 for a while, so I can't say if XP has the same restrictions):

(1) Make sure you include a Report ID byte. Even if your device does not support one, Windows needs a Report ID of 0.

(2) On Windows your buffer needs to be the same length as the maximum report. So for example, if your report is 48 bytes, you need to write 49 bytes (start with a Report ID always). I seem to recall getting a write error if I didn't do this.

Since you mention 64-bit Windows...

(3) One 64-bit Windows specific issue I ran into was that (as of .NET 2.0 and 4.0) 64-bit P/Invoke does not treat the OVERLAPPED structure (or NativeOverlapped for that matter) as blittable. Therefore if you use 'ref OVERLAPPED' it will make a copy, P/Invoke, and copy back. Overlapped operations assume the memory doesn't move, so this is a real problem -- GetOverlappedResult will be flat-out wrong, you'll get subtle memory corruption, etc. You can solve this with fixed() or stackalloc -- it's one reminder ref T isn't identical to T*, even if the struct is allocated on the stack.

Hope at least one of these three resolves your problem. :)

James

Related Topic