BluetoothAim.cs 16 KB

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