BluetoothAim.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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 = 4;
  178. SetStatus(BluetoothStatusEnum.Connecting);
  179. #if UNITY_STANDALONE_WIN || UNITY_EDITOR
  180. ConnectBleByUDP();
  181. #else
  182. ConnectBleHelper();
  183. #endif
  184. }
  185. int _scanCanRetryCount = 4;
  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. });
  248. };
  249. bluetoothHelper.OnConnectionFailed += (BluetoothHelper helper) =>
  250. {
  251. Log("连接失败\n" + helper.getDeviceName());
  252. OnDisconnect();
  253. };
  254. bluetoothHelper.OnCharacteristicChanged += (helper, value, characteristic) =>
  255. {
  256. if (status != BluetoothStatusEnum.ConnectSuccess) return;
  257. // logger.Log(String.Join(",", value));
  258. if (!hasData) {
  259. hasData = true;
  260. hasDataTime = JCUnityLib.TimeUtils.GetTimestamp();
  261. }
  262. dataCount++;
  263. if (curMac == null && dataCount < 500) {
  264. UploadMacAddress(value);
  265. }
  266. byte[] bytes = value;
  267. // Log(String.Join(",", bytes));
  268. BluetoothClient.UploadData(0, bytes);
  269. if (AimHandler.ins)
  270. {
  271. AimHandler.ins.OnDataReceived(bytes);
  272. }
  273. };
  274. bluetoothHelper.OnScanEnded += (BluetoothHelper helper, LinkedList<BluetoothDevice> nearbyDevices) =>
  275. {
  276. scanLock = false;
  277. if (connectCanceled) {
  278. userDoConnect = false;
  279. canConnect = true;
  280. status = BluetoothStatusEnum.Connect;
  281. Debug.Log("ble connectCanceled");
  282. return;
  283. }
  284. foreach (BluetoothDevice device in nearbyDevices)
  285. {
  286. Log("发现设备 " + device.DeviceName);
  287. if (device.DeviceName == targetDeviceName)
  288. {
  289. deviceName = device.DeviceName;
  290. bluetoothHelper.setDeviceName(deviceName);
  291. bluetoothHelper.Connect();
  292. Log("匹配设备 " + device.DeviceName);
  293. return;
  294. }
  295. }
  296. if (_scanCanRetryCount > 0) {
  297. _scanCanRetryCount--;
  298. scanLock = true;
  299. ConnectBleHelper();
  300. } else {
  301. userDoConnect = false;
  302. canConnect = true;
  303. Log("没有发现设备");
  304. TextAutoLanguage2.GetTextByKey("ble-dev-notfound");
  305. SetStatus(BluetoothStatusEnum.ConnectFail);
  306. }
  307. };
  308. bluetoothHelper.ScanNearbyDevices();
  309. Log("正在扫描设备");
  310. }
  311. catch (Exception e)
  312. {
  313. Debug.LogError(e);
  314. HandleConnectException(TextAutoLanguage2.GetTextByKey("ble-please-open-ble"));
  315. }
  316. }
  317. void HandleConnectException(string errorText)
  318. {
  319. scanLock = false;
  320. canConnect = true;
  321. // SetStatus(BluetoothStatusEnum.ConnectFail);
  322. status = BluetoothStatusEnum.Connect;
  323. userDoConnect = false;
  324. PopupMgr.ins.ShowTip(errorText);
  325. }
  326. void ConnectBleByUDP()
  327. {
  328. try
  329. {
  330. BleUDP.ins.OnConnected = () =>
  331. {
  332. Log("连接成功\n" + deviceName);
  333. SetStatus(BluetoothStatusEnum.ConnectSuccess);
  334. BowCamera.isTouchMode = false;
  335. InitWhenConenct();
  336. };
  337. BleUDP.ins.OnConnectionFailed = () =>
  338. {
  339. Log("连接失败\n" + deviceName);
  340. OnDisconnect();
  341. };
  342. BleUDP.ins.OnCharacteristicChanged = (byte[] value) =>
  343. {
  344. if (!hasData) {
  345. hasDataTime = JCUnityLib.TimeUtils.GetTimestamp();
  346. UploadMacAddress(value);
  347. }
  348. hasData = true;
  349. byte[] bytes = value;
  350. // Log(String.Join(",", bytes));
  351. BluetoothClient.UploadData(0, bytes);
  352. if (AimHandler.ins)
  353. {
  354. AimHandler.ins.OnDataReceived(bytes);
  355. }
  356. };
  357. BleUDP.ins.OnScanEnded = () =>
  358. {
  359. scanLock = false;
  360. deviceName = targetDeviceName;
  361. BleUDP.ins.Connect();
  362. Log("发现设备\n" + deviceName);
  363. };
  364. BleUDP.ins.ScanNearbyDevices();
  365. }
  366. catch (Exception e)
  367. {
  368. Debug.LogError(e.Message);
  369. Debug.LogError(e.StackTrace);
  370. scanLock = false;
  371. canConnect = true;
  372. SetStatus(BluetoothStatusEnum.ConnectFail);
  373. }
  374. }
  375. #region 自动进入/退出休眠状态, 这里做程指令发送队列,为了控制连续发送指令的间隔,避免硬件收不到或处理不过来
  376. class CmdToSend
  377. {
  378. public string[] cmds;
  379. public Action onComplete;
  380. public Func<bool> canDo;
  381. public CmdToSend(string[] cmds, Action onComplete, Func<bool> canDo)
  382. {
  383. this.cmds = cmds;
  384. this.onComplete = onComplete;
  385. this.canDo = canDo;
  386. }
  387. }
  388. Queue<CmdToSend> cmdWaitingList = new Queue<CmdToSend>();
  389. bool isSendCmdLocked = false;
  390. bool canAutoDormancy = false;
  391. bool isStartUp = false;
  392. JCUnityLib.CountLock needModularAwake = new JCUnityLib.CountLock();
  393. void CheckAndStartUp()
  394. {
  395. if (needModularAwake.IsLocked())
  396. {
  397. StartUp();
  398. }
  399. else
  400. {
  401. Dormancy();
  402. }
  403. }
  404. void InitAutoDormancy()
  405. {
  406. // GlobalEventCenter.ins.onGameSceneLoad += () => {
  407. // needModularAwake.Lock();
  408. // CheckAndStartUp();
  409. // };
  410. // GlobalEventCenter.ins.onGameSceneDestroy += () => {
  411. // needModularAwake.Unlock();
  412. // CheckAndStartUp();
  413. // };
  414. // GlobalEventCenter.ins.onSimulateMouseAwakeChanged += (waked) => {
  415. // if (waked) needModularAwake.Lock();
  416. // else needModularAwake.Unlock();;
  417. // CheckAndStartUp();
  418. // };
  419. // GlobalEventCenter.ins.onDeviceCalibrateViewAwakeChanged += (waked) => {
  420. // if (waked) needModularAwake.Lock();
  421. // else needModularAwake.Unlock();;
  422. // CheckAndStartUp();
  423. // };
  424. //暂时关闭自动休眠,默认是需要模块保持激活
  425. needModularAwake.Lock();
  426. }
  427. void InitWhenConenct()
  428. {
  429. canAutoDormancy = true;
  430. List<string> cmds = new List<string>();
  431. cmds.Add("M"); //获取Mac地址
  432. cmds.Add("b"); //确保开启stm32
  433. cmds.Add("b"); //获取初始电量
  434. cmds.Add("1"); //开启发送逻辑
  435. Action onComplete = null;
  436. if (needModularAwake.IsLocked())
  437. {
  438. cmds.Add("w"); //红外灯开启
  439. cmds.Add("3"); //九轴开启
  440. onComplete = () =>
  441. {
  442. isStartUp = true;
  443. };
  444. }
  445. else
  446. {
  447. cmds.Add("s"); //红外灯关闭
  448. cmds.Add("S"); //Stm32关闭
  449. cmds.Add("4"); //九轴关闭
  450. onComplete = () =>
  451. {
  452. isStartUp = false;
  453. };
  454. }
  455. SendCDM(null, onComplete, cmds.ToArray());
  456. }
  457. void DestroyWhenDisconenct()
  458. {
  459. canAutoDormancy = false;
  460. sendCMD_CheckAndDoStop(null);
  461. }
  462. //启动
  463. void StartUp()
  464. {
  465. SendCDM(() =>
  466. {
  467. return !isStartUp;
  468. }, () =>
  469. {
  470. isStartUp = true;
  471. }, "b", "w", "3");
  472. }
  473. //休眠
  474. void Dormancy()
  475. {
  476. SendCDM(() =>
  477. {
  478. return isStartUp;
  479. }, () =>
  480. {
  481. isStartUp = false;
  482. }, "4", "s", "S");
  483. }
  484. void SendCDM(Func<bool> canDo, Action onComplete, params string[] cmds)
  485. {
  486. CmdToSend cmdToSend = new CmdToSend(cmds, onComplete, canDo);
  487. if (isSendCmdLocked)
  488. {
  489. cmdWaitingList.Enqueue(cmdToSend);
  490. return;
  491. }
  492. sendCMD_NotCheck(cmdToSend);
  493. }
  494. void sendCMD_NotCheck(CmdToSend cmdToSend)
  495. {
  496. if (cmdToSend.canDo != null && !cmdToSend.canDo.Invoke())
  497. {
  498. sendCMD_CheckNext();
  499. return;
  500. }
  501. isSendCmdLocked = true;
  502. Sequence sequence = DOTween.Sequence();
  503. sequence.PrependInterval(0.3f);
  504. foreach (var cmd in cmdToSend.cmds)
  505. {
  506. sequence.AppendCallback(() =>
  507. {
  508. bool stopped = sendCMD_CheckAndDoStop(sequence);
  509. if (!stopped) WriteData(cmd);
  510. });
  511. sequence.AppendInterval(0.5f);
  512. }
  513. sequence.AppendCallback(() =>
  514. {
  515. bool stopped = sendCMD_CheckAndDoStop(sequence);
  516. if (!stopped)
  517. {
  518. isSendCmdLocked = false;
  519. cmdToSend.onComplete?.Invoke();
  520. sendCMD_CheckNext();
  521. }
  522. });
  523. sequence.SetUpdate(true);
  524. }
  525. void sendCMD_CheckNext()
  526. {
  527. if (cmdWaitingList.Count <= 0) return;
  528. CmdToSend cmdToSend = cmdWaitingList.Dequeue();
  529. sendCMD_NotCheck(cmdToSend);
  530. }
  531. bool sendCMD_CheckAndDoStop(Sequence sequence)
  532. {
  533. if (canAutoDormancy) return false;
  534. isStartUp = false;
  535. isSendCmdLocked = false;
  536. cmdWaitingList.Clear();
  537. if (sequence != null) sequence.Kill();
  538. return true;
  539. }
  540. #endregion
  541. public void RequestBattery()
  542. {
  543. if (!isStartUp) return;
  544. if (isSendCmdLocked) return;
  545. WriteData("b");
  546. }
  547. public void ReplyInfraredShoot()
  548. {
  549. if (isSendCmdLocked) return;
  550. WriteData("I");
  551. }
  552. void CallDelay(float delayTime, TweenCallback callback)
  553. {
  554. Sequence sequence = DOTween.Sequence();
  555. sequence.PrependInterval(delayTime).AppendCallback(callback);
  556. sequence.SetUpdate(true);
  557. }
  558. public void WriteData(string data)
  559. {
  560. #if UNITY_STANDALONE_WIN || UNITY_EDITOR
  561. BleUDP.ins.SendMsg(data);
  562. #else
  563. if (DebugDeviceCMD.ins) DebugDeviceCMD.ins.ShowCMD(data);
  564. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristicWrite.getName());
  565. ch.setService(bluetoothService.getName());
  566. bluetoothHelper.WriteCharacteristic(ch, data);
  567. #endif
  568. }
  569. void Log(string text)
  570. {
  571. if (textUI)
  572. {
  573. textUI.text = text;
  574. }
  575. Debug.Log(string.Format("[{0}]{1}", typeof(BluetoothAim).Name, text));
  576. }
  577. [NonSerialized] public string curMac;
  578. void UploadMacAddress(byte[] bytes) {
  579. string mac = System.Text.Encoding.ASCII.GetString(bytes);
  580. if (mac != null) mac = mac.Trim();
  581. if (CheckIsMacValid(mac)) {
  582. curMac = mac;
  583. SideTipView.ShowTip("Mac获取成功:" + mac, Color.white);
  584. } else {
  585. SideTipView.ShowTip("Mac获取失败", Color.yellow);
  586. }
  587. }
  588. bool CheckIsMacValid(string mac) {
  589. if (mac == null) return false;
  590. if (!mac.StartsWith("{")) return false;
  591. if (!mac.EndsWith("}")) return false;
  592. if (!mac.Contains(":")) return false;
  593. char[] validChars = {'{','}',':','0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
  594. foreach (var c in mac.ToCharArray()) {
  595. if (Array.IndexOf(validChars, c) == -1) return false;
  596. }
  597. if (mac.Length != 19) return false;
  598. string macNoneFrame = mac.Substring(1, mac.Length - 2);
  599. string[] macNoneFrameSplits = macNoneFrame.Split(':');
  600. if (macNoneFrameSplits.Length != 6) return false;
  601. foreach (var item in macNoneFrameSplits) {
  602. if (item.Length != 2) return false;
  603. foreach (var c in item.ToCharArray())
  604. if (Array.IndexOf(validChars, c) < 3) return false;
  605. }
  606. return true;
  607. }
  608. }