unity 硬件傳感器 串口通信

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
using System.Threading;
using System.IO;
using UnityEngine.Video;
using System;
using System.Text;

public class SerialPortScript : MonoBehaviour
{
    public string portName = " ";
    public int baudrate = 9600;
    public Parity parite = Parity.None;
    public int dataBits = 8;
    public StopBits stopbits = StopBits.One;
    SerialPort port;
    Thread portRev, portDeal;
    Queue<string> dataQueue;
    string outStr = string.Empty;

    void Start()
    {
        ////本地路徑  
        //string fileAddress = System.IO.Path.Combine(Application.streamingAssetsPath, "/PortNameConfig.txt");
        //FileInfo fInfo0 = new FileInfo(fileAddress);
        //string s = "";
        //if (fInfo0.Exists)
        //{
        //    StreamReader r = new StreamReader(fileAddress);
        //    s = r.ReadToEnd();
        portName = "COM2";
        dataQueue = new Queue<string>();
        port = new SerialPort(portName, baudrate, parite, dataBits, stopbits);
        port.ReadTimeout = 300;
        try
        {
            port.Open();
            Debug.Log("串口打開成功!");
            portRev = new Thread(PortReceivedThread);
            portRev.IsBackground = true;
            portRev.Start();
            portDeal = new Thread(DealData);
            portDeal.Start();
        }
        catch (System.Exception ex)
        {
            Debug.Log(ex.Message);
        }
        // }
    }


    //接收數據
    void PortReceivedThread()
    {
        try
        {
            byte[] buf = new byte[1];
            string resStr = string.Empty;
            if (port.IsOpen)
            {
                port.Read(buf, 0, 1);
            }
            if (buf.Length == 0)
            {
                return;
            }
            if (buf != null)
            {
                for (int i = 0; i < buf.Length; i++)
                {
                    //   resStr += ASCIIEncoding.UTF8.GetString (buf);
                    resStr += buf[i].ToString("X2") + " ";
                    //   resStr += Encoding.UTF8.GetString (buf);
                    dataQueue.Enqueue(resStr);
                    resStr += resStr;
                    //   print (resStr); 
                }
            }
        }
        catch (System.Exception ex)
        {
            //    Debug.Log (ex.Message);
        }
    }
    string message = " ";
    //處理
    void DealData()
    {
        while (dataQueue.Count != 0)
        {
            for (int i = 0; i < dataQueue.Count; i++)
            {
                outStr += dataQueue.Dequeue();
                if (outStr.Length == 24)
                {
                    Debug.Log(outStr);
                    message = outStr;
                    outStr = string.Empty;
                }
            }
        }

    }
    public GameObject _shotctl;

    /// <summary>
        /// 傳參數
        /// </summary>
        /// <param name="message"></param>
    void GetTheMessage(string message)
    //轉字符串
    {
        Byte[] bt = strToToHexByte(message);
        Debug.Log(bt);
        string xx = System.Text.Encoding.Default.GetString(bt);
        string hexString;
        //轉16進制
        hexString = byteToHexStr(bt);
        Debug.Log(hexString);
        //16進制轉字符串
        string AsciiString = HexStringToString(hexString, Encoding.UTF8);
        //字符數組轉字符串
        Debug.Log(Encoding.ASCII.GetString(bt, 0, bt.Length));
        Debug.Log(AsciiString);
        SendData(bt);
        SendEndSerialPortByte(0x00, 0xff, 0xaa, 0xaa, 0xaa, 0xaa, 0xa7);
        //傳參數給 _shotctl這個遊戲物體
    }
    /// <summary>
    /// 發送字符串
    /// </summary>
    /// <param name="msg"></param>
    void SendData(byte[] msg)
    {
        //這裏要檢測一下msg
        if (port.IsOpen)
        {
            port.Write(msg, 0, msg.Length);
        }
    }
    /// <summary>
    /// 發送16進制的
    /// </summary>
    /// <param name="byte1"></param>
    /// <param name="byte2"></param>
    /// <param name="byte3"></param>
    /// <param name="byte4"></param>
    /// <param name="byte5"></param>
    /// <param name="byte6"></param>
    /// <param name="byte7"></param>
    public void SendEndSerialPortByte(byte byte1, byte byte2, byte byte3, byte byte4, byte byte5, byte byte6, byte byte7)
    {
        byte[] buffer = new byte[] { byte1, byte2, byte3, byte4, byte5, byte6, byte7 };
        if (port.IsOpen)
        {
            port.Write(buffer, 0, buffer.Length);
        }
    }
    string Info = " ";
    // Update is called once per frame
    void Update()
    {
        if (port.IsOpen)
        {


            if (!portRev.IsAlive)
            {
                portRev = new Thread(PortReceivedThread);
                portRev.IsBackground = true;
                portRev.Start();

            }
            if (!portDeal.IsAlive)
            {
                portDeal = new Thread(DealData);
                portDeal.Start();
            }
        }
        if (Info != message)
        {
            GetTheMessage(message);
            Info = message = " ";
        }
    }
    /// <summary>
    /// 16進制轉字符串
    /// </summary>
    /// <param name="hs"></param>
    /// <param name="encode"></param>
    /// <returns></returns>
    public string HexStringToString(string hs, Encoding encode)
    {
        string strTemp = "";
        byte[] b = new byte[hs.Length / 2];
        for (int i = 0; i < hs.Length / 2; i++)
        {
            strTemp = hs.Substring(i * 2, 2);
            b[i] = Convert.ToByte(strTemp, 16);
        }
        //按照指定編碼將字節數組變爲字符串
        return encode.GetString(b);
    }
    /// <summary>
    /// 字符串轉16進制
    /// </summary>
    /// <param name="s"></param>
    /// <param name="encode"></param>
    /// <returns></returns>
    public string StringToHexString(string s, Encoding encode)
    {
        byte[] b = encode.GetBytes(s);//按照指定編碼將string編程字節數組
        string result = string.Empty;
        for (int i = 0; i < b.Length; i++)//逐字節變爲16進制字符
        {
            result += Convert.ToString(b[i], 16);
        }
        return result;
    }
    /// <summary>
    /// byte[]轉16進制字符串
    /// </summary>
    /// <param name="bytes"></param>
    /// <returns></returns>
    public static string byteToHexStr(byte[] bytes)
    {
        string returnStr = "";
        if (bytes != null)
        {
            for (int i = 0; i < bytes.Length; i++)
            {
                returnStr += bytes[i].ToString("X2");
            }
        }
        return returnStr;
    }
    /// <summary>
    /// 16進制字符串轉byte[]
    /// </summary>
    /// <param name="hexString"></param>
    /// <returns></returns>
    public static byte[] strToToHexByte(string hexString)
    {
        hexString = hexString.Replace(" ", "");
        if ((hexString.Length % 2) != 0)
            hexString += " ";
        byte[] returnBytes = new byte[hexString.Length / 2];
        for (int i = 0; i < returnBytes.Length; i++)
            returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
        return returnBytes;
    }
    void OnApplicationQuit()
    {
        Debug.Log("退出!");
        if (port.IsOpen)
        {
            if (portRev.IsAlive)
            {
                portRev.Abort();
            }
            if (portDeal.IsAlive)
            {
                portDeal.Abort();
            }
        }

        port.Close();
    }

}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章