Topic: HIDSharp ASync Stream Reading
First of all, thank you for making this amazing library, and for putting it out there. Looks extremely professional and well designed!
I'm new to HID communication, but not to programming and hardware communication (done quite a bit of Serial Port and MIDI stuff in .NET)
I'm trying to figure out the "proper" way to do communication with my HID device. What I have made through trial-and-error works, but I'm sure it's not "correct".
Here's a sample of my code:
HidSharp.HidDevice USBDevice;
HidSharp.DeviceList USBList;
HidSharp.HidStream USBStream;
IAsyncResult result;
byte[] testUSBHeader = new byte[] { 01, 14, 0x0a, 0, 0x0b, 0, 0x32, 0, 2, 0, 1, 0, 0x10, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
byte[] USBBuffer;
private void btnConnect_Click(object sender, EventArgs e)
{
USBList = DeviceList.Local;
USBDevice = USBList.GetHidDevices(0x0483,0xA0E0).First();
if (USBDevice != null && USBDevice.TryOpen(out USBStream))
{
USBStream.ReadTimeout = 32767;
textBox1.Text = USBDevice.DevicePath;
btnConnect.Text = "Connected!";
USBBuffer = new byte[65];
result = USBStream.BeginRead(USBBuffer, 0, 64, new AsyncCallback(BytesReady), null);
}
}
private void btnSend_Click(object sender, EventArgs e)
{
byte[] BytesToSend = new byte[65];
Array.Copy(testUSBHeader, 0, BytesToSend, 1, testUSBHeader.Length);
BytesToSend[0] = 0;
USBStream.Write(BytesToSend, 0, 65);
}
private void BytesReady(IAsyncResult result)
{
try
{
Debug.WriteLine($"Bytes Read = {USBStream.EndRead(result)}");
if (listBox1.InvokeRequired)
listBox1.BeginInvoke((MethodInvoker)delegate () { listBox1.Items.Add(BitConverter.ToString(USBBuffer)); ; });
else
listBox1.Items.Add(BitConverter.ToString(USBBuffer));
result = USBStream.BeginRead(USBBuffer, 0, 64, new AsyncCallback(BytesReady), null);
}
catch (Exception)
{
}
}
private void btnStop_Click(object sender, EventArgs e)
{
USBStream.EndRead(result);
USBStream.Dispose();
}
}
Some things I don't quite understand:
Why do I need to call BeginRead inside BytesReady? It seems if I don't, no more reads happen. I thought BeginRead would continue until Cancelled. I've tried it with and without EndRead, it only reads once unless I call it again.
How do I close the stream and stop reading? When I call USBStream.Close() or USBStream.Dispose(), it calls BytesReady continuously. The only way I can get it to stop is with the try/catch on EndRead, so it doesn't call BeginRead again.
What is a better way to do what I'm trying to do?
Thank you for your help and advice!