ArrowSerialPort.cs 12 KB

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