BluetoothAim.cs 19 KB

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