ArrowSerialPort.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. using SerialPortUtility;
  2. using System;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. public class ArrowSerialPort : MonoBehaviour
  6. {
  7. private SerialPortUtilityPro serialPortUtility;
  8. private SerialPortUtilityPro.OpenSystem openMode = SerialPortUtilityPro.OpenSystem.PCI;
  9. private int baudrate = 115200;
  10. private string PortName = "/dev/ttyS0";
  11. private static Dictionary<string, int> _isInit = new();
  12. public bool testMode = false;
  13. private void Awake()
  14. {
  15. if (!_isInit.TryGetValue(gameObject.name, out int instanceID) && instanceID == 0)
  16. {
  17. DontDestroyOnLoad(gameObject);
  18. Init();
  19. }
  20. }
  21. private void LOG(string msg, bool warning = false)
  22. {
  23. if (!warning)
  24. Debug.Log($"<color=#00FF00>{msg}</color>");
  25. else
  26. Debug.LogWarning($"<color=#00FF00>{msg}</color>");
  27. }
  28. private void Init()
  29. {
  30. _isInit[gameObject.name] = GetInstanceID();
  31. #if UNITY_ANDROID && !UNITY_EDITOR
  32. serialPortUtility = gameObject.GetComponent<SerialPortUtilityPro>();
  33. serialPortUtility.OpenMethod = openMode;
  34. serialPortUtility.DeviceName = PortName;
  35. serialPortUtility.BaudRate = baudrate;
  36. serialPortUtility.StopBit = SerialPortUtilityPro.StopBitEnum.OneBit;
  37. serialPortUtility.DataBit = SerialPortUtilityPro.DataBitEnum.EightBit;
  38. serialPortUtility.SystemEventObject.AddListener(SystemEventObject);
  39. TrySerialOpenPort();
  40. #endif
  41. #if UNITY_EDITOR
  42. if (testMode)
  43. {
  44. var testBoard = Resources.Load<GameObject>("SerialPortTest");
  45. GameObject.Instantiate(testBoard);
  46. }
  47. #endif
  48. }
  49. private void TrySerialOpenPort()
  50. {
  51. serialPortUtility?.Open();
  52. }
  53. private void SystemEventObject(SerialPortUtilityPro arg0, string msg)
  54. {
  55. if (msg.Equals("OPEN_ERROR") || msg.Equals("PERMISSION_ERROR"))//串口开启失败 定时重试
  56. {
  57. #if UNITY_ANDROID && !UNITY_EDITOR
  58. Invoke("TrySerialOpenPort", 1f);
  59. #endif
  60. // LOG($"{PortName} 串口打开失败 重试中", true);
  61. }
  62. else if (msg.Equals("OPENED"))
  63. {
  64. SerialPortHelper.ins.OnConnect(arg0.DeviceName);
  65. RequestDeviceIno();//应用启动 请求一次设备信息
  66. LOG($"{PortName} 串口打开成功!");
  67. }
  68. else if (msg.Equals("CLOSED"))//串口断开
  69. {
  70. SerialPortHelper.ins.OnDisConnect(arg0.DeviceName);
  71. LOG($"{PortName} 串口关闭!");
  72. }
  73. }
  74. private void OnDestroy()
  75. {
  76. if (_isInit.TryGetValue(gameObject.name, out var instanceID) && instanceID == GetInstanceID())
  77. {
  78. LOG($"{PortName} 串口关闭");
  79. SerialPortHelper.ins.OnDisConnect(serialPortUtility?.DeviceName);
  80. serialPortUtility?.Close();
  81. _isInit.Remove(gameObject.name);
  82. }
  83. }
  84. /// <summary>
  85. /// 串口读取二进制流数据(界面挂载调用)
  86. /// </summary>
  87. /// <param name="data"></param>
  88. public void ReadStreamingBinary(object data)
  89. {
  90. PhraseData(data as byte[]);
  91. }
  92. public void TestRead(byte[] bytes)
  93. {
  94. PhraseData(bytes);
  95. }
  96. /// <summary>
  97. /// 解析串口数据
  98. /// </summary>
  99. /// <param name="bytes"></param>
  100. private void PhraseData(byte[] bytes)
  101. {
  102. string msg = string.Empty;
  103. for (int i = 0; i < bytes.Length; i++)
  104. {
  105. msg += bytes[i].ToString("x2") + " ";
  106. }
  107. LOG($"{PortName} 收到串口信息 msg={msg}!");
  108. if (bytes[0] == 0xAA)
  109. {
  110. var cmdID = bytes[1];
  111. switch (cmdID)
  112. {
  113. case 0x80://设备信息响应
  114. OnDeviceInfoBack(bytes);
  115. break;
  116. case 0x81://射击消息
  117. OnDeviceShoot(bytes);
  118. break;
  119. case 0x82://按键消息
  120. OnDeviceButton(bytes);
  121. break;
  122. }
  123. }
  124. }
  125. #region APP请求
  126. // 异或校验内容:命令+长度+数据内容
  127. /// <summary>
  128. /// app请求设备信息
  129. /// </summary>
  130. public void RequestDeviceIno()
  131. {
  132. List<byte> data = new List<byte>();
  133. data.Add(0xAA);//起始码
  134. data.Add(0x80);//命令号
  135. data.Add(0x05);//长度
  136. data.Add(0x85);//异或校验
  137. data.Add(0x55);//结束码
  138. serialPortUtility?.Write(data.ToArray());
  139. }
  140. #endregion
  141. #region 返回消息处理
  142. /// <summary>
  143. /// 设备信息响应
  144. /// </summary>
  145. private void OnDeviceInfoBack(byte[] bytes)// 0xAA 0x80 0x07 0x01 0x01 0x89 0x5D
  146. {
  147. Debug.Log($"{PortName} 收到设备信息响应!");
  148. var check = bytes[1] + bytes[2] + bytes[3] + bytes[4];//校验:命令+长度+数据内容
  149. //if (check != bytes[5])
  150. // LOG("OnDeviceInfoBack 数据校验错误!");
  151. //else
  152. //{
  153. //0x01 HOUYI Pro
  154. //0x02 ARTEMIS Pro
  155. //0x03 Pistol 1
  156. var deviceType = bytes[3];//设备类型
  157. Debug.Log("设备类型 Device Type: " + deviceType);
  158. switch (deviceType)
  159. {
  160. case 0x01:
  161. UserSettings.ins.selectDevicesName = "HOUYI Pro";
  162. DevicesHolder.ins.SwitchDeviceByType(AimDeviceType.HOUYIPRO);
  163. break;
  164. case 0x02:
  165. UserSettings.ins.selectDevicesName = "ARTEMIS Pro";
  166. DevicesHolder.ins.SwitchDeviceByType(AimDeviceType.ARTEMISPRO);
  167. break;
  168. case 0x03:
  169. UserSettings.ins.selectDevicesName = "Pistol M9";
  170. DevicesHolder.ins.SwitchDeviceByType(AimDeviceType.Gun);
  171. break;
  172. }
  173. UserSettings.ins.Save();
  174. //刷新界面
  175. var setting = FindAnyObjectByType<CustomUIView.BoxUserSettings>();
  176. setting?.FlushDeviceSelect();
  177. //}
  178. }
  179. /// <summary>
  180. /// 射击消息
  181. /// </summary>
  182. private void OnDeviceShoot(byte[] bytes)
  183. {
  184. LOG($"{PortName} 收到设备射击消息!");
  185. var check = bytes[1] + bytes[2] + bytes[3] + bytes[4];//校验:命令+长度+数据内容
  186. //if (check != bytes[5])
  187. //{
  188. // LOG("OnDeviceShoot 数据校验错误!");
  189. //}else
  190. SerialPortHelper.shoot?.Invoke(bytes);
  191. }
  192. /// <summary>
  193. /// 按键消息
  194. /// </summary>
  195. /// <param name="bytes"></param>
  196. private void OnDeviceButton(byte[] bytes)
  197. {
  198. Debug.Log($"{PortName} 收到设备按键消息!");
  199. var check = bytes[1] + bytes[2] + bytes[3];
  200. //校验:命令+长度+数据内容
  201. //if (check != bytes[4])
  202. //{
  203. // LOG("OnDeviceButton 数据校验错误!");
  204. //}
  205. //else
  206. if (string.IsNullOrEmpty(UserSettings.ins.selectDevicesName))
  207. //开机
  208. RequestDeviceIno();
  209. SerialPortHelper.aim?.Invoke(bytes);
  210. }
  211. #endregion
  212. }