BluetoothAim.cs 19 KB

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