BluetoothAim.cs 18 KB

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