BluetoothAim.cs 20 KB

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