HIDSharp: USB HID Communications in .NET

Right now I’m working on a .NET desktop application that needs to communicate with a USB device. The team has chosen to operate the device as a “HID peripheral”:http://en.wikipedia.org/wiki/USB_HID in lieu of creating our own USB driver. Avoiding a custom USB driver is great, but it has an unforeseen downside: the .NET USB libraries are not as rich as the .NET libraries for other USB device classes.

Thankfully I found “HIDSharp”:http://www.zer7.com/software/hidsharp. It took me a while to find this library, as it’s fairly low key and searching for something like “.net usb hid” results in some low-quality hits. But HIDSharp is precisely what I was looking for. With HIDSharp, I can communicate quickly with code that looks roughly like this:

public byte[] ReadModelNumber() {
  var loader = new HidDeviceLoader();
  var device = loader.GetDevices(0x1234, 0x9876).First();
  HidStream stream;
  device.TryOpen(out stream);
  
  var message = new byte[] { 0, 0xaa };
  stream.Write(message);
  return stream.Read();
}

Not bad! This is about as succinct as I’d expect in C#, and doesn’t take a lot of deep USB knowledge to understand.

One downside of HIDSharp is that it doesn’t have any built-in facilities for handling USB connect and disconnect messages. Oh well. I’m still better off than I was before.

I hope that by posting this it will be a little easier for the next person to find HIDSharp. Big thanks to “Zer”:http://www.zer7.com/, whoever you are!
 

Conversation
  • What this code will to is to send a output report (write) and and receive and input report (read). This what normally happens with a HID device. But a lot of designers choose HID, because it’s drivers “free” on Windows and the general misconception that a WinUSB device needs WHQL signed drivers. The WHQL articles from MS are written in such a way, most non-native speakers would conlude it is mandatory – it’s NOT. I have signed WinUSB drivers, that work and install without the Windows Security warning. In fact there are propriatary USB descriptors to tell Windows it is a WinUSB compatible device, an drivers will be installed behind the scene.

    Anyway, when an embedded device needs to talk to a host over USB and its not a matter of user input, HID suggest using feature reports. In a project I’m doing right now, this is the case and the read/write does nothing for me. GetFeature() and SetFeature() are the functions to look at for in HIDSharp. Thanks Matt and Joel Coenraadts (Zer).

  • Felix Collins says:

    In the license info at the top of the files the name “James F. Bellinger” appears. Maybe that is Zer?

  • Comments are closed.