BluetoothAim.cs 18 KB

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