16路舵机控制器USB访问

16路舵机控制器USB访问

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

namespace MCtl
{
    public partial class Form1 : Form
    {
        private byte OfflineCnt;
        public byte OnlineBoard;
        private UsbHidPort usb;
        public ushort usOnboardID = 0xffff;
        private ushort usRxCnt;
        private ushort usTotalLength = 5;
        private MotorControl.MSG stcMSG;
        public byte byteID;
        private byte[] RxBuffer = new byte[0x3e8];
        private delegate void DecodeDataHandler(byte[] byteTemp, ushort usLength);
        public Form1()
        {
            InitializeComponent();
            this.usb = new UsbHidPort();
            this.usb.ProductId = 0x100;
            this.usb.VendorId = 0x1920;
            this.usb.OnSpecifiedDeviceArrived += new EventHandler(this.usb_OnSpecifiedDeviceArrived);
            this.usb.OnSpecifiedDeviceRemoved += new EventHandler(this.usb_OnSpecifiedDeviceRemoved);
            this.usb.OnDeviceArrived += new EventHandler(this.usb_OnDeviceArrived);
            this.usb.OnDeviceRemoved += new EventHandler(this.usb_OnDeviceRemoved);
            this.usb.OnDataRecieved += new DataRecievedEventHandler(this.usb_OnDataRecieved);
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        private string GetLocalText(string ChString, string EnString)
        {
            if (Thread.CurrentThread.CurrentUICulture.Name == "zh-CN") return ChString;
            return EnString;
        }
        #region USB

        private void MyLog(byte[] bytes)
        {
            if (bytes[1] == 0) return;
            Console.WriteLine(BitConverter.ToString(bytes));
        }
        public void Send(byte cmd, byte ch, int data)
        {
            byte[] byteSend = new byte[5];
            short num = (short)data;
            byteSend[0] = 0xff;
            byteSend[1] = cmd;
            byteSend[2] = ch;
            byteSend[3] = (byte)(num & 0xff);
            byteSend[4] = (byte)(num >> 8);
            try
            {
                this.SendUSBMsg(3, byteSend, (byte)byteSend.Length);
                MyLog(byteSend);
               // if (this.spSerialPort.IsOpen) this.spSerialPort.Write(byteSend, 0, 5);
                if (cmd != 0)
                {
                    if (this.OnlineBoard == 0)
                        this.Status1.Text = this.GetLocalText("端口未打开!待发送数据:", "Port not open, datas to send are:") + byteSend[0].ToString("x") + " " + byteSend[1].ToString("x") + " " + byteSend[2].ToString("x") + " " + byteSend[3].ToString("x") + " " + byteSend[4].ToString("x") + " ";
                    else
                        this.Status1.Text = this.GetLocalText("已发送:", "Send:") + byteSend[0].ToString("x") + " " + byteSend[1].ToString("x") + " " + byteSend[2].ToString("x") + " " + byteSend[3].ToString("x") + " " + byteSend[4].ToString("x") + " ";
                }
            }
            catch (Exception)
            {
            }
        }

        public void SendMessage(byte cmd, byte ch, int data)
        {
            this.stcMSG.cmd = ((CMD)cmd) | ((CMD)(this.byteID << 4));
            this.stcMSG.ch = ch;
            this.stcMSG.data = data;
            this.Send((byte)this.stcMSG.cmd, this.stcMSG.ch, this.stcMSG.data);
        }

        private sbyte SendUSBMsg(byte ucType, byte[] byteSend, byte ucLength)
        {
            try
            {
                if (this.usb.SpecifiedDevice != null)
                {
                    byte[] array = new byte[0x43];
                    array[1] = ucLength;
                    array[2] = ucType;
                    byteSend.CopyTo(array, 3);
                    this.usb.SpecifiedDevice.SendData(array);
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString());
            }
            return 0;
        }

        private void usb_OnDataRecieved(object sender, DataRecievedEventArgs args)
        {
            if (base.InvokeRequired)
            {
                try
                {
                    base.Invoke(new DataRecievedEventHandler(this.usb_OnDataRecieved), new object[] { sender, args });
                }
                catch (Exception)
                {
                }
            }
            else
            {
                byte usLength = args.data[1];
                switch (args.data[2])
                {
                    case 0:
                        return;

                    case 1:
                        for (int i = 0; i < usLength; i++)
                        {
                            args.data[i] = args.data[i + 3];
                        }
                        this.DecodeData(args.data, usLength);
                        return;

                    default:
                        return;
                }
            }
        }

        private void usb_OnDeviceArrived(object sender, EventArgs e)
        {
            this.Status1.Text = "Find USB Device!";
        }

        private void usb_OnDeviceRemoved(object sender, EventArgs e)
        {
            this.Status1.Text = "USB Device Removed!";
        }

        private void usb_OnSpecifiedDeviceArrived(object sender, EventArgs e)
        {
            this.Status1.Text = "My Device Connected!";
            this.OnlineBoard = (byte)(this.OnlineBoard | 2);
            //this.SetBaudrate(this.spSerialPort.BaudRate);
        }

        private void usb_OnSpecifiedDeviceRemoved(object sender, EventArgs e)
        {
            this.Status1.Text = "My Device DisConnected!";
            this.OnlineBoard = (byte)(this.OnlineBoard & 0xfd);
        }
        private bool CheckHead(byte[] byteData, byte[] byteHeadTemp, int byteHeadLength)
        {
            for (byte i = 0; i < byteHeadLength; i = (byte)(i + 1))
            {
                if (byteData[i] != byteHeadTemp[i]) return false;
            }
            return true;
        }
        private void ByteCopy(byte[] byteFrom, byte[] byteTo, ushort usFromIndex, ushort usToIndex, ushort usLength)
        {
            for (int i = 0; i < usLength; i++)
            {
                byteTo[usToIndex + i] = byteFrom[usFromIndex + i];
            }
        }
        public void DecodeData(byte[] byteTemp, ushort usLength)
        {
            if (base.InvokeRequired)
            {
                try
                {
                    base.Invoke(new DecodeDataHandler(this.DecodeData), new object[] { byteTemp, usLength });
                }
                catch (Exception)
                {
                }
            }
            else
            {
                this.ByteCopy(byteTemp, this.RxBuffer, 0, this.usRxCnt, usLength);
                this.usRxCnt = (ushort)(this.usRxCnt + usLength);
                while (this.usRxCnt >= this.usTotalLength)
                {
                    if (!this.CheckHead(this.RxBuffer, new byte[] { 0xff, 240 }, 2))
                    {
                        this.ByteCopy(this.RxBuffer, this.RxBuffer, 1, 0, this.usRxCnt);
                        this.usRxCnt = (ushort)(this.usRxCnt - 1);
                    }
                    else
                    {
                       // if (this.formConfig != null) this.formConfig.DecodeData(this.RxBuffer);
                        if (this.RxBuffer[1] == 240)
                        {
                            short num = BitConverter.ToInt16(this.RxBuffer, 3);
                            if (num == 0 | (num & 0xff) == 0xff) this.usOnboardID = 0;
                        }
                        this.ByteCopy(this.RxBuffer, this.RxBuffer, this.usTotalLength, 0, (ushort)(this.usRxCnt - this.usTotalLength));
                        this.usRxCnt = (ushort)(this.usRxCnt - this.usTotalLength);
                    }
                }
            }
        }
        protected override void OnHandleCreated(EventArgs e)
        {
            try
            {
                base.OnHandleCreated(e);
                this.usb.RegisterHandle(base.Handle);
            }
            catch (Exception)
            {
            }
        }
        protected override void WndProc(ref Message m)
        {
            try
            {
                this.usb.ParseMessages(ref m);
                base.WndProc(ref m);
            }
            catch (Exception)
            {
            }
        }
        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            var rnd = new Random(Environment.TickCount);
            var v = rnd.Next(500, 2500);
            SendMessage(2, 0, v);
            Console.WriteLine("转:" + v);
        }
    }
}
View Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UsbLibrary;
using MotorControl;
using System.Threading;

