1. 程式人生 > >Unity獲取串列埠資料

Unity獲取串列埠資料

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
using System;
using System.Threading;
using UnityEngine.UI;


public class PortManager  {
    private SerialPort sp = null;//埠
    bool isActive = false;
    private Thread athread;
    public Action<string> ReadDataEvent;
    object lockd = new object();


    /// <summary>
    /// 初始化埠
    /// </summary>
    public void InitPort(string portName,int baudRate) {
        isActive = true;
        sp = new SerialPort("\\\\.\\" + portName, baudRate);
    }
    /// <summary>
    /// 開啟埠
    /// </summary>
    public void OpenPort() {
        try {
            sp.Open();
        } catch( Exception ex ) {
            Debug.Log(ex.Message);
        }
    }
    /// <summary>
    /// 關閉埠
    /// </summary>
    public void ClosePort() {
        try {
            sp.Close();
        } catch( Exception ex ) {
            Debug.Log(ex.Message);
        }
    }
    /// <summary>
    /// 獲取所有埠
    /// </summary>
    /// <returns></returns>
    public string[] GetAllPorts() {
        return SerialPort.GetPortNames();
    }
    /// <summary>
    /// 開始讀取資料
    /// </summary>
    public void StartReadData() {
        athread = new Thread(new ThreadStart(GoThread));
        athread.IsBackground = true;
        athread.Start();
    }


    void GoThread() {
        while( isActive ) {
            lock( lockd ) {
                ReadPortData();
            }
            Thread.Sleep(10);
        }
    }


    private void ReadPortData() {
        if( sp != null && sp.IsOpen ) {
            try {
                string portValue = sp.ReadLine();
                if( !string.IsNullOrEmpty(portValue) && ReadDataEvent != null ) {
                    ReadDataEvent(portValue);
                }
            } catch( Exception ex ) {
                Debug.Log(ex.Message);
            }
        } else {
            Debug.LogError("請檢查埠設定!");
        }
    }
}