下载安装

Nuget下载并安装 LibUsbDotNet。

查看所需打开设备的PID和VID:
using System;
using LibUsbDotNet;
using LibUsbDotNet.Main;

namespace LibdotnetTest
{
    class Program
    {
        static void Main(string[] args)
        {
            GetUSBInfo();
            Console.ReadLine();
        }

        public static void GetUSBInfo()
        {
            UsbRegDeviceList allDevices = UsbDevice.AllDevices;
            Console.WriteLine("Found {0} devices", allDevices.Count);
            foreach (UsbRegistry usb in allDevices)
            {
                Console.WriteLine("----------------");
                Console.WriteLine($"Device info: {usb.Device.Info.ProductString}");
                Console.WriteLine($"Pid: { usb.Pid}, VID: {usb.Vid}");
            }
            Console.WriteLine(allDevices.Count);
        }
    }
}

使用LibUSBDotNet写和读:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using LibUsbDotNet;
using LibUsbDotNet.Main;

namespace LibdotnetTest
{

    class LibUSB : IDisposable
    {
        private UsbDevice usbDevice;
        private UsbEndpointReader epReader;
        private UsbEndpointWriter epWriter;
        private List<byte> recvData;
        private bool isDisposed;

        public LibUSB()
        {
            recvData = new List<byte>();
            isDisposed = false;
        }

        public void Open(int vid, int pid)
        {
            UsbDeviceFinder usbFinder = new UsbDeviceFinder(vid, pid);
            usbDevice = UsbDevice.OpenUsbDevice(usbFinder);

            if (usbDevice == null)
            {
                // 异步多次尝试连接USB设备
                int count = 0;
                while (count < 10 && usbDevice == null)
                {
                    Thread.Sleep(100);
                    usbDevice = UsbDevice.OpenUsbDevice(usbFinder);
                    count++;
                }
            }

            if (usbDevice == null)
            {
                Console.WriteLine("打开USB设备失败");
            }
            else
            {
                IUsbDevice wholeUSBDevice = usbDevice as IUsbDevice;
                if (wholeUSBDevice != null)
                {
                    wholeUSBDevice.SetConfiguration(1);
                    wholeUSBDevice.ClaimInterface(0);
                }

                epReader = usbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
                epReader.ReadBufferSize = 1024;
                epReader.DataReceived += EpReader_DataReceived;
                epReader.DataReceivedEnabled = true;

                epWriter = usbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);
            }
        }

        private void EpReader_DataReceived(object sender, EndpointDataEventArgs e)
        {
            byte[] byteRead = new byte[e.Count];
            Array.Copy(e.Buffer, byteRead, e.Count);
            lock (recvData)
            {
                recvData.AddRange(byteRead);
            }
        }

        public void Close()
        {
            if (IsOpen())
            {
                IUsbDevice wholeUsbDevice = usbDevice as IUsbDevice;
                if (wholeUsbDevice != null)
                {
                    wholeUsbDevice.ReleaseInterface(0);
                }

                usbDevice.Close();
                usbDevice = null;
            }

            UsbDevice.Exit();
        }

        public bool IsOpen()
        {
            return usbDevice != null && usbDevice.IsOpen;
        }

        public List<byte> SendCommand(string cmd)
        {
            List<byte> result = new List<byte>();
            int byteWrite;
            ErrorCode ec = epWriter.Write(Encoding.Default.GetBytes(cmd), 3000, out byteWrite);
            if (ec != ErrorCode.None)
            {
                Console.WriteLine($"Write Error, {UsbDevice.LastErrorString}");
                return null;
            }

            TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
            Timer timer = new Timer(_ =>
            {
                lock (recvData)
                {
                    if (recvData.Count > 0)
                    {
                        tcs.SetResult(true);
                    }
                }
            }, null, 0, 100);

            tcs.Task.Wait();
            timer.Dispose();

            lock (recvData)
            {
                result.AddRange(recvData);
                recvData.Clear();
            }

            return result;
        }

        public void Dispose()
        {
            if (!isDisposed)
            {
                Close();
                isDisposed = true;
            }
        }
    }

}

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