namespace MCtl
{
    public partial class Form1 : Form
    {
        private byte OfflineCnt;
        public byte OnlineBoard;
        private UsbHidPort usb;
        public ushort usOnboardID = 0xffff;
        private ushort usRxCnt;
        private ushort usTotalLength = 5;
        private bool bCheckID = true;
        private MotorControl.MSG stcMSG;
        public byte byteID;
        private byte[] RxBuffer = new byte[0x3e8];
        private delegate void DecodeDataHandler(byte[] byteTemp, ushort usLength);
        public Form1()
        {
            InitializeComponent();
            this.usb = new UsbHidPort();
            this.usb.ProductId = 0x100;
            this.usb.VendorId = 0x1920;
            this.usb.OnSpecifiedDeviceArrived += new EventHandler(this.usb_OnSpecifiedDeviceArrived);
            this.usb.OnSpecifiedDeviceRemoved += new EventHandler(this.usb_OnSpecifiedDeviceRemoved);
            this.usb.OnDeviceArrived += new EventHandler(this.usb_OnDeviceArrived);
            this.usb.OnDeviceRemoved += new EventHandler(this.usb_OnDeviceRemoved);
            this.usb.OnDataRecieved += new DataRecievedEventHandler(this.usb_OnDataRecieved);
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        private string GetLocalText(string ChString, string EnString)
        {
            if (Thread.CurrentThread.CurrentUICulture.Name == "zh-CN") return ChString;
            return EnString;
        }
        #region USB

        private void MyLog(byte[] bytes)
        {
            //if (bytes[1] == 0) return;
            Console.WriteLine(BitConverter.ToString(bytes));
        }
        public void Send(byte cmd, byte ch, int data)
        {
            byte[] byteSend = new byte[5];
            short num = (short)data;
            byteSend[0] = 0xff;
            byteSend[1] = cmd;
            byteSend[2] = ch;
            byteSend[3] = (byte)(num & 0xff);
            byteSend[4] = (byte)(num >> 8);
            try
            {
                this.SendUSBMsg(3, byteSend, (byte)byteSend.Length);
                MyLog(byteSend);
               // if (this.spSerialPort.IsOpen) this.spSerialPort.Write(byteSend, 0, 5);
                if (cmd != 0)
                {
                    if (this.OnlineBoard == 0)
                        this.Status1.Text = this.GetLocalText("端口未打开!待发送数据:", "Port not open, datas to send are:") + byteSend[0].ToString("x") + " " + byteSend[1].ToString("x") + " " + byteSend[2].ToString("x") + " " + byteSend[3].ToString("x") + " " + byteSend[4].ToString("x") + " ";
                    else
                        this.Status1.Text = this.GetLocalText("已发送:", "Send:") + byteSend[0].ToString("x") + " " + byteSend[1].ToString("x") + " " + byteSend[2].ToString("x") + " " + byteSend[3].ToString("x") + " " + byteSend[4].ToString("x") + " ";
                }
            }
            catch (Exception)
            {
            }
        }

        public void SendMessage(byte cmd, byte ch, int data)
        {
            this.stcMSG.cmd = ((CMD)cmd) | ((CMD)(this.byteID << 4));
            this.stcMSG.ch = ch;
            this.stcMSG.data = data;
            this.Send((byte)this.stcMSG.cmd, this.stcMSG.ch, this.stcMSG.data);
        }

        private sbyte SendUSBMsg(byte ucType, byte[] byteSend, byte ucLength)
        {
            try
            {
                if (this.usb.SpecifiedDevice != null)
                {
                    byte[] array = new byte[0x43];
                    array[1] = ucLength;
                    array[2] = ucType;
                    byteSend.CopyTo(array, 3);
                    this.usb.SpecifiedDevice.SendData(array);
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString());
            }
            return 0;
        }

        private void usb_OnDataRecieved(object sender, DataRecievedEventArgs args)
        {
            if (base.InvokeRequired)
            {
                try
                {
                    base.Invoke(new DataRecievedEventHandler(this.usb_OnDataRecieved), new object[] { sender, args });
                }
                catch (Exception)
                {
                }
            }
            else
            {
                byte usLength = args.data[1];
                switch (args.data[2])
                {
                    case 0:
                        return;

                    case 1:
                        for (int i = 0; i < usLength; i++)
                        {
                            args.data[i] = args.data[i + 3];
                        }
                        this.DecodeData(args.data, usLength);
                        return;

                    default:
                        return;
                }
            }
        }

        private void usb_OnDeviceArrived(object sender, EventArgs e)
        {
            this.Status1.Text = "Find USB Device!";
        }

        private void usb_OnDeviceRemoved(object sender, EventArgs e)
        {
            this.Status1.Text = "USB Device Removed!";
        }

        private void usb_OnSpecifiedDeviceArrived(object sender, EventArgs e)
        {
            this.Status1.Text = "My Device Connected!";
            this.OnlineBoard = (byte)(this.OnlineBoard | 2);
            //this.SetBaudrate(this.spSerialPort.BaudRate);
        }

        private void usb_OnSpecifiedDeviceRemoved(object sender, EventArgs e)
        {
            this.Status1.Text = "My Device DisConnected!";
            this.OnlineBoard = (byte)(this.OnlineBoard & 0xfd);
        }
        private bool CheckHead(byte[] byteData, byte[] byteHeadTemp, int byteHeadLength)
        {
            for (byte i = 0; i < byteHeadLength; i = (byte)(i + 1))
            {
                if (byteData[i] != byteHeadTemp[i]) return false;
            }
            return true;
        }
        private void ByteCopy(byte[] byteFrom, byte[] byteTo, ushort usFromIndex, ushort usToIndex, ushort usLength)
        {
            for (int i = 0; i < usLength; i++)
            {
                byteTo[usToIndex + i] = byteFrom[usFromIndex + i];
            }
        }
        public void DecodeData(byte[] byteTemp, ushort usLength)
        {
            if (base.InvokeRequired)
            {
                try
                {
                    base.Invoke(new DecodeDataHandler(this.DecodeData), new object[] { byteTemp, usLength });
                }
                catch (Exception)
                {
                }
            }
            else
            {
                this.ByteCopy(byteTemp, this.RxBuffer, 0, this.usRxCnt, usLength);
                this.usRxCnt = (ushort)(this.usRxCnt + usLength);
                while (this.usRxCnt >= this.usTotalLength)
                {
                    if (!this.CheckHead(this.RxBuffer, new byte[] { 0xff, 240 }, 2))
                    {
                        this.ByteCopy(this.RxBuffer, this.RxBuffer, 1, 0, this.usRxCnt);
                        this.usRxCnt = (ushort)(this.usRxCnt - 1);
                    }
                    else
                    {
                       // if (this.formConfig != null) this.formConfig.DecodeData(this.RxBuffer);
                        if (this.RxBuffer[1] == 240)
                        {
                            short num = BitConverter.ToInt16(this.RxBuffer, 3);
                            if (num == 0 | (num & 0xff) == 0xff) this.usOnboardID = 0;
                        }
                        this.ByteCopy(this.RxBuffer, this.RxBuffer, this.usTotalLength, 0, (ushort)(this.usRxCnt - this.usTotalLength));
                        this.usRxCnt = (ushort)(this.usRxCnt - this.usTotalLength);
                    }
                }
            }
        }
        protected override void OnHandleCreated(EventArgs e)
        {
            try
            {
                base.OnHandleCreated(e);
                this.usb.RegisterHandle(base.Handle);
            }
            catch (Exception)
            {
            }
        }
        protected override void WndProc(ref Message m)
        {
            try
            {
                this.usb.ParseMessages(ref m);
                base.WndProc(ref m);
            }
            catch (Exception)
            {
            }
        }
        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            var rnd = new Random(Environment.TickCount);
            var v = rnd.Next(500, 2500);
            SendMessage(2, 0, v);
            Console.WriteLine("转:" + v);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (this.OnlineBoard == 0)
            {
                this.textBoxBoard.Text = this.GetLocalText("离线", "Offline");
                this.textBoxBoard.BackColor = Color.Yellow;
            }
            else if (this.bCheckID)
            {
                this.bCheckID = false;
                this.usOnboardID = 0xffff;
                this.Send(0, 0x12, 0);
            }
            else
            {
                this.bCheckID = true;
                if (this.usOnboardID == 0xffff)
                    this.OfflineCnt = (byte)(this.OfflineCnt + 1);
                else
                    this.OfflineCnt = 0;
                if (this.usOnboardID == 0xffff)
                    this.textBoxBoard.Text = this.GetLocalText("离线", "Offline");
                else
                    this.textBoxBoard.Text = this.GetLocalText("在线", "Online");
                if (this.textBoxBoard.Text == this.GetLocalText("离线", "Offline"))
                    this.textBoxBoard.BackColor = Color.Yellow;
                else if ((this.usOnboardID & ((int)1) << this.byteID) == 0) this.textBoxBoard.BackColor = Color.Lime;
            }
        }
    }
}
View Code
原文地址:https://www.cnblogs.com/wdfrog/p/14841812.html