USB通信

相关工具

  Bus Hound

  HidLib.dll  

      通过百度网盘分享的文件:通信
      链接:https://pan.baidu.com/s/1hsiSaMz0IW2TbnPWUT9-aA
      提取码:fvkt

动态库功能:

  • 枚举USB设备信息(设备路径、厂商id、产品id和设备序列号)
  • 根据设备路径,打开和关闭USB设备
  • 进行USB通信,即数据的收发

代码实现:

  说明:该代码不能直接运行,以下代码是winform的后台代码

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace HIDAssistance
{
    [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Auto)]
    public struct HIDDevInfo
    {
        public string m_DevicePath;
        public ushort m_VendorID;
        public ushort m_ProductID;
        public string m_ManufacturerString;
        public string m_ProductString;
        public string m_SerialNumber;
    }

    public delegate int RECEIVE_CALLBACK(IntPtr recvData, int dlen);
    public partial class Form1 : Form
    {
        [DllImport("HidLib.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        public static extern int HID_EnumDevices();
        [DllImport("HidLib.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        public static extern IntPtr HID_GetHIDDevPath(int index);

        [DllImport("HidLib.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        public static extern int OpenHID(string index);

        [DllImport("HidLib.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        public static extern int CloseHID();

        [DllImport("HidLib.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode)]
        public static extern int write(byte[] buffer, UInt32 bytesToWrite, ref UInt32 bytesWritten);

        [DllImport("HidLib", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
        public static extern int SetFuncRecall(RECEIVE_CALLBACK receive);

        List<HIDDevInfo> lst = new List<HIDDevInfo>();
        public Form1()
        {
            InitializeComponent();
            int cnt = HID_EnumDevices();
            for (int i = 0; i < cnt; i++)
            {
                IntPtr pDevice = HID_GetHIDDevPath(i);
                HIDDevInfo obj = (HIDDevInfo)Marshal.PtrToStructure(pDevice, typeof(HIDDevInfo));
                lst.Add(obj);
                if (!string.IsNullOrEmpty(obj.m_DevicePath))
                {
                    comboBox1.Items.Add(obj.m_DevicePath);
                    textBox1.Text = obj.m_VendorID.ToString("X4");
                    textBox2.Text = obj.m_ProductID.ToString("X4");
                    if (comboBox1.Items.Count > 0)
                        comboBox1.SelectedIndex = 0;
                }
            }
        }

        public event RECEIVE_CALLBACK callBackEvt = null;
        private void button2_Click(object sender, EventArgs e)
        {
            callBackEvt = new RECEIVE_CALLBACK(recvCallBackFunc);
            SetFuncRecall(callBackEvt);
            string hidStr = comboBox1.Text;
            int ret=OpenHID(hidStr);
            if (ret != 0)
            {
                MessageBox.Show("fail!");
                return;
            }
            button2.Enabled = false;
            //HIDDevInfo[] arr = new HIDDevInfo[1];
            //int size = Marshal.SizeOf(typeof(HIDDevInfo));
            //IntPtr structPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(HIDDevInfo)));

            //int nSize = 0;
            //IntPtr ret = HID_SearchHIDPath(ref nSize);
            //if (nSize > 0)
            //{
            //    //HIDDevInfo obj = (HIDDevInfo)Marshal.PtrToStructure(ret, typeof(HIDDevInfo));
            //    object obj = Marshal.PtrToStructure(ret, typeof(HIDDevInfo));

            //    Marshal.FreeHGlobal(ret);
            //}

        }

        public int recvCallBackFunc(IntPtr recvData, int dlen)
        {
            if (recvData != null && dlen > 0)
            {
                byte[] data = new byte[dlen];
                Marshal.Copy(recvData, data, 0, dlen);
                string str = BitConverter.ToString(data, 0, (int)dlen).Replace("-", "");
                this.Invoke((EventHandler)delegate
                {
                    richTextBox2.AppendText(str + "\n");
                    richTextBox2.SelectionStart = richTextBox2.Text.Length;
                    richTextBox2.ScrollToCaret();

                });
                return 0;
            }
            else
            {
                return -1;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            int ret=CloseHID();
            if (ret != 0)
            {
                MessageBox.Show("fail!");
                return;
            }
            button2.Enabled = true;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            int bufLen;
            uint written = 0;
            byte[] buf = StringToHexByteArray(richTextBox1.Text);
            bufLen = buf.Length;
            write(buf, (uint)bufLen, ref written);
        }

        public static byte[] StringToHexByteArray(string hex)
        {
            if (hex.Length % 2 == 1)
                throw new Exception("The binary key cannot have an odd number of digits");

            int len = hex.Length >> 1;
            byte[] arr = new byte[len];

            for (int i = 0; i < len; ++i)
            {
                arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1])));
            }

            return arr;
        }

        public static int GetHexVal(char hex)
        {
            int val = (int)hex;
            return val - (val < 58 ? 48 : (val < 97 ? 55 : 87));
        }

        
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = comboBox1.SelectedIndex;
            HIDDevInfo currentDev = lst[index];
            textBox1.Text = currentDev.m_VendorID.ToString("X4");
            textBox2.Text = currentDev.m_ProductID.ToString("X4");
        }

    }
}

实现效果

  略

posted @ 2024-10-29 10:21  !>Mon<!  阅读(25)  评论(0编辑  收藏  举报