LibUsbDotNet的readwrite(Event Driven)

24 篇文章 2 订阅

过程:
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));
        }

    }

}



  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
Event-driven programming is a programming paradigm that allows the software to respond to events or user actions in a asynchronous manner. Here are the general steps to implement an event-driven program: 1. Identify the events: Determine the events that the program needs to respond to. These could be user actions, system events, or external signals. 2. Define event handlers: Create functions or methods to handle each event. These functions will be executed when the event occurs. 3. Register event handlers: Associate each event handler with the corresponding event. This is usually done using a framework or library. 4. Run the program: Once the event handlers are registered, the program is ready to execute. As events occur, the associated event handlers will be executed. 5. Clean up: After the program finishes executing, clean up any resources used or allocated during the program. Here's an example of an event-driven program in Python using the Tkinter GUI library: ```python import tkinter as tk def button_click(event): print("Button clicked") root = tk.Tk() button = tk.Button(root, text="Click me") button.bind("<Button-1>", button_click) button.pack() root.mainloop() ``` In this program, we identify the event as a button click, define an event handler function `button_click` to handle the event, register the event handler with the button using the `bind` method, and run the program using the `mainloop` method. When the button is clicked, the `button_click` function will be executed and print "Button clicked" to the console.
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值