ArrowSerialPort.cs 9.9 KB

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