using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
public class MyPortControl : MonoBehaviour {
#region 定义串口属性
//public static MyPortControl instance;
//public string portName = "COM3";
string portName = "COM10";
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;
//端口号输出
public Text portText;
#endregion
#region 打开串口
void Start() {
DontDestroyOnLoad(gameObject);
//print("ddddd");
OpenPort();
//if (p)
//Invoke("OpenPort", 5);
}
void OpenPort()
{
//print("aaaaaaa");
portName = File.ReadAllText(Application.streamingAssetsPath + "/Config.txt");
if (int.Parse(portName.Substring(3)) > 10)
{
portName = "\\\\.\\" + portName;
}
dataQueue = new Queue<string>();
port = new SerialPort(portName, baudrate, parite, dataBits, stopbits);
port.ReadTimeout = 400;
//print("aaaaaaa");
try
{
//print("ssssss");
port.Open();
print("串口打开成功!");
portRev = new Thread(PortReceivedThread);
portRev.IsBackground = true;
portRev.Start();
portDeal = new Thread(DealData);
portDeal.Start();
}
catch (System.Exception ex)
{
print(ex.Message);
}
}
#endregion
#region 接收数据
void PortReceivedThread()
{
try
{
byte[] buf = new byte[1];
string resStr = string.Empty;
if (port.IsOpen)
{
port.Read(buf, 0, 1);
//print("buf: "+buf.Length);
}
if (buf.Length == 0)
{
return;
}
if (buf != null)
{
//string strbytes = Encoding.Default.GetString(buf);
string strbytes= System.Text.Encoding.Default.GetString(buf);
print("strbytes: " + strbytes);
//string str= BytesToHexText(buf);
//string str =HexStringToString(BytesToHexText(buf), Encoding.UTF8);
if (strbytes.Equals("9"))
{
print("999999");
//portText.text = "999999";
RecognitionVoice._instance.isPickUp = true;
}
if (strbytes.Equals("B"))
{
print("BBBBB");
//portText.text = "BBBBB";
RecognitionVoice._instance.isPutDown = true;
}
// for (int i = 0; i < buf.Length; i++)
//{
// resStr += buf[i].ToString("X2");
// dataQueue.Enqueue(resStr);
//}
}
}
catch (System.Exception ex)
{
//Debug.Log(ex.Message);
}
}
/// <summary>
/// 字节数组转16进制字符串
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public string BytesToHexText(byte[] bytes)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr += bytes[i].ToString("X2") + " ";
}
}
return returnStr.TrimEnd();
}
private string HexStringToString(string hs, Encoding encode)
{
//以%分割字符串,并去掉空字符
string[] chars = hs.Split(new char[] { '%' }, StringSplitOptions.RemoveEmptyEntries);
byte[] b = new byte[chars.Length];
//逐个字符变为16进制字节数据
for (int i = 0; i < chars.Length; i++)
{
b[i] = Convert.ToByte(chars[i], 16);
}
//按照指定编码将字节数组变为字符串
return encode.GetString(b);
}
#endregion
#region 处理接收到的数据
void DealData()
{
while (dataQueue.Count != 0)
{
for (int i = 0; i < dataQueue.Count; i++)
{
outStr += dataQueue.Dequeue();
//接收到16个字节时 输出
if (outStr.Length == 12)
{
if (outStr == "16080503A55A")
{
print("有人");
//LightControll.instance._Playing();//开灯
}
else if(outStr=="16080504A55A")
{
print("停止播放");
//LightControll.instance._Ending();
}
print(outStr);
outStr = string.Empty;
}
}
}
}
#endregion
#region 发送数据
//e9 01 01 00 00 eb 0d 0a ;连接设备
//e9 01 11 01 00 fc 0d 0a ;调用模式1
//e9_01_11_02_00_fd_0d_0a ;调用模式2
//e9 01 11 03 00 fe 0d 0a ;调用模式3
//e9_01_11_04_00_ff_0d_0a ;调用模式4
private byte[] sendInfo000 = { 0xe9, 0x01, 0x01, 0x00, 0x00, 0xeb, 0x0d, 0x0a };
private byte[] sendInfo1 = { 0xe9, 0x01, 0x11, 0x01, 0x00, 0xfc, 0x0d, 0x0a };
private byte[] sendInfo2 = { 0xe9, 0x01, 0x11, 0x02, 0x00, 0xfd, 0x0d, 0x0a };
private byte[] sendInfo3 = { 0xe9, 0x01, 0x11, 0x03, 0x00, 0xfe, 0x0d, 0x0a };
private byte[] sendInfo4 = { 0xe9, 0x01, 0x11, 0x04, 0x00, 0xff, 0x0d, 0x0a };
public void SendData(byte[] msg)
{
//这里要检测一下msg
if (port.IsOpen)
{
port.Write(msg, 0, msg.Length);
print("发送数据,共"+msg.Length+"个字节。");
}
}
#endregion
#region 定时发送心跳包
float timer = 10;
void Update()
{
timer -= Time.deltaTime;
if (timer <= 0)
{
//SendData(sendInfo000);
timer = 20.0f;
}
if(portRev!=null)
{
if (!portRev.IsAlive)
{
portRev = new Thread(PortReceivedThread);
portRev.IsBackground = true;
portRev.Start();
}
}
//if (!portDeal.IsAlive)
//{
// portDeal = new Thread(DealData);
// portDeal.Start();
//}
}
#endregion
#region 退出程序
void OnApplicationQuit()
{
print("退出!");
//if ()
if (portRev.IsAlive)
{
portRev.Abort();
}
if (portDeal.IsAlive)
{
portDeal.Abort();
}
port.Close();
}
#endregion
private void OnDisable()
{
}
private void OnDestroy()
{
//print("退出!");
//if (portRev.IsAlive)
//{
// portRev.Abort();
//}
//if (portDeal.IsAlive)
//{
// portDeal.Abort();
//}
//port.Close();
//portText.text = "";
}
/ <summary>
}
接收发送十六进制数据:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Threading;
using UnityEngine;
using UnityEngine.UI;
public class MyPortControl : MonoBehaviour {
#region 定义串口属性
public static MyPortControl instance;
//public string portName = "COM3";
string portName = "COM11";
public int baudrate = 38400;
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;
//端口号输出
public Text portText;
public bool canopen;
public bool isopen;
public GameObject mainScript;
#endregion
#region 打开串口
public string[] names;
void Start() {
DontDestroyOnLoad(gameObject);
OpenPort();
StartCoroutine("DataSendFunction");
}
void OpenPort()
{
portName = File.ReadAllText(Application.streamingAssetsPath + "/Config.txt");
//print("ss: " + portName.Substring(3));
if (int.Parse(portName.Substring(3))>10)
{
portName = "\\\\.\\" + portName;
}
//print("portName: " + portName);
dataQueue = new Queue<string>();
//"\\\\.\\COM11"
port = new SerialPort(portName, baudrate, parite, dataBits, stopbits);
port.ReadTimeout = 400;
try
{
port.Open();
print("串口打开成功!");
portRev = new Thread(PortReceivedThread);
//port.DataReceived
portRev.IsBackground = true;
portRev.Start();
//portDeal = new Thread(DealData);
//portDeal.Start();
}
catch (System.Exception ex)
{
print(ex.Message);
}
}
#endregion
IEnumerator DataSendFunction()
{
while (true)
{
//yield return new WaitForSeconds(2f);
if (port != null && port.IsOpen)
{
//print("coming");
//port.w
byte[] byt = new byte[8];
byt[0] = 0x01;
byt[1] = 0x04;
byt[2] = 0x00;
byt[3] = 0x00;
byt[4] = 0x00;
byt[5] = 0x01;
byt[6] = 0x31;
byt[7] = 0xCA;
//port.Write("01 04 00 00 00 01 31 CA");
port.Write(byt, 0, 8);
}
yield return new WaitForSeconds(0.5f);
}
}
#region 接收数据
void PortReceivedThread()
{
try
{
byte[] buf = new byte[8];
string resStr = string.Empty;
if (port.IsOpen)
{
port.Read(buf, 0, port.BytesToRead);
//print("buf: "+buf.Length);
}
if (buf.Length == 0)
{
return;
}
if (buf != null)
{
string str= BytesToHexText(buf);
if(str== "01 04 02 00 00 B9 30 00")
{
//print("没人");
isopen = false;
canopen = true;
}
if(str == "01 04 02 00 01 78 F0 00")
{
//print("有人");
isopen = true;
}
}
}
catch (System.Exception ex)
{
//Debug.Log(ex.Message);
}
Thread.Sleep(1000);
}
/// <summary>
/// 字节数组转16进制字符串
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public string BytesToHexText(byte[] bytes)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr += bytes[i].ToString("X2") + " ";
}
}
return returnStr.TrimEnd();
}
private string HexStringToString(string hs, Encoding encode)
{
//以%分割字符串,并去掉空字符
string[] chars = hs.Split(new char[] { '%' }, StringSplitOptions.RemoveEmptyEntries);
byte[] b = new byte[chars.Length];
//逐个字符变为16进制字节数据
for (int i = 0; i < chars.Length; i++)
{
b[i] = Convert.ToByte(chars[i], 16);
}
//按照指定编码将字节数组变为字符串
return encode.GetString(b);
}
#endregion
#region 定时发送心跳包
float timer = 10;
float sendTime=0;
void Update()
{
timer -= Time.deltaTime;
if (timer <= 0)
{
//SendData(sendInfo000);
timer = 20.0f;
}
if (portRev != null)
{
if (!portRev.IsAlive)
{
portRev = new Thread(PortReceivedThread);
portRev.IsBackground = true;
portRev.Start();
}
}
sendTime += Time.deltaTime;
if (sendTime > 2)
{
byte[] byt = new byte[8];
byt[0] = 0x01;
byt[1] = 0x04;
byt[2] = 0x00;
byt[3] = 0x00;
byt[4] = 0x00;
byt[5] = 0x01;
byt[6] = 0x31;
byt[7] = 0xCA;
//port.Write("01 04 00 00 00 01 31 CA");
port.Write(byt, 0, 8);
sendTime = 0;
}
if (isopen)
{
//if (canopen)
{
isopen = false;
canopen = false;
//print("open open ");
transform.GetComponent<DealVoice>().Open();
}
}
//if (!portDeal.IsAlive)
//{
// portDeal = new Thread(DealData);
// portDeal.Start();
//}
}
#endregion
#region 退出程序
void OnApplicationQuit()
{
print("退出!");
//if ()
if(portRev!=null)
{
if (portRev.IsAlive)
{
portRev.Abort();
}
}
if (portDeal!=null)
{
if (portDeal.IsAlive)
{
portDeal.Abort();
}
}
port.Close();
}
#endregion
private void OnDisable()
{
}
private void OnDestroy()
{
//print("退出!");
//if (portRev.IsAlive)
//{
// portRev.Abort();
//}
//if (portDeal.IsAlive)
//{
// portDeal.Abort();
//}
//port.Close();
//portText.text = "";
}
}
另一张数据处理:
byte[] dataBytes = new byte[4];//存储长度
List<byte> buffer1 = new List<byte>();
IEnumerator DataReceiveFunction()
{
while (true)
{
//yield return new WaitForSeconds(2f);
if (port != null && port.IsOpen)
{
try
{
int bytesToRead = 0;//记录获取的数据长度
//通过read函数获取串口数据
bytesToRead = port.Read(dataBytes, 0, dataBytes.Length);
if (dataBytes.Length > 0)
{
foreach (byte item in dataBytes)
{
if (item != 0)
{
buffer1.Add(item);
}
}
}
if (buffer1.Count >= 2)
{
string strbytes = Encoding.Default.GetString(buffer1.ToArray());
Debug.Log("strbytes: " + strbytes);
buffer1.Clear();
int temp = int.Parse(strbytes);
DealMessage(temp);
//buffer1=new byte[1024];
}
//string strbytes = System.Text.Encoding.UTF8.GetString(dataBytes);
//print(strbytes);
//int temp = int.Parse(strbytes);
//if (int.Parse(strbytes)==1)
//{
// strbytes = "a";
//}
//串口数据已经被存入dataBytes中
}
catch (System.Exception ex)
{
}
}
yield return new WaitForSeconds(Time.deltaTime);
}
}