HidLibrary
HidLibrary copied to clipboard
I cannot read from buffer asynchronously
class CardManager
{
public const int VendorId = 1133;
public const int ProductId = 52475;
//public byte[] data;
private static HidDevice mydevice;
//private static HidDeviceData hidDevice;
//private string devicePath;
//private const int ReportLength = 8;
//public string tString1 { get ; set; }
public HidDevice[] GetAllDevice()
{
var allDeviceList = HidDevices.Enumerate().ToArray();
HidDevice[] device = new HidDevice[allDeviceList.Length];
for (int i = 0; i < allDeviceList.Length; i++)
{
device[i] = allDeviceList[i];
}
return device;
}
public byte[] Close()
{
mydevice = HidDevices.Enumerate(VendorId, ProductId).FirstOrDefault();
mydevice.OpenDevice();
if (mydevice!= null)
{
//devicePath = mydevice.DevicePath;
//mydevice.Inserted += DeviceAttachedHandler;
//mydevice.Removed += DeviceRemovedHandler;
mydevice.MonitorDeviceEvents = true;
// mydevice.ReadReport(OnReport);
var data = new byte[9]
{
0x00,
0x15,
0x00,
0x00,
0x02,
0x19,
0x00,
0x00,
0x00
}; // Lock
mydevice.Write(data);
// mydevice.ReadReport(OnReport);
HidDeviceData carddata = mydevice.Read();
mydevice.CloseDevice();
return carddata.Data;
}
else
{
return null;
}
}
I can write and read to the buffer synchronously, but I want to listen to the device asynchronously in the background and see the incoming data(byte array). Is it possible ?
Of course it is possible, but you have to make some modifications in the HidDevices.cs code.
1) Add this method:
public async Task<HidReport> ReadReportAsync()
{
return await Task.Run(() => {
return new HidReport(Capabilities.InputReportByteLength, Read());
});
}
2) consume it as follows:
ReportDevice = Task.Run(async () => await Device?.ReadReportAsync());
ReportDevice.ContinueWith(t => OnReport(ReportDevice.Result));
Example from my flight simulator:
private void OnReport(HidReport report)
{
if (report.Data[4].IsBitSet(0)) FlapsUp?.Invoke();
if (report.Data[4].IsBitSet(1)) FlapsDown?.Invoke();
if (report.Data[4].IsBitSet(2)) LandingGearUp?.Invoke();
if (report.Data[4].IsBitSet(3)) LandingGearDown?.Invoke();
ReportDevice = Task.Run(async () => await Device?.ReadReportAsync());
ReportDevice.ContinueWith(t => OnReport(ReportDevice.Result));
}
This code is non-blocking. Don't use Begin.Invoke, use TASK.