LibUsbDotNet使用方法


最近在用C#調試USB程序,libusb源碼是C語言的,C#用起來不方便,偶然在網上看到了LibUsbDotNet,這是開源的項目,下載后參考Example,用起來非常方便。

LibUsbDotNet下載 - http://sourceforge.net/projects/libusbdotnet/

我寫的示例工程(附件傳不上來,只能直接貼代碼了^_^) - Enjoy...

 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

using LibUsbDotNet;
using LibUsbDotNet.Info;
using LibUsbDotNet.Main;
using LibUsbDotNet.DeviceNotify;


using LibUsbDotNet.LibUsb;

 

namespace USBLib
{
    public partial class Form1 : Form
    {
        const int myPID = 0x050F;  //產品ID
        const int myVID = 0x0425;  //供應商ID

        public static UsbDevice MyUsbDevice;//USB設備
        public static DeviceNotifier DeviceNotifier = new DeviceNotifier();//設備變化通知函數
        public static UsbEndpointWriter writer = null;
        public static UsbEndpointReader reader = null;

        delegate void SetTextCallback(string text);//安全線程訪問txtReadInt的值


        Boolean EnbaleInt = false;//是否使用中斷接收

        public Form1()
        {
            InitializeComponent();
        }

        private void ShowCon(string msg)
        {
            lblConnState.Text = msg;
        }

        private void ShowMsg(string msg)
        {
            lblMsg.Text = msg;
        }
     

        private void Form1_Load(object sender, EventArgs e)
        {
            if (FindAndOpenUSB(myVID, myPID) == true)
                ShowCon("設備已連接");
            else
                ShowCon("設備未連接");

            DeviceNotifier.OnDeviceNotify += OnDeviceNotifyEvent;

            writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep03);
            reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep02);

            if( EnbaleInt == true)
            {
                reader.DataReceived += (OnRxEndPointData);
                    reader.DataReceivedEnabled = true;
            }

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            CloseUSB();
        }
 
        #region USB
        ///
        /// 初始化USB設備
        ///
        /// 設備PID
        /// 設備VID
        ///
        private bool FindAndOpenUSB(int PID, int VID)
        {
            UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(PID, VID);
            UsbRegistry myUsbRegistry   = UsbGlobals.AllDevices.Find(MyUsbFinder);

            if (ReferenceEquals(myUsbRegistry, null))
            {
                return false;
            }
            // Open this usb device.
            if (!myUsbRegistry.Open(out MyUsbDevice))
            {
                return false;
            }

            MyUsbDevice.SetConfiguration(1);

            ((LibUsbDevice)MyUsbDevice).ClaimInterface(0);

            ShowMsg(string.Format("Find Device:{0}",myUsbRegistry[SPDRP.DeviceDesc]));
            return true;
        }
        //關閉USB設備
        public void CloseUSB()
        {
            if (!ReferenceEquals(reader, null))
                reader.Dispose();
            if (!ReferenceEquals(writer, null))
                writer.Dispose();
            if (!ReferenceEquals(MyUsbDevice,null))
                MyUsbDevice.Close();
        }
        //獲得上次錯誤信息
        public string GetLastError()
        {
            return UsbGlobals.LastErrorString;
        }
        //設備變化消息相應函數
        private void OnDeviceNotifyEvent(object sender, DeviceNotifyEventArgs e)
        {
            if (e.EventType == EventType.DeviceArrival)
            {
                ShowMsg(string.Format("發現有新USB設備連接,PID = 0x{0:X},VID = 0x{1:X}.\r\n設備的詳細信息{2}", e.Device.IdProduct, e.Device.IdVendor, e.Device.ToString()));
                //看看目前新連接的USB設備是不是目標設備
                if (e.Device.IdProduct == myPID && e.Device.IdVendor == myVID)
                {
                    ShowMsg("該USB設備是目標設備");
                    //發現目標設備並打開該設備
                    FindAndOpenUSB(myPID,myVID);
                }
                else
                {
                    ShowMsg("該USB設備不是目標設備\r\n");
                }
            }
            else if (e.EventType == EventType.DeviceRemoveComplete)
            {

                ShowMsg(string.Format("發現有USB設備移除,PID = 0x{0:X}, VID = 0x{1:X}\r\n設備的詳細信息{2}", e.Device.IdProduct, e.Device.IdVendor, e.Device.ToString()));
                //看看目前移除的USB設備是不是目標設備
                if (e.Device.IdProduct == myPID && e.Device.IdVendor == myVID)
                {
                    ShowMsg(string.Format("移除的USB設備是目標設備\r\n"));
                    CloseUSB();
                }
                else
                {
                    ShowMsg(string.Format("移除的USB設備不是目標設備\r\n"));
                }
            }
        }
        //USB中斷接收函數
        private void OnRxEndPointData(object sender, EndpointDataEventArgs e)
        {
           //txtReadInt.Text = Encoding.Default.GetString(e.Buffer, 0, e.Count);
            //MessageBox.Show(Encoding.Default.GetString(e.Buffer, 0, e.Count));
            SetText(Encoding.Default.GetString(e.Buffer, 0, e.Count));
        }

        #endregion

        private void btnSend_Click(object sender, EventArgs e)
        {
            ErrorCode ec = ErrorCode.None;
            
            int bytesWritten;
            try
            {
                ec = writer.Write(Encoding.Default.GetBytes(txtSend.Text), 2000, out bytesWritten);
                if (ec != ErrorCode.None)
                    throw new Exception(UsbGlobals.LastErrorString);
            }
            catch (Exception ex)
            {
                ShowMsg("Error:" + ex.Message);
            }
            finally
            {
               
            }
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            ErrorCode ec = ErrorCode.None;
           
            byte[] readBuffer = new byte[1024];
            int bytesRead;
            try
            {
                ec = reader.Read(readBuffer, 100, out bytesRead);
                if (bytesRead == 0)
                    throw new Exception("No more bytes!");
                txtRead.Text = Encoding.Default.GetString(readBuffer, 0, bytesRead);
            }
            catch (Exception ex)
            {
                ShowMsg("Error:" + ex.Message);
            }
            finally
            {
               
            }
        }
        //線程安全訪問txtReadInt
        private void SetText(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.txtReadInt.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.txtReadInt.Text = text;
            }
        }

    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM