|
|
@@ -1,4 +1,5 @@
|
|
|
using SerialPortUtility;
|
|
|
+using System;
|
|
|
using System.Collections.Generic;
|
|
|
using UnityEngine;
|
|
|
|
|
|
@@ -33,8 +34,9 @@ public class ArrowSerialPort : MonoBehaviour
|
|
|
serialPortUtility.BaudRate = baudrate;
|
|
|
serialPortUtility.StopBit = SerialPortUtilityPro.StopBitEnum.OneBit;
|
|
|
serialPortUtility.DataBit = SerialPortUtilityPro.DataBitEnum.EightBit;
|
|
|
- serialPortUtility.Open();
|
|
|
- LOG($"{PortName} 串口打开");
|
|
|
+ serialPortUtility.SystemEventObject.AddListener(SystemEventObject);
|
|
|
+ TrySerialOpenPort();
|
|
|
+
|
|
|
#if UNITY_EDITOR
|
|
|
if (testMode)
|
|
|
{
|
|
|
@@ -42,7 +44,33 @@ public class ArrowSerialPort : MonoBehaviour
|
|
|
GameObject.Instantiate(testBoard);
|
|
|
}
|
|
|
#endif
|
|
|
- RequestDeviceIno();//应用启动 请求一次设备信息
|
|
|
+ }
|
|
|
+
|
|
|
+ private void TrySerialOpenPort()
|
|
|
+ {
|
|
|
+ serialPortUtility.Open();
|
|
|
+ }
|
|
|
+
|
|
|
+ private void SystemEventObject(SerialPortUtilityPro arg0, string msg)
|
|
|
+ {
|
|
|
+ if (msg.Equals("OPEN_ERROR") || msg.Equals("PERMISSION_ERROR"))//串口开启失败 定时重试
|
|
|
+ {
|
|
|
+#if UNITY_ANDROID && !UNITY_EDITOR
|
|
|
+ Invoke("TrySerialOpenPort", 1f);
|
|
|
+#endif
|
|
|
+ LOG($"{PortName} 串口打开失败 重试中");
|
|
|
+ }
|
|
|
+ else if (msg.Equals("OPENED"))
|
|
|
+ {
|
|
|
+ SerialPortHelper.ins.OnConnect(arg0.DeviceName);
|
|
|
+ RequestDeviceIno();//应用启动 请求一次设备信息
|
|
|
+ LOG($"{PortName} 串口打开成功!");
|
|
|
+ }
|
|
|
+ else if (msg.Equals("CLOSED"))//串口断开
|
|
|
+ {
|
|
|
+ SerialPortHelper.ins.OnDisConnect(arg0.DeviceName);
|
|
|
+ LOG($"{PortName} 串口关闭!");
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
private void OnDestroy()
|
|
|
@@ -50,6 +78,7 @@ public class ArrowSerialPort : MonoBehaviour
|
|
|
if (_isInit.TryGetValue(gameObject.name, out var instanceID) && instanceID == GetInstanceID())
|
|
|
{
|
|
|
LOG($"{PortName} 串口关闭");
|
|
|
+ SerialPortHelper.ins.OnDisConnect(serialPortUtility.DeviceName);
|
|
|
serialPortUtility.Close();
|
|
|
_isInit.Remove(gameObject.name);
|
|
|
}
|