ArrowSerialPort.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. //应用启动 间隔十秒请求一次设备信息
  66. InvokeRepeating("RequestDeviceIno", 0f, 10f);
  67. LOG($"{PortName} 串口打开成功!");
  68. }
  69. else if (msg.Equals("CLOSED"))//串口断开
  70. {
  71. SerialPortHelper.ins.OnDisConnect(arg0.DeviceName);
  72. LOG($"{PortName} 串口关闭!");
  73. }
  74. }
  75. private void OnDestroy()
  76. {
  77. if (_isInit.TryGetValue(gameObject.name, out var instanceID) && instanceID == GetInstanceID())
  78. {
  79. LOG($"{PortName} 串口关闭");
  80. SerialPortHelper.ins.OnDisConnect(serialPortUtility?.DeviceName);
  81. serialPortUtility?.Close();
  82. _isInit.Remove(gameObject.name);
  83. }
  84. }
  85. /// <summary>
  86. /// 串口读取二进制流数据(界面挂载调用)
  87. /// </summary>
  88. /// <param name="data"></param>
  89. public void ReadStreamingBinary(object data)
  90. {
  91. PhraseData(data as byte[]);
  92. }
  93. public void TestRead(byte[] bytes)
  94. {
  95. PhraseData(bytes);
  96. }
  97. /// <summary>
  98. /// 解析串口数据
  99. /// </summary>
  100. /// <param name="bytes"></param>
  101. private void PhraseData(byte[] bytes)
  102. {
  103. string msg = string.Empty;
  104. for (int i = 0; i < bytes.Length; i++)
  105. {
  106. msg += bytes[i].ToString("x2") + " ";
  107. }
  108. LOG($"{PortName} 收到串口信息 msg={msg}!");
  109. if (bytes[0] == 0xAA)
  110. {
  111. var cmdID = bytes[1];
  112. switch (cmdID)
  113. {
  114. case 0x80://设备信息响应
  115. OnDeviceInfoBack(bytes);
  116. break;
  117. case 0x81://射击消息
  118. OnDeviceShoot(bytes);
  119. break;
  120. case 0x82://按键消息
  121. OnDeviceButton(bytes);
  122. break;
  123. case 0x83://激光控制
  124. OnLightChange(bytes);
  125. break;
  126. case 0x84://弹夹消息(仅手枪)
  127. OnMagazinesInfo(bytes);
  128. break;
  129. }
  130. }
  131. }
  132. bool lightWaitClose = false;
  133. public void DelayCloseLight()
  134. {
  135. if (!lightWaitClose)
  136. {
  137. LOG("游戏时间结束 延迟关闭激光");
  138. Invoke("DoDelayCloseLight", 60f);
  139. lightWaitClose = true;
  140. }
  141. }
  142. public void CancelDelayCloseLight()
  143. {
  144. LOG("关闭延迟关闭激光");
  145. lightWaitClose = false;
  146. CancelInvoke("DoDelayCloseLight");
  147. }
  148. private void DoDelayCloseLight()
  149. {
  150. RequestLightState(false);
  151. }
  152. #region APP请求
  153. // 异或校验内容:命令+长度+数据内容
  154. /// <summary>
  155. /// 设置激光状态
  156. /// </summary>
  157. public void RequestLightState(bool on)
  158. {
  159. List<byte> data = new List<byte>();
  160. data.Add(0xAA);//起始码
  161. data.Add(0x83);//命令号
  162. data.Add(0x06);//长度
  163. data.Add((byte)(on ? 0x01 : 0x00));//长度
  164. byte temp = 0;
  165. for (int i = 1; i < data.Count; i++)
  166. {
  167. temp ^= data[i];
  168. }
  169. data.Add(temp);//异或校验
  170. data.Add(0x55);//结束码
  171. serialPortUtility?.Write(data.ToArray());
  172. LOG($"设置激光状态:{on}!");
  173. OnLightChange(data.ToArray());
  174. }
  175. /// <summary>
  176. /// app请求设备信息
  177. /// </summary>
  178. public void RequestDeviceIno()
  179. {
  180. List<byte> data = new List<byte>();
  181. data.Add(0xAA);//起始码
  182. data.Add(0x80);//命令号
  183. data.Add(0x05);//长度
  184. data.Add(0x85);//异或校验
  185. data.Add(0x55);//结束码
  186. serialPortUtility?.Write(data.ToArray());
  187. }
  188. #endregion
  189. #region 返回消息处理
  190. /// <summary>
  191. /// 弹夹消息
  192. /// </summary>
  193. /// <param name="bytes"></param>
  194. private void OnMagazinesInfo(byte[] bytes)
  195. {
  196. Debug.Log($"{PortName} 收到弹夹消息!");
  197. SerialPortHelper.ins.OnMagazineChange(bytes);
  198. }
  199. private void OnLightChange(byte[] bytes)// 0xAA 0x83 0x06 0x01 0x84 0x55
  200. {
  201. lightWaitClose = false;
  202. Debug.Log($"{PortName} 激光状态变更回包!");
  203. var isOn = bytes[3] == 0x01;
  204. UserSettings.ins.lightState = isOn;
  205. }
  206. /// <summary>
  207. /// 设备信息响应
  208. /// </summary>
  209. private void OnDeviceInfoBack(byte[] bytes)// 0xAA 0x80 0x07 0x01 0x01 0x89 0x5D
  210. {
  211. Debug.Log($"{PortName} 收到设备信息响应!");
  212. var check = bytes[1] + bytes[2] + bytes[3] + bytes[4];//校验:命令+长度+数据内容
  213. //if (check != bytes[5])
  214. // LOG("OnDeviceInfoBack 数据校验错误!");
  215. //else
  216. //{
  217. //0x01 HOUYI Pro
  218. //0x02 ARTEMIS Pro
  219. //0x03 Pistol 1
  220. var deviceType = bytes[3];//设备类型
  221. Debug.Log("设备类型 Device Type: " + deviceType);
  222. switch (deviceType)
  223. {
  224. case 0x01:
  225. UserSettings.ins.selectDevicesName = "HOUYI Pro";
  226. DevicesHolder.ins.SwitchDeviceByType(AimDeviceType.HOUYIPRO);
  227. break;
  228. case 0x02:
  229. UserSettings.ins.selectDevicesName = "ARTEMIS Pro";
  230. DevicesHolder.ins.SwitchDeviceByType(AimDeviceType.ARTEMISPRO);
  231. break;
  232. case 0x03:
  233. UserSettings.ins.selectDevicesName = "Pistol M9";
  234. DevicesHolder.ins.SwitchDeviceByType(AimDeviceType.Gun);
  235. break;
  236. }
  237. UserSettings.ins.Save();
  238. //刷新界面
  239. var setting = FindAnyObjectByType<CustomUIView.BoxUserSettings>();
  240. setting?.FlushDeviceSelect();
  241. //}
  242. }
  243. /// <summary>
  244. /// 射击消息
  245. /// </summary>
  246. private void OnDeviceShoot(byte[] bytes)
  247. {
  248. LOG($"{PortName} 收到设备射击消息!");
  249. var check = bytes[1] + bytes[2] + bytes[3] + bytes[4];//校验:命令+长度+数据内容
  250. //if (check != bytes[5])
  251. //{
  252. // LOG("OnDeviceShoot 数据校验错误!");
  253. //}else
  254. SerialPortHelper.shoot?.Invoke(bytes);
  255. }
  256. /// <summary>
  257. /// 按键消息
  258. /// </summary>
  259. /// <param name="bytes"></param>
  260. private void OnDeviceButton(byte[] bytes)
  261. {
  262. Debug.Log($"{PortName} 收到设备按键消息!");
  263. var check = bytes[1] + bytes[2] + bytes[3];
  264. //校验:命令+长度+数据内容
  265. //if (check != bytes[4])
  266. //{
  267. // LOG("OnDeviceButton 数据校验错误!");
  268. //}
  269. //else
  270. if (string.IsNullOrEmpty(UserSettings.ins.selectDevicesName))
  271. //开机
  272. RequestDeviceIno();
  273. SerialPortHelper.aim?.Invoke(bytes);
  274. }
  275. #endregion
  276. }