BluetoothAim.cs 19 KB

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