侧边栏壁纸
  • 累计撰写 62 篇文章
  • 累计收到 17 条评论

LibUsbDotNet C#与USB通讯插件用法

一缕清风
2021-01-16 / 0 评论 / 35 阅读 / 正在检测是否收录...

简介

LibUsbDotNet是一个.NET C#的USB库,适用于WinUsb,libusb-win32,Linux libusb v1.x,适用于各类终端的USB操作,代码结构清晰,调用简单;接下来本文将介绍此类库基本用法。

GitHub

开源地址:https://github.com/LibUsbDotNet/LibUsbDotNet

准备工作

  • 下载并安装LibDotNetUsb驱动,点此下载
  • 运行Filter Wizard, Install a device filter。 安装需要通信的usb设备。
    204744ejqcjucji3cf5izl.png

使用教程

NUGET管理器中搜索“LibDotNetUsb”并安装

using LibUsbDotNet;
using LibUsbDotNet.DeviceNotify;
using LibUsbDotNet.Main;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UsbDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private UsbEndpointWriter writer;
        private UsbEndpointReader reader;
        private IDeviceNotifier notifier = DeviceNotifier.OpenDeviceNotifier();
        private UsbDevice usbDevice;

        private void button1_Click(object sender, EventArgs e)
        {
            notifier.OnDeviceNotify += Notifier_OnDeviceNotify;
            if (Connection())
            {
                richTextBox1.Text += "连接成功\r\n";

            }
            else
            {
                richTextBox1.Text += "连接失败\r\n";

            }
        }

        private void Notifier_OnDeviceNotify(object sender, DeviceNotifyEventArgs e)
        {
            this.Invoke((Action)delegate ()
            {
                richTextBox1.Text += "检测到热插拔\r\n";
            });
        }

        public bool Connection()
        {
            try
            {
                UsbRegistry print = default;
                foreach (UsbRegistry item in UsbDevice.AllDevices)
                {
                    //筛选指定设备
                    if (item.Device.Info.Descriptor.VendorID == 2214 && item.Device.Info.Descriptor.ProductID == 83)
                    {
                        print = item;
                        break;
                    }
                }

                //初始化设备实例
                var usbFinder = new UsbDeviceFinder(2214, 83);
                print.Open(out usbDevice);
                IUsbDevice wholeUsbDevice = usbDevice as IUsbDevice;
                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    //这是一个“完整的”USB设备。在使用之前,
                    //必须选择所需的配置和接口。
                    //选择config #1
                    wholeUsbDevice.SetConfiguration(1);

                    //接口地址重置 #0
                    wholeUsbDevice.ClaimInterface(0);
                }
                if (usbDevice != null)
                {
                    //发送端口
                    writer = usbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);
                    //接收端口
                    reader = usbDevice.OpenEndpointReader(ReadEndpointID.Ep02);
                    //启用数据接收
                    reader.DataReceivedEnabled = true;
                    reader.DataReceived += OnDataReceived; ;
                    return usbDevice.Open();
                }
                else
                {
                    return false;
                }

            }
            catch (Exception ex)
            {
                return false;
            }
        }

        private void OnDataReceived(object sender, EndpointDataEventArgs e)
        {
            this.Invoke((Action)delegate ()
            {
                richTextBox1.Text +=  Encoding.UTF8.GetString(e.Buffer)+ "\r\n";
            });
            //throw new NotImplementedException();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (usbDevice?.IsOpen ?? false)
            {
                var data = Encoding.UTF8.GetBytes(textBox1.Text);
                var res = writer.Write(data, 2000, out int len);
                if (res == ErrorCode.None) { richTextBox1.Text += "发送成功\r\n"; }
                else
                {
                    richTextBox1.Text += "发送失败\r\n";
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (usbDevice?.IsOpen ?? false)
            {
                usbDevice.Close();
            }
        }
    }
}

103353lss1tiycezczc92t.png

0

评论 (0)

取消