BluetoothAim.cs 16 KB

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