BluetoothAim.cs 19 KB

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