ArrowSerialPort.cs 10 KB

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