ArrowSerialPort.cs 10.0 KB

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