unity 串口通信

1、unity设置
在这里插入图片描述
2、代码:

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Threading.Tasks;
using UnityEngine;
using Lander;
using GLHttpUtils;
using UnityEngine.SceneManagement;

public class Handle : HardParm
{
    public int Value { get; private set; }
    public override void SetValue(byte state, byte value)
    {
        if (state == 0x84 && value == 0x24 || (state == 0x85 && value == 0x25))
            Value += 1;
        if ((state == 0x85 && value == 0x24) || (state == 0x84 && value == 0x25))
            Value -= 1;
        if (state == 0x84 && value == 0x26)
            Value = Value > 0 ? (Value + 1) : (Value - 1);
        if (state == 0x85 && value == 0x26)
            Value = Value > 0 ? (Value - 1) : (Value + 1);

        SerialCon.action?.Invoke($"{Name}挡位{Value}");
        return;
    }
    public Handle(string name, params byte[] contain) : base(name, contain)
    {
        Name = name;
        Contain = contain.ToList();
    }
}

public class HardParm
{
    public HardParm(string name, params byte[] contain)
    {
        Name = name;
        Contain = contain.ToList();
    }
    public string Name;
    public List<byte> Contain;
    public virtual void SetValue(byte state, byte value)
    {
        if (state == 0x85 && Contain.Contains(value))
        {
            SerialCon.action?.Invoke(Name + $"{value - Contain.Min() + 1} 关闭");
        }
        if (state == 0x84 && Contain.Contains(value))
        {
            SerialCon.action?.Invoke(Name + $"{value - Contain.Min() + 1} 打开");
        }
    }
}

public class SerialCon : MonoBehaviour
{
    public SerialPort serialPortCom7;//串口通信 - COM7
    public SerialPort serialPortCom8;//串口通信 - COM8

    [HideInInspector] public string Com7;//不可读取开关值
    [HideInInspector] public string Com8;//可读取开关值

    [SerializeField] public bool com7Open;
    [SerializeField] public bool com8Open;


    BlockingCollection<byte[]> buffers7 = new BlockingCollection<byte[]>();//数列
    BlockingCollection<byte[]> buffers8 = new BlockingCollection<byte[]>();//数列


    public string TS = "TS0";

    public static Action<string> action;

    public List<HardParm> hardParms = new List<HardParm>();

    public K21UIManager k21UIManager;

    private void Awake()
    {
        Application.quitting += OnDisable;

        hardParms.Add(new Handle("主令手柄", 0x24, 0x25, 0x26, 0x27));
        hardParms.Add(new HardParm("高压电源", 16, 17));
        hardParms.Add(new HardParm("提升方式", 20, 21, 22, 23));
        hardParms.Add(new HardParm("运行方式", 0x1E, 0x1F));
        SetHardParmsK23();
        //action = (s, e) => Debug.Log(s + "值变动了,变动后的值为" + e);
        action = K21Control.TestSwitchState;

        ReadComSet();
    }

    public SwitchHoming switchHoming;//开关灯 

    public static int ward;//挡位

    public static int ZDSB;//制动手柄值

    private async void Start()
    {

        try
        {
            //---------------------------------端口名、波特率、...        、数据位、停止位
            serialPortCom8 = new SerialPort(Com8, 9600, Parity.None, 8, StopBits.One);

            serialPortCom8.Open();//开启串口8
            com8Open = true;
        }
        catch (Exception ex)
        {
            HintAnomaly(ex.ToString());
            Debug.LogError(ex);

            serialPortCom8.Close();
            serialPortCom8.Dispose();
        }
        if (!com8Open) return;
        //85 02 05 08 4a 2a 2b b3 06 85 02 05 08 4a 2a 2b b3 06 85 02 05 08 4a 2a 2b b3 06 85 02 05 08 4a 2a 2b b3 06 85 02 05 08 4a 2a 2b b3 06 85 02 05 08 4a 2a 2b b3 06
        byte[] buffer = new byte[] { 0x85, 0x02, 0x05, 0x08, 0x4a, 0x2a, 0x2b, 0xb3, 0x06, 0x85, 0x02, 0x05, 0x08, 0x4a, 0x2a, 0x2b, 0xb3, 0x06, 0x85, 0x02, 0x05, 0x08, 0x4a, 0x2a, 0x2b, 0xb3, 0x06, 0x85, 0x02, 0x05, 0x08, 0x4a, 0x2a, 0x2b, 0xb3, 0x06, 0x85, 0x02, 0x05, 0x08, 0x4a, 0x2a, 0x2b, 0xb3, 0x06, 0x85, 0x02, 0x05, 0x08, 0x4a, 0x2a, 0x2b, 0xb3, 0x06 };
        serialPortCom8.Write(buffer, 0, buffer.Length);

        await Task.Delay(200);//时间间隔
        serialPortCom8.BaudRate = 19200;

        try
        {
            serialPortCom7 = new SerialPort(Com7, 9600, Parity.None, 8, StopBits.One);

            serialPortCom7.Open();//开启串口7
            com7Open = true;
        }
        catch (Exception ex)
        {
            HintAnomaly(ex.ToString());
            Debug.LogError(ex);

            serialPortCom7.Close();
            serialPortCom7.Dispose();
        }
        if (!com7Open) return;
        serialPortCom7.Write(buffer, 0, buffer.Length);

        await Task.Delay(200);//时间间隔
        serialPortCom7.BaudRate = 19200;
 
        await Task.Run(() => Send7());
        await Task.Run(() => Send8());

        await Task.Run(() => Read2());

        
    }

    /// <summary>
    /// 获取是否开启
    /// </summary>
    /// <param name="i">灯</param>
    /// <param name="temp">是否开启</param>
    public void SetLight(string com, byte i, bool temp)
    {
        byte[] send = new byte[] { (byte)(temp ? 0x81 : 0x82), i };

        if (com.Equals(Com7))
            buffers7.Add(send);

        if (com.Equals(Com8))
            buffers8.Add(send);

    }

    /// <summary>
    /// 给COM7写入命令
    /// </summary>
    async void Send7()
    {
        while (serialPortCom7.IsOpen)
        {
            var temp = buffers7.Take();
            serialPortCom7.Write(temp, 0, temp.Length);//写入
            await Task.Delay(10);
        }
    }

    /// <summary>
    ///  给COM8写入命令
    /// </summary>
    async void Send8()
    {
        while (serialPortCom8.IsOpen)
        {
            var temp = buffers8.Take();
            serialPortCom8.Write(temp, 0, temp.Length);//写入

            await Task.Delay(10);
        }
    }


    async void Read2()
    {

        if (serialPortCom8.IsOpen)
        {
            byte[] buffer = new byte[] { 0x83, 0x00, 0x84, 0x00 };
            serialPortCom8.Write(buffer, 0, buffer.Length);
        }
        List<int[]> Reset = new List<int[]> { new int[] { 36, 37, 38 }, new int[] { 16, 17 }, new int[] { 20, 21, 22, 23 }, new int[] { 30, 31 } };
        SetSwitchValueK23(Reset);
        try
        {

            while (serialPortCom8.IsOpen)
            {
                if (K21Control.StartTest)
                {
                    int length = serialPortCom8.BytesToRead;
                    if (length > 0)
                    {

                        byte[] receive = new byte[1];
                        serialPortCom8.Read(receive, 0, 1);
                        if (receive[0] == 0x85)
                        {
                            serialPortCom8.Read(receive, 0, 1);
                            for (int i = 0; i < Reset.Count; i++)
                            {
                                if (Reset[i].Contains(receive[0]))
                                    K21Control.initialSwitch[i + 1] = false;
                            }
                        }
                        else if (receive[0] == 0x84)
                        {
                            serialPortCom8.Read(receive, 0, 1);
                            for (int i = 0; i < Reset.Count; i++)
                            {
                                if (Reset[i].Contains(receive[0]))
                                    K21Control.initialSwitch[i + 1] = true;
                            }
                        }
                        else if (receive[0] == 0x86)
                        {
                            serialPortCom8.Read(receive, 0, 1);
                            K21Control.initialSwitch[0] = receive[0] != 0;
                        }
                    }
                }
                else
                {

                    int length = serialPortCom8.BytesToRead;
                    if (length > 1)
                    {
                        byte[] receive = new byte[1];
                        serialPortCom8.Read(receive, 0, 1);
                        if (receive[0] == 0x85)
                        {
                            K21Control.Operate = 1;
                            serialPortCom8.Read(receive, 0, 1);
                            hardParms.ForEach(x => x.SetValue(0x85, receive[0]));
                            //Debug.Log($"{receive[0]}打开");
                        }
                        else if (receive[0] == 0x84)
                        {
                            K21Control.Operate = 1;
                            serialPortCom8.Read(receive, 0, 1);
                            hardParms.ForEach(x => x.SetValue(0x84, receive[0]));
                            
                            //Debug.Log($"{receive[0]}关闭");
                        }
                        else if (receive[0] == 0x86)
                        {
                            K21Control.Operate = 1;
                            serialPortCom8.Read(receive, 0, 1);
                            //Debug.Log($"制动手柄{receive[1]}");
                            ZDSB = receive[0];
                        }
                    }
                }
            }

        }
        catch (Exception ex)
        {
            Debug.LogError(ex);
        }

    }



    private void OnGUI()
    {
        //GUI.Label(new Rect(10, 10, 200, 90), str[0]);
        //GUI.Label(new Rect(10, 100, 200, 90), str[1]);
        //GUI.Label(new Rect(10, 190, 200, 90), str[2]);
    }

    private void OnDisable()
    {
        serialPortCom7.Close();
        serialPortCom7.Dispose();
        serialPortCom8.Close();
        serialPortCom8.Dispose();
    }

    /// <summary>
    /// 检测开关是否复位
    /// </summary>
    public void WriteTestSwitchState()
    {
        byte[] buffer = new byte[] { 0x84, 0x01 };
        buffers8.Add(buffer);
    }

    /// <summary>
    /// 获取COM口设置
    /// </summary>
    void ReadComSet()
    {
        if (App.Instance != null)
        {
            Com7 = Global.Instance.localSettingData.com1;
            Com8 = Global.Instance.localSettingData.com2;
            Debug.Log("com_7:" + Com7);
            Debug.Log("com_8:" + Com8);
        }
    }

    /// <summary>
    /// 添加K23开关参数
    /// </summary>
    void SetSwitchValueK23(List<int[]> Reset)
    {
        if (Global.Instance.projectId == "K23")
            Reset.Add(new int[] { 0x18, 0x19 });

    }

    /// <summary>
    /// 设置防跑车挡位参数
    /// </summary>
    void SetHardParmsK23()
    {

        string projectId = SceneManager.GetActiveScene().name.Substring(0,2);
        Debug.Log(projectId);
        if (projectId == "K23")
            hardParms.Add(new HardParm("防跑车", 0x18, 0x19));

    }

    /// <summary>
    /// 提示与硬件连接异常
    /// </summary>
    public void HintAnomaly(string error)
    {
        k21UIManager.errorRecord.Write(error);
    }

}

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值