BluetoothAim.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. using ArduinoBluetoothAPI;
  2. using System;
  3. using UnityEngine;
  4. using System.Collections.Generic;
  5. using UnityEngine.UI;
  6. using DG.Tweening;
  7. /* 蓝牙瞄准模块 */
  8. public class BluetoothAim : MonoBehaviour
  9. {
  10. SBLogger logger = new SBLogger(typeof(BluetoothAim).Name);
  11. readonly string targetDeviceName = "Bbow_20210501";
  12. string targetDeviceService {
  13. get {
  14. if (CommonConfig.devicePlan == 0 || CommonConfig.devicePlan == 3) return "0000fff0";
  15. return "6e400001";
  16. }
  17. }
  18. string targetDeviceCharacteristicWrite {
  19. get {
  20. if (CommonConfig.devicePlan == 0 || CommonConfig.devicePlan == 3) return "0000fff2";
  21. return "6e400002";
  22. }
  23. }
  24. string targetDeviceCharacteristicNotify {
  25. get {
  26. if (CommonConfig.devicePlan == 0 || CommonConfig.devicePlan == 3) return "0000fff1";
  27. return "6e400003";
  28. }
  29. }
  30. BluetoothHelper bluetoothHelper;
  31. BluetoothHelperCharacteristic characteristicWrite;
  32. BluetoothHelperService bluetoothService;
  33. string deviceName = "";
  34. bool canConnect = true;
  35. [SerializeField] Text textUI;
  36. public BluetoothStatusEnum status = BluetoothStatusEnum.Connect;
  37. public bool hasData = false;
  38. public long hasDataTime;
  39. public static bool scanLock = false; //防止同时扫描冲突
  40. public static BluetoothAim ins;
  41. void Start()
  42. {
  43. ins = this;
  44. InitAutoDormancy();
  45. #if UNITY_STANDALONE_WIN || UNITY_EDITOR
  46. new GameObject("BleUDP").AddComponent<BleUDP>();
  47. #endif
  48. }
  49. void OnDestroy()
  50. {
  51. DisconnectBleHelper();
  52. }
  53. private bool userDoConnect = false;
  54. private bool doConnect = false;
  55. public Func<bool> action_DoConnectInterceptor;
  56. public void DoConnect()
  57. {
  58. if (action_DoConnectInterceptor != null) {
  59. if (action_DoConnectInterceptor.Invoke()) return;
  60. }
  61. if (status == BluetoothStatusEnum.Connect)
  62. {
  63. userDoConnect = true;
  64. doConnect = true;
  65. SetStatus(BluetoothStatusEnum.Connecting);
  66. }
  67. else if (status == BluetoothStatusEnum.ConnectSuccess)
  68. {
  69. userDoConnect = false;
  70. doConnect = false;
  71. OnDisconnect();
  72. #if UNITY_STANDALONE_WIN || UNITY_EDITOR
  73. BleUDP.ins.Disconnect();
  74. #else
  75. DisconnectBleHelper();
  76. #endif
  77. }
  78. }
  79. void OnDisconnect()
  80. {
  81. hasData = false;
  82. canConnect = true;
  83. SetStatus(BluetoothStatusEnum.ConnectFail);
  84. BowCamera.isTouchMode = true;
  85. DestroyWhenDisconenct();
  86. if (AimHandler.ins) AimHandler.ins.msOld = default;
  87. }
  88. void Update()
  89. {
  90. if (userDoConnect && status == BluetoothStatusEnum.Connect)
  91. {
  92. DoConnect();
  93. }
  94. if (doConnect) Connect();
  95. }
  96. void SetStatus(BluetoothStatusEnum statusValue)
  97. {
  98. status = statusValue;
  99. if (status == BluetoothStatusEnum.ConnectFail)
  100. {
  101. Sequence sequence = DOTween.Sequence();
  102. sequence.AppendInterval(2f);
  103. sequence.AppendCallback(delegate ()
  104. {
  105. if (status == BluetoothStatusEnum.ConnectFail)
  106. {
  107. status = BluetoothStatusEnum.Connect;
  108. }
  109. });
  110. sequence.SetUpdate(true);
  111. DeviceReconnectView.Show();
  112. SimulateMouseController.ins?.SetBleConnected(false);
  113. } else if (status == BluetoothStatusEnum.ConnectSuccess) {
  114. SimulateMouseController.ins?.SetBleConnected(true);
  115. }
  116. }
  117. void DisconnectBleHelper()
  118. {
  119. if (bluetoothHelper != null) bluetoothHelper.Disconnect();
  120. }
  121. void Connect()
  122. {
  123. if (BluetoothShoot.scanLock)
  124. {
  125. return;
  126. }
  127. if (!canConnect)
  128. {
  129. return;
  130. }
  131. doConnect = false;
  132. scanLock = true;
  133. canConnect = false;
  134. SetStatus(BluetoothStatusEnum.Connecting);
  135. #if UNITY_STANDALONE_WIN || UNITY_EDITOR
  136. ConnectBleByUDP();
  137. #else
  138. ConnectBleHelper();
  139. #endif
  140. }
  141. void ConnectBleHelper()
  142. {
  143. try
  144. {
  145. BluetoothHelper.BLE = true;
  146. bluetoothHelper = BluetoothHelper.GetNewInstance();
  147. bluetoothHelper.OnConnected += (BluetoothHelper helper) =>
  148. {
  149. Log("连接成功\n" + helper.getDeviceName());
  150. SetStatus(BluetoothStatusEnum.ConnectSuccess);
  151. BowCamera.isTouchMode = false;
  152. logger.Log("连接成功");
  153. foreach (BluetoothHelperService service in helper.getGattServices())
  154. {
  155. logger.Log("待检测的服务名:" + service.getName());
  156. if (service.getName().ToLower().StartsWith(targetDeviceService))
  157. {
  158. bluetoothService = service;
  159. logger.Warn("匹配的服务名:" + service.getName());
  160. foreach (BluetoothHelperCharacteristic characteristic in service.getCharacteristics())
  161. {
  162. logger.Log("待检测的特征:" + characteristic.getName());
  163. if (characteristic.getName().ToLower().StartsWith(targetDeviceCharacteristicWrite))
  164. {
  165. characteristicWrite = characteristic;
  166. logger.Warn("匹配的写入特征:" + characteristic.getName());
  167. }
  168. else if (characteristic.getName().ToLower().StartsWith(targetDeviceCharacteristicNotify))
  169. {
  170. logger.Warn("匹配的订阅特征(准备):" + characteristic.getName());
  171. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristic.getName());
  172. ch.setService(bluetoothService.getName());
  173. bluetoothHelper.Subscribe(ch);
  174. logger.Warn("匹配的订阅特征(完成):" + characteristic.getName());
  175. }
  176. }
  177. }
  178. }
  179. logger.Log("服务匹配结束");
  180. // CallDelay(1, OpenInfrared);
  181. // CallDelay(2, OpenReceiveData);
  182. // CallDelay(3, RequestBattery);
  183. CallDelay(2, () =>
  184. {
  185. if (status != BluetoothStatusEnum.ConnectSuccess) return;
  186. logger.Log("初始化自动发送CMD");
  187. InitWhenConenct();
  188. });
  189. };
  190. bluetoothHelper.OnConnectionFailed += (BluetoothHelper helper) =>
  191. {
  192. Log("连接失败\n" + helper.getDeviceName());
  193. OnDisconnect();
  194. };
  195. bluetoothHelper.OnCharacteristicChanged += (helper, value, characteristic) =>
  196. {
  197. logger.Log(String.Join(",", value));
  198. if (!hasData) {
  199. hasDataTime = JC.CS.Utility.GetTimestamp();
  200. UploadMacAddress(value);
  201. }
  202. hasData = true;
  203. byte[] bytes = value;
  204. // Log(String.Join(",", bytes));
  205. BluetoothClient.UploadData(0, bytes);
  206. if (AimHandler.ins)
  207. {
  208. AimHandler.ins.OnDataReceived(bytes);
  209. }
  210. };
  211. int scanCount = 0;
  212. bluetoothHelper.OnScanEnded += (BluetoothHelper helper, LinkedList<BluetoothDevice> nearbyDevices) =>
  213. {
  214. scanLock = false;
  215. foreach (BluetoothDevice device in nearbyDevices)
  216. {
  217. if (device.DeviceName == targetDeviceName)
  218. {
  219. deviceName = device.DeviceName;
  220. bluetoothHelper.setDeviceName(deviceName);
  221. bluetoothHelper.Connect();
  222. Log("发现设备\n" + device.DeviceName);
  223. return;
  224. }
  225. }
  226. if (scanCount < 3)
  227. { //如果没扫描到,则重新扫描,达到延迟提示失败的效果
  228. scanCount++;
  229. scanLock = true;
  230. bluetoothHelper.ScanNearbyDevices();
  231. }
  232. else
  233. {
  234. canConnect = true;
  235. Log("没有发现设备");
  236. SetStatus(BluetoothStatusEnum.ConnectFail);
  237. }
  238. };
  239. bluetoothHelper.ScanNearbyDevices();
  240. Log("正在扫描设备");
  241. }
  242. catch (Exception e)
  243. {
  244. Debug.LogError(e.Message);
  245. Debug.LogError(e.StackTrace);
  246. scanLock = false;
  247. canConnect = true;
  248. // SetStatus(BluetoothStatusEnum.ConnectFail);
  249. status = BluetoothStatusEnum.Connect;
  250. userDoConnect = false;
  251. PopupMgr.ins.ShowTip(TextAutoLanguage2.GetTextByKey("ble-please-open-ble"));
  252. }
  253. }
  254. void ConnectBleByUDP()
  255. {
  256. try
  257. {
  258. BleUDP.ins.OnConnected = () =>
  259. {
  260. Log("连接成功\n" + deviceName);
  261. SetStatus(BluetoothStatusEnum.ConnectSuccess);
  262. BowCamera.isTouchMode = false;
  263. InitWhenConenct();
  264. };
  265. BleUDP.ins.OnConnectionFailed = () =>
  266. {
  267. Log("连接失败\n" + deviceName);
  268. OnDisconnect();
  269. };
  270. BleUDP.ins.OnCharacteristicChanged = (byte[] value) =>
  271. {
  272. if (!hasData) {
  273. hasDataTime = JC.CS.Utility.GetTimestamp();
  274. UploadMacAddress(value);
  275. }
  276. hasData = true;
  277. byte[] bytes = value;
  278. // Log(String.Join(",", bytes));
  279. BluetoothClient.UploadData(0, bytes);
  280. if (AimHandler.ins)
  281. {
  282. AimHandler.ins.OnDataReceived(bytes);
  283. }
  284. };
  285. BleUDP.ins.OnScanEnded = () =>
  286. {
  287. scanLock = false;
  288. deviceName = targetDeviceName;
  289. BleUDP.ins.Connect();
  290. Log("发现设备\n" + deviceName);
  291. };
  292. BleUDP.ins.ScanNearbyDevices();
  293. }
  294. catch (Exception e)
  295. {
  296. Debug.LogError(e.Message);
  297. Debug.LogError(e.StackTrace);
  298. scanLock = false;
  299. canConnect = true;
  300. SetStatus(BluetoothStatusEnum.ConnectFail);
  301. }
  302. }
  303. #region 自动进入/退出休眠状态, 这里做程指令发送队列,为了控制连续发送指令的间隔,避免硬件收不到或处理不过来
  304. class CmdToSend
  305. {
  306. public string[] cmds;
  307. public Action onComplete;
  308. public Func<bool> canDo;
  309. public CmdToSend(string[] cmds, Action onComplete, Func<bool> canDo)
  310. {
  311. this.cmds = cmds;
  312. this.onComplete = onComplete;
  313. this.canDo = canDo;
  314. }
  315. }
  316. Queue<CmdToSend> cmdWaitingList = new Queue<CmdToSend>();
  317. bool isSendCmdLocked = false;
  318. bool canAutoDormancy = false;
  319. bool isStartUp = false;
  320. JC.CS.CountLocker needModularAwake = new JC.CS.CountLocker();
  321. void CheckAndStartUp()
  322. {
  323. if (needModularAwake.IsLocked())
  324. {
  325. StartUp();
  326. }
  327. else
  328. {
  329. Dormancy();
  330. }
  331. }
  332. void InitAutoDormancy()
  333. {
  334. // GlobalEventCenter.ins.onGameSceneLoad += () => {
  335. // needModularAwake.Lock();
  336. // CheckAndStartUp();
  337. // };
  338. // GlobalEventCenter.ins.onGameSceneDestroy += () => {
  339. // needModularAwake.Unlock();
  340. // CheckAndStartUp();
  341. // };
  342. // GlobalEventCenter.ins.onSimulateMouseAwakeChanged += (waked) => {
  343. // if (waked) needModularAwake.Lock();
  344. // else needModularAwake.Unlock();;
  345. // CheckAndStartUp();
  346. // };
  347. // GlobalEventCenter.ins.onDeviceCalibrateViewAwakeChanged += (waked) => {
  348. // if (waked) needModularAwake.Lock();
  349. // else needModularAwake.Unlock();;
  350. // CheckAndStartUp();
  351. // };
  352. //暂时关闭自动休眠,默认是需要模块保持激活
  353. needModularAwake.Lock();
  354. }
  355. void InitWhenConenct()
  356. {
  357. canAutoDormancy = true;
  358. List<string> cmds = new List<string>();
  359. cmds.Add("M"); //获取Mac地址
  360. cmds.Add("b"); //确保开启stm32
  361. cmds.Add("b"); //获取初始电量
  362. cmds.Add("1"); //开启发送逻辑
  363. Action onComplete = null;
  364. if (needModularAwake.IsLocked())
  365. {
  366. cmds.Add("w"); //红外灯开启
  367. cmds.Add("3"); //九轴开启
  368. onComplete = () =>
  369. {
  370. isStartUp = true;
  371. };
  372. }
  373. else
  374. {
  375. cmds.Add("s"); //红外灯关闭
  376. cmds.Add("S"); //Stm32关闭
  377. cmds.Add("4"); //九轴关闭
  378. onComplete = () =>
  379. {
  380. isStartUp = false;
  381. };
  382. }
  383. SendCDM(null, onComplete, cmds.ToArray());
  384. }
  385. void DestroyWhenDisconenct()
  386. {
  387. canAutoDormancy = false;
  388. sendCMD_CheckAndDoStop(null);
  389. }
  390. //启动
  391. void StartUp()
  392. {
  393. SendCDM(() =>
  394. {
  395. return !isStartUp;
  396. }, () =>
  397. {
  398. isStartUp = true;
  399. }, "b", "w", "3");
  400. }
  401. //休眠
  402. void Dormancy()
  403. {
  404. SendCDM(() =>
  405. {
  406. return isStartUp;
  407. }, () =>
  408. {
  409. isStartUp = false;
  410. }, "4", "s", "S");
  411. }
  412. void SendCDM(Func<bool> canDo, Action onComplete, params string[] cmds)
  413. {
  414. CmdToSend cmdToSend = new CmdToSend(cmds, onComplete, canDo);
  415. if (isSendCmdLocked)
  416. {
  417. cmdWaitingList.Enqueue(cmdToSend);
  418. return;
  419. }
  420. sendCMD_NotCheck(cmdToSend);
  421. }
  422. void sendCMD_NotCheck(CmdToSend cmdToSend)
  423. {
  424. if (cmdToSend.canDo != null && !cmdToSend.canDo.Invoke())
  425. {
  426. sendCMD_CheckNext();
  427. return;
  428. }
  429. isSendCmdLocked = true;
  430. Sequence sequence = DOTween.Sequence();
  431. sequence.PrependInterval(0.3f);
  432. foreach (var cmd in cmdToSend.cmds)
  433. {
  434. sequence.AppendCallback(() =>
  435. {
  436. bool stopped = sendCMD_CheckAndDoStop(sequence);
  437. if (!stopped) WriteData(cmd);
  438. });
  439. sequence.AppendInterval(0.5f);
  440. }
  441. sequence.AppendCallback(() =>
  442. {
  443. bool stopped = sendCMD_CheckAndDoStop(sequence);
  444. if (!stopped)
  445. {
  446. isSendCmdLocked = false;
  447. cmdToSend.onComplete?.Invoke();
  448. sendCMD_CheckNext();
  449. }
  450. });
  451. sequence.SetUpdate(true);
  452. }
  453. void sendCMD_CheckNext()
  454. {
  455. if (cmdWaitingList.Count <= 0) return;
  456. CmdToSend cmdToSend = cmdWaitingList.Dequeue();
  457. sendCMD_NotCheck(cmdToSend);
  458. }
  459. bool sendCMD_CheckAndDoStop(Sequence sequence)
  460. {
  461. if (canAutoDormancy) return false;
  462. isStartUp = false;
  463. isSendCmdLocked = false;
  464. cmdWaitingList.Clear();
  465. if (sequence != null) sequence.Kill();
  466. return true;
  467. }
  468. #endregion
  469. public void RequestBattery()
  470. {
  471. if (!isStartUp) return;
  472. if (isSendCmdLocked) return;
  473. WriteData("b");
  474. }
  475. public void ReplyInfraredShoot()
  476. {
  477. if (isSendCmdLocked) return;
  478. WriteData("I");
  479. }
  480. void CallDelay(float delayTime, TweenCallback callback)
  481. {
  482. Sequence sequence = DOTween.Sequence();
  483. sequence.PrependInterval(delayTime).AppendCallback(callback);
  484. sequence.SetUpdate(true);
  485. }
  486. public void WriteData(string data)
  487. {
  488. logger.Log("发送CMD(准备):" + data);
  489. #if UNITY_STANDALONE_WIN || UNITY_EDITOR
  490. BleUDP.ins.SendMsg(data);
  491. #else
  492. if (DebugDeviceCMD.ins) DebugDeviceCMD.ins.ShowCMD(data);
  493. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristicWrite.getName());
  494. ch.setService(bluetoothService.getName());
  495. bluetoothHelper.WriteCharacteristic(ch, data);
  496. #endif
  497. logger.Log("发送CMD(完成):" + data);
  498. }
  499. void Log(string text)
  500. {
  501. if (textUI)
  502. {
  503. textUI.text = text;
  504. }
  505. }
  506. void UploadMacAddress(byte[] bytes) {
  507. string mac = System.Text.Encoding.ASCII.GetString(bytes);
  508. if (mac != null) mac = mac.Trim();
  509. if (CheckIsMacValid(mac)) {
  510. LoginMgr.myUserInfo.mac = mac;
  511. SaveMac(mac);
  512. }
  513. }
  514. bool CheckIsMacValid(string mac) {
  515. if (mac == null) return false;
  516. if (!mac.StartsWith("{")) return false;
  517. if (!mac.EndsWith("}")) return false;
  518. if (!mac.Contains(":")) return false;
  519. char[] validChars = {'{','}',':','0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
  520. foreach (var c in mac.ToCharArray()) {
  521. if (Array.IndexOf(validChars, c) == -1) return false;
  522. }
  523. return true;
  524. }
  525. void SaveMac(string mac) {
  526. Action<Newtonsoft.Json.Linq.JToken> cb = (Newtonsoft.Json.Linq.JToken o) => {
  527. string gyrStr = o.Value<string>("gyr");
  528. string magStr = o.Value<string>("mag");
  529. AimHandler.ins.InitGyr(gyrStr);
  530. AimHandler.ins.InitMag(magStr);
  531. };
  532. UserPlayer.ins.call("userComp.saveMac", new object[]{mac}, cb);
  533. }
  534. // #region 测试mac获取服务端校准记录
  535. // void Awake()
  536. // {
  537. // StartCoroutine(qqq());
  538. // }
  539. // System.Collections.IEnumerator qqq() {
  540. // while (LoginMgr.myUserInfo.id == 0) {
  541. // yield return null;
  542. // }
  543. // SaveMac("123");
  544. // StartCoroutine(AimHandler.ins.SaveGyr());
  545. // StartCoroutine(AimHandler.ins.SaveMag());
  546. // }
  547. // #endregion
  548. }