BluetoothAim.cs 18 KB

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