ArrowSerialPort.cs 9.1 KB

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