ArrowSerialPort.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. DevicesHolder.ins?.ShowConnectTip();
  190. }
  191. #endregion
  192. #region 返回消息处理
  193. /// <summary>
  194. /// 弹夹消息
  195. /// </summary>
  196. /// <param name="bytes"></param>
  197. private void OnMagazinesInfo(byte[] bytes)
  198. {
  199. Debug.Log($"{PortName} 收到弹夹消息!");
  200. SerialPortHelper.ins.OnMagazineChange(bytes);
  201. }
  202. private void OnLightChange(byte[] bytes)// 0xAA 0x83 0x06 0x01 0x84 0x55
  203. {
  204. lightWaitClose = false;
  205. Debug.Log($"{PortName} 激光状态变更回包!");
  206. var isOn = bytes[3] == 0x01;
  207. UserSettings.ins.lightState = isOn;
  208. }
  209. /// <summary>
  210. /// 设备信息响应
  211. /// </summary>
  212. private void OnDeviceInfoBack(byte[] bytes)// 0xAA 0x80 0x07 0x01 0x01 0x89 0x5D
  213. {
  214. Debug.Log($"{PortName} 收到设备信息响应!");
  215. var check = bytes[1] + bytes[2] + bytes[3] + bytes[4];//校验:命令+长度+数据内容
  216. //if (check != bytes[5])
  217. // LOG("OnDeviceInfoBack 数据校验错误!");
  218. //else
  219. //{
  220. //0x01 HOUYI Pro
  221. //0x02 ARTEMIS Pro
  222. //0x03 Pistol 1
  223. var deviceType = bytes[3];//设备类型
  224. Debug.Log("设备类型 Device Type: " + deviceType);
  225. switch (deviceType)
  226. {
  227. case 0x01:
  228. UserSettings.ins.selectDevicesName = "HOUYI Pro";
  229. DevicesHolder.ins.SwitchDeviceByType(AimDeviceType.HOUYIPRO);
  230. break;
  231. case 0x02:
  232. UserSettings.ins.selectDevicesName = "ARTEMIS Pro";
  233. DevicesHolder.ins.SwitchDeviceByType(AimDeviceType.ARTEMISPRO);
  234. break;
  235. case 0x03:
  236. UserSettings.ins.selectDevicesName = "Pistol M9";
  237. DevicesHolder.ins.SwitchDeviceByType(AimDeviceType.Gun);
  238. break;
  239. }
  240. UserSettings.ins.Save();
  241. //刷新界面
  242. var setting = FindAnyObjectByType<CustomUIView.BoxUserSettings>();
  243. setting?.FlushDeviceSelect();
  244. //}
  245. }
  246. /// <summary>
  247. /// 射击消息
  248. /// </summary>
  249. private void OnDeviceShoot(byte[] bytes)
  250. {
  251. LOG($"{PortName} 收到设备射击消息!");
  252. var check = bytes[1] + bytes[2] + bytes[3] + bytes[4];//校验:命令+长度+数据内容
  253. //if (check != bytes[5])
  254. //{
  255. // LOG("OnDeviceShoot 数据校验错误!");
  256. //}else
  257. SerialPortHelper.shoot?.Invoke(bytes);
  258. }
  259. /// <summary>
  260. /// 按键消息
  261. /// </summary>
  262. /// <param name="bytes"></param>
  263. private void OnDeviceButton(byte[] bytes)
  264. {
  265. Debug.Log($"{PortName} 收到设备按键消息!");
  266. var check = bytes[1] + bytes[2] + bytes[3];
  267. //校验:命令+长度+数据内容
  268. //if (check != bytes[4])
  269. //{
  270. // LOG("OnDeviceButton 数据校验错误!");
  271. //}
  272. //else
  273. if (string.IsNullOrEmpty(UserSettings.ins.selectDevicesName))
  274. //开机
  275. RequestDeviceIno();
  276. SerialPortHelper.aim?.Invoke(bytes);
  277. }
  278. #endregion
  279. }