LibUsbDotNet的readwrite(Event Driven)

来源:互联网 发布:网速限制软件 编辑:程序博客网 时间:2024/06/02 00:44

过程:
1、通过vendor 和product id,打开USB设备

2、设置DataReceivedEnabled=True

3、DataReceived事件

4、写入到Ep01

5、将收到的数据显示出来


using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Text.RegularExpressions;using System.Threading.Tasks;using LibUsbDotNet;using LibUsbDotNet.Main;namespace LibUsbDotNet_Learn{    class Program    {        public static UsbDevice MyUsbDevice;        public static DateTime LastDataEventDate = DateTime.Now;        //设置USB的Vendor Product ID        public static UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(0x1f3b, 0x1000);        static void Main(string[] args)        {            //保存异常数据            ErrorCode ec = ErrorCode.None;            try            {                //找到并打开USB设备                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);                if(MyUsbDevice==null)                {                    throw new Exception("Device Not Found");                }                //如果设备打开and ready                //libusb-win32是"whole"USB device,为IUsbDevice interface,不是(WinUSB),则变量                //wholeUSBDevice变量为null,是device interface,不需要configuration 和 interface                //as is 判断两个变量是否相等,is 返回TRUE/FALSE as 相同返回结果,不同返回null                IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;                if(!ReferenceEquals(wholeUsbDevice,null))                {                    //这是个"whole"USB device,使用前选择configuration interface                    //选中配置1                    wholeUsbDevice.SetConfiguration(1);                    wholeUsbDevice.ClaimInterface(0);                }                                //打开并读取read endpoint1                UsbEndpointReader reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);                UsbEndpointWriter writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);                // Remove the exepath/startup filename text from the begining of the CommandLine.                string cmdline = Regex.Replace(Environment.CommandLine, "^\".+?\"^.*? |^.*? ", "", RegexOptions.Singleline);                if (!String.IsNullOrEmpty(cmdline))                {                    reader.DataReceived+=(OnRxEndPointData);                    reader.DataReceivedEnabled = true;                    int bytesWritten;                    ec = writer.Write(Encoding.Default.GetBytes(cmdline), 2000, out bytesWritten);                    if (ec != ErrorCode.None) throw new Exception(UsbDevice.LastErrorString);                    LastDataEventDate = DateTime.Now;                    //如果长时间内为收到数据,则结束                    while((DateTime.Now-LastDataEventDate).TotalMilliseconds<100)                    {                    }                    reader.DataReceivedEnabled = false;                    reader.DataReceived-=(OnRxEndPointData);                    Console.WriteLine("\r\n Done! \r\n")                }                else                    throw new Exception("Nothing to do.");            }            catch (System.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))                        {                            //释放interface 0                            wholeUsbDevice.ReleaseInterface(0);                        }                        MyUsbDevice.Close();                    }                    MyUsbDevice = null;                    //释放usb资源                    UsbDevice.Exit();                }                Console.ReadKey();            }        }        //中断处理函数        private static void OnRxEndPointData(object sender,EndpointDataEventArgs e)        {            LastDataEventDate = DateTime.Now;            Console.WriteLine(Encoding.Default.GetString(e.Buffer, 0, e.Count));        }    }}