BluetoothAim.cs 17 KB

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