我有一个 USB 设备,我需要通过 LibUsbDotNet 从中读取数据。
如果我在成功打开设备后使用以下代码...
protected UsbEndpointReader _libUsbReader = null;
protected UsbEndpointWriter _libUsbWriter = null;
.
IUsbDevice wholeUsbDevice = PhysicalLibUSBDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
// This is a "whole" USB device. Before it can be used,
// the desired configuration and interface must be selected.
// Select config #1
wholeUsbDevice.SetConfiguration(1);
// Claim interface #0.
wholeUsbDevice.ClaimInterface(0);
}
// Create the reader and writer streams
_libUsbReader = PhysicalLibUSBDevice.OpenEndpointReader(LibUsbDotNet.Main.ReadEndpointID.Ep01);
_libUsbWriter = PhysicalLibUSBDevice.OpenEndpointWriter(LibUsbDotNet.Main.WriteEndpointID.Ep02);
_libUsbReader.DataReceivedEnabled = true;
_libUsbReader.DataReceived += OnDataReceived;
_libUsbReader.ReadThreadPriority = System.Threading.ThreadPriority.Highest;
_libUsbReader.ReadBufferSize = 32;
并定义方法:
private void OnDataReceived(object sender, EndpointDataEventArgs e)
{
Console.WriteLine("Data received");
}
该事件永远不会触发。我知道我的代码正在接收数据包,因为我连接了一个 USB 分析器并且可以看到它们进入。
如果我更改代码以消除对事件回调的依赖,而是在后台线程上使用下面的循环来读取阅读器对象
while(true)
{
ErrorCode ec = ErrorCode.None;
Thread.Sleep(5);
int bytesRead;
byte[] buffer = new byte[32];
ec = _libUsbReader.Read(buffer, 1000, out bytesRead);
if(bytesRead>0) Console.WriteLine("Data Received");
}
然后一切都很好。
我已经尝试过使用我初始化的顺序、值等,但仍然没有任何乐趣。如果我使用 DataReceived 事件,谁能建议为什么事件没有触发?
我正在使用 LibUsbDotNet 2.2.8。