[英]Communicate with USB device in C# using LibUsbDotNet
0) 在 Windows7 Ultimate 32 位下工作并安装 linusb-win32-dlevel-filter 1.2.6.0。
1)我尝试了libusb dotnet的showinfo示例并得到以下结果,[请查看结果(1-结果)]
2) 之后我尝试读取(轮询)libusb 的示例,但在“ec = reader.Read(readBuffer, 1000, out bytesRead);”行出现错误错误是“win32error:no more byte!” [请看代码(2-代码)]
这个错误是什么意思,我该如何解决? 实际上我是usb设备通信的新手,如果对使用c#进行usb设备通信有任何想法,请帮助我
1-结果:-
长度:18 描述符类型:设备 BcdUsb:0x0110 类:通信子类:0x00 协议:0x00 MaxPacketSize0:64 供应商 ID:0x11CA 产品 ID:0x0241 BcdDevice:0x0100 制造商字符串索引:1 产品字符串索引:2 序列字符串索引:3 配置计数:1 制造商字符串:VeriFone Inc 产品字符串:Trident USB设备 1.1 序列号:
长度:9 DescriptorType:配置 TotalLength:67 InterfaceCount:2 ConfigID:1 StringIndex:0 Attributes:0xC0 MaxPower:25 ConfigString:
长度:7 描述符类型:端点 EndpointID:0x85 属性:0x03 MaxPacketSize:16 间隔:0 刷新:0 同步地址:0x00
长度:9 描述符类型:接口接口 ID:1 备用 ID:0 端点计数:2 类:数据子类:0x00 协议:0x00 字符串索引:0 接口字符串:
长度:7 描述符类型:端点 EndpointID:0x81 属性:0x02 MaxPacketSize:64 间隔:0 刷新:0 同步地址:0x00
长度:7 描述符类型:端点 EndpointID:0x03 属性:0x02 MaxPacketSize:32 间隔:0 刷新:0 同步地址:0x00
2-代码:-
公共静态 UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(4554, 577);
ErrorCode ec = ErrorCode.None;
try
{
// Find and open the usb device.
MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
// If the device is open and ready
if (MyUsbDevice == null) throw new Exception("Device Not Found.");
IUsbDevice wholeUsbDevice = MyUsbDevice 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);
}
// open read endpoint 1.
UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
byte[] readBuffer = new byte[1024];
while (ec == ErrorCode.None)
{
int bytesRead;
// If the device hasn't sent data in the last 5 seconds,
// a timeout error (ec = IoTimedOut) will occur.
ec = reader.Read(readBuffer, 5000, out bytesRead);
if (bytesRead == 0) throw new Exception(string.Format("{0}:No more bytes!", ec));
Console.WriteLine("{0} bytes read", bytesRead);
// Write that output to the console.
Console.Write(Encoding.Default.GetString(readBuffer, 0, bytesRead));
}
Console.WriteLine("\r\nDone!\r\n");
}
catch (Exception ex)
{
Console.WriteLine();
Console.WriteLine((ec != ErrorCode.None ? ec + ":" : String.Empty) + ex.Message);
}
finally
{
if (MyUsbDevice != null)
{
if (MyUsbDevice.IsOpen)
{
IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
// Release interface #0.
wholeUsbDevice.ReleaseInterface(0);
}
MyUsbDevice.Close();
}
MyUsbDevice = null;
// Free usb resources
UsbDevice.Exit();
}
// Wait for user input..
Console.ReadKey();
}
通过注意您的描述符,您必须将您的接口设置为1 。
wholeUsbDevice.ClaimInterface(1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.