Common library class to receive updates from a USB HID and reconnect automatically when disconnected
This library provides AbstractHidClient
, a class that layers on top of HidSharp and provides the following useful abstractions.
- Automatically connect to a device with the given Vendor ID and Product ID
- If the device is not physically connected yet, wait for it to be available and use it automatically as soon as it's ready
- If the device disconnects, wait for it and automatically reconnect when it's available again
- Properties and events that let you observe the connection state
- Automatically run a message pump thread to receive data from the device
This common logic was extracted from Aldaviva/PowerMate so it could be reused in Aldaviva/WebScale.Net. It is intended to help developers write device-specific HID libraries without duplicating boilerplate connection management code in each project.
- Any .NET runtime that supports .NET Standard 2.0 or later:
- Operating systems:
- Windows
- MacOS
- Linux (although HidSharp seems to be unable to detect most devices on Linux)
dotnet add package HidClient
- Create a subclass of
AbstractHidClient
and stub out the mandatory overrides.public class WebScale: AbstractHidClient { public WebScale() { } public WebScale(DeviceList deviceList): base(deviceList) { } protected override int VendorId { get; } protected override int ProductId { get; } protected override void OnHidRead(byte[] readBuffer) { } }
- Override the
VendorId
andProductId
properties to return the VID and PID of your device.- In Windows, these can be found in Device Manager as the hexadecimal
VID
andPID
values under Hardware Ids. - In Linux, these can be found in the output of
lsusb
as the hexadecimalID
colon-delimited value.
protected override int VendorId { get; } = 0x2474; protected override int ProductId { get; } = 0x0550;
- In Windows, these can be found in Device Manager as the hexadecimal
- If you need to run initialization logic each time the device connects, for example resetting LED brightness that the device doesn't persist on its own, you may optionally override the
OnConnect()
method.protected override void OnConnect() { DeviceStream?.SetFeature(new byte[]{ 0x00, 0x41, 0x01, 0x01, 0x00, 0x50, 0x00, 0x00, 0x00 }); }
- Override the
OnHidRead(byte[])
method to handle the bytes read from the device.protected override void OnHidRead(byte[] readBuffer) { double ounces = BitConverter.ToInt16(readBuffer, 4) / 10.0; Weight = Force.FromOunceForce(ounces); }
- To send commands to the device, call
DeviceStream.Write(byte[])
orDeviceStream.WriteAsync(byte[], int, int)
.public void Tare() { DeviceStream?.Write(new byte[]{ 0x04, 0x01 }); }
See Aldaviva/PowerMate and Aldaviva/WebScale.Net for examples of unit testing HidClient. These test suites mock HidSharp using FakeItEasy so they don't need real devices connected to the build machines.