BluetoothAim.cs 18 KB

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