ArrowSerialPort.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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. // 获取当前时间
  130. DateTime currentTime = DateTime.Now;
  131. LOG($"{PortName} 收到串口信息 msg={msg}!,接收时间:" + currentTime.ToString("yyyy-MM-dd HH:mm:ss.fff"));
  132. if (bytes[0] == 0xAA)
  133. {
  134. var cmdID = bytes[1];
  135. switch (cmdID)
  136. {
  137. case 0x80://设备信息响应
  138. OnDeviceInfoBack(bytes);
  139. break;
  140. case 0x81://射击消息
  141. if (CommonConfig.bDisableBluetooth) {
  142. // 获取当前时间
  143. DateTime currentTime1 = DateTime.Now;
  144. // 打印带毫秒的时间戳
  145. Debug.Log("射箭前:CurrentTime1: " + currentTime1.ToString("yyyy-MM-dd HH:mm:ss.fff"));
  146. //3 - APP在收到射箭消息后,立即回复相同的内容给设备端;
  147. serialPortUtility?.Write(bytes);
  148. DateTime currentTime3 = DateTime.Now;
  149. // 打印带毫秒的时间戳
  150. Debug.Log("*** 回复相同的内容给设备端 CurrentTime3: " + currentTime3.ToString("yyyy-MM-dd HH:mm:ss.fff"));
  151. }
  152. OnDeviceShoot(bytes);
  153. if (CommonConfig.bDisableBluetooth)
  154. {
  155. // 获取当前时间
  156. DateTime currentTime2 = DateTime.Now;
  157. // 打印带毫秒的时间戳
  158. Debug.Log("射箭后:CurrentTime2: " + currentTime2.ToString("yyyy-MM-dd HH:mm:ss.fff"));
  159. }
  160. break;
  161. case 0x82://按键消息
  162. OnDeviceButton(bytes);
  163. break;
  164. case 0x83://激光控制
  165. OnLightChange(bytes);
  166. break;
  167. case 0x84://弹夹消息(仅手枪)
  168. OnMagazinesInfo(bytes);
  169. break;
  170. }
  171. }
  172. else
  173. {
  174. if (CommonConfig.bDisableBluetooth) {
  175. //byte[] bytes = new byte[] { 0x0A, 0x00, 0x00, 0x00, // 1st timestamp
  176. // 0x0B, 0x00, 0x00, 0x00, // 2nd timestamp
  177. // 0x00, 0x01, 0x00, 0x00 // 3rd timestamp
  178. //};
  179. if (bytes.Length == 12)
  180. {
  181. // 解析并转换时间戳
  182. for (int i = 0; i < bytes.Length; i += 4)
  183. {
  184. // 提取 4 字节的时间戳
  185. uint timestamp = BitConverter.ToUInt32(bytes, i);
  186. // 转换为毫秒(单位是 100us)
  187. float timeInMilliseconds = timestamp * 0.1f;
  188. // 打印转换结果
  189. Debug.Log($"Timestamp (U32): {timestamp} => Time: {timeInMilliseconds} ms");
  190. }
  191. }
  192. }
  193. }
  194. }
  195. bool lightWaitClose = false;
  196. public void DelayCloseLight()
  197. {
  198. if (!lightWaitClose && hasOnceInceCoin)
  199. {
  200. LOG("游戏时间结束 延迟关闭激光");
  201. Invoke("DoDelayCloseLight", 60f);
  202. lightWaitClose = true;
  203. }
  204. }
  205. public void CancelDelayCloseLight()
  206. {
  207. LOG("关闭延迟关闭激光");
  208. lightWaitClose = false;
  209. CancelInvoke("DoDelayCloseLight");
  210. }
  211. private void DoDelayCloseLight()
  212. {
  213. RequestLightState(false);
  214. }
  215. //是否有过首次投币 没投币过 不关闭摄像头
  216. bool hasOnceInceCoin = false;
  217. #region APP请求
  218. // 异或校验内容:命令+长度+数据内容
  219. /// <summary>
  220. /// 设置激光状态
  221. /// </summary>
  222. public void RequestLightState(bool on, bool insertCoin = false)
  223. {
  224. if (insertCoin)
  225. hasOnceInceCoin = true;
  226. List<byte> data = new List<byte>();
  227. data.Add(0xAA);//起始码
  228. data.Add(0x83);//命令号
  229. data.Add(0x06);//长度
  230. data.Add((byte)(on ? 0x01 : 0x00));//长度
  231. byte temp = 0;
  232. for (int i = 1; i < data.Count; i++)
  233. {
  234. temp ^= data[i];
  235. }
  236. data.Add(temp);//异或校验
  237. data.Add(0x55);//结束码
  238. serialPortUtility?.Write(data.ToArray());
  239. LOG($"设置激光状态:{on}!");
  240. OnLightChange(data.ToArray());
  241. }
  242. /// <summary>
  243. /// app请求设备信息
  244. /// </summary>
  245. public void RequestDeviceIno()
  246. {
  247. List<byte> data = new List<byte>();
  248. data.Add(0xAA);//起始码
  249. data.Add(0x80);//命令号
  250. data.Add(0x05);//长度
  251. data.Add(0x85);//异或校验
  252. data.Add(0x55);//结束码
  253. serialPortUtility?.Write(data.ToArray());
  254. Debug.Log("发送心跳包");
  255. DevicesHolder.ins?.ShowConnectTip();
  256. }
  257. #endregion
  258. #region 返回消息处理
  259. /// <summary>
  260. /// 弹夹消息
  261. /// </summary>
  262. /// <param name="bytes"></param>
  263. private void OnMagazinesInfo(byte[] bytes)
  264. {
  265. Debug.Log($"{PortName} 收到弹夹消息!");
  266. SerialPortHelper.ins.OnMagazineChange(bytes);
  267. }
  268. private void OnLightChange(byte[] bytes)// 0xAA 0x83 0x06 0x01 0x84 0x55
  269. {
  270. lightWaitClose = false;
  271. Debug.Log($"{PortName} 激光状态变更回包!");
  272. var isOn = bytes[3] == 0x01;
  273. UserSettings.ins.lightState = isOn;
  274. }
  275. /// <summary>
  276. /// 设备信息响应
  277. /// </summary>
  278. private void OnDeviceInfoBack(byte[] bytes)// 0xAA 0x80 0x07 0x01 0x01 0x89 0x5D
  279. {
  280. Debug.Log($"{PortName} 收到设备信息响应!");
  281. var check = bytes[1] + bytes[2] + bytes[3] + bytes[4];//校验:命令+长度+数据内容
  282. if (HomeView.ins == null) {
  283. return;
  284. }
  285. //0x01 HOUYI Pro
  286. //0x02 ARTEMIS Pro
  287. //0x03 Pistol 1
  288. var deviceType = bytes[3];//设备类型
  289. Debug.Log("设备类型 Device Type: " + deviceType);
  290. switch (deviceType)
  291. {
  292. case 0x01:
  293. UserSettings.ins.selectDevicesName = "HOUYI Pro";
  294. DevicesHolder.ins.SwitchDeviceByType(AimDeviceType.HOUYIPRO);
  295. break;
  296. case 0x02:
  297. UserSettings.ins.selectDevicesName = "ARTEMIS Pro";
  298. DevicesHolder.ins.SwitchDeviceByType(AimDeviceType.ARTEMISPRO);
  299. break;
  300. case 0x03:
  301. UserSettings.ins.selectDevicesName = "Pistol M9";
  302. DevicesHolder.ins.SwitchDeviceByType(AimDeviceType.Gun);
  303. break;
  304. }
  305. UserSettings.ins.Save();
  306. //刷新界面
  307. var setting = FindAnyObjectByType<CustomUIView.BoxUserSettings>();
  308. setting?.FlushDeviceSelect();
  309. }
  310. /// <summary>
  311. /// 射击消息
  312. /// </summary>
  313. private void OnDeviceShoot(byte[] bytes)
  314. {
  315. LOG($"{PortName} 收到设备射击消息!");
  316. var check = bytes[1] + bytes[2] + bytes[3] + bytes[4];//校验:命令+长度+数据内容
  317. //if (check != bytes[5])
  318. //{
  319. // LOG("OnDeviceShoot 数据校验错误!");
  320. //}else
  321. SerialPortHelper.shoot?.Invoke(bytes);
  322. }
  323. /// <summary>
  324. /// 按键消息
  325. /// </summary>
  326. /// <param name="bytes"></param>
  327. private void OnDeviceButton(byte[] bytes)
  328. {
  329. Debug.Log($"{PortName} 收到设备按键消息!");
  330. var check = bytes[1] + bytes[2] + bytes[3];
  331. //校验:命令+长度+数据内容
  332. //if (check != bytes[4])
  333. //{
  334. // LOG("OnDeviceButton 数据校验错误!");
  335. //}
  336. //else
  337. if (string.IsNullOrEmpty(UserSettings.ins.selectDevicesName))
  338. //开机
  339. RequestDeviceIno();
  340. SerialPortHelper.aim?.Invoke(bytes);
  341. }
  342. #endregion
  343. }