BluetoothAim.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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) hasDataTime = JC.CS.Utility.GetTimestamp();
  181. hasData = true;
  182. byte[] bytes = value;
  183. // Log(String.Join(",", bytes));
  184. BluetoothClient.UploadData(0, bytes);
  185. if (AimHandler.ins)
  186. {
  187. AimHandler.ins.OnDataReceived(bytes);
  188. }
  189. };
  190. int scanCount = 0;
  191. bluetoothHelper.OnScanEnded += (BluetoothHelper helper, LinkedList<BluetoothDevice> nearbyDevices) =>
  192. {
  193. scanLock = false;
  194. foreach (BluetoothDevice device in nearbyDevices)
  195. {
  196. if (device.DeviceName == targetDeviceName)
  197. {
  198. deviceName = device.DeviceName;
  199. bluetoothHelper.setDeviceName(deviceName);
  200. bluetoothHelper.Connect();
  201. Log("发现设备\n" + device.DeviceName);
  202. return;
  203. }
  204. }
  205. if (scanCount < 3)
  206. { //如果没扫描到,则重新扫描,达到延迟提示失败的效果
  207. scanCount++;
  208. scanLock = true;
  209. bluetoothHelper.ScanNearbyDevices();
  210. }
  211. else
  212. {
  213. canConnect = true;
  214. Log("没有发现设备");
  215. SetStatus(BluetoothStatusEnum.ConnectFail);
  216. }
  217. };
  218. bluetoothHelper.ScanNearbyDevices();
  219. Log("正在扫描设备");
  220. }
  221. catch (Exception e)
  222. {
  223. Debug.LogError(e.Message);
  224. Debug.LogError(e.StackTrace);
  225. scanLock = false;
  226. canConnect = true;
  227. SetStatus(BluetoothStatusEnum.ConnectFail);
  228. Log("请打开蓝牙");
  229. }
  230. }
  231. void ConnectBleByUDP()
  232. {
  233. try
  234. {
  235. BleUDP.ins.OnConnected = () =>
  236. {
  237. Log("连接成功\n" + deviceName);
  238. SetStatus(BluetoothStatusEnum.ConnectSuccess);
  239. BowCamera.isTouchMode = false;
  240. InitWhenConenct();
  241. };
  242. BleUDP.ins.OnConnectionFailed = () =>
  243. {
  244. Log("连接失败\n" + deviceName);
  245. OnDisconnect();
  246. };
  247. BleUDP.ins.OnCharacteristicChanged = (byte[] value) =>
  248. {
  249. if (!hasData) hasDataTime = JC.CS.Utility.GetTimestamp();
  250. hasData = true;
  251. byte[] bytes = value;
  252. // Log(String.Join(",", bytes));
  253. BluetoothClient.UploadData(0, bytes);
  254. if (AimHandler.ins)
  255. {
  256. AimHandler.ins.OnDataReceived(bytes);
  257. }
  258. };
  259. BleUDP.ins.OnScanEnded = () =>
  260. {
  261. scanLock = false;
  262. deviceName = targetDeviceName;
  263. BleUDP.ins.Connect();
  264. Log("发现设备\n" + deviceName);
  265. };
  266. BleUDP.ins.ScanNearbyDevices();
  267. }
  268. catch (Exception e)
  269. {
  270. Debug.LogError(e.Message);
  271. Debug.LogError(e.StackTrace);
  272. scanLock = false;
  273. canConnect = true;
  274. SetStatus(BluetoothStatusEnum.ConnectFail);
  275. }
  276. }
  277. #region 自动进入/退出休眠状态, 这里做程指令发送队列,为了控制连续发送指令的间隔,避免硬件收不到或处理不过来
  278. class CmdToSend
  279. {
  280. public string[] cmds;
  281. public Action onComplete;
  282. public Func<bool> canDo;
  283. public CmdToSend(string[] cmds, Action onComplete, Func<bool> canDo)
  284. {
  285. this.cmds = cmds;
  286. this.onComplete = onComplete;
  287. this.canDo = canDo;
  288. }
  289. }
  290. Queue<CmdToSend> cmdWaitingList = new Queue<CmdToSend>();
  291. bool isSendCmdLocked = false;
  292. bool canAutoDormancy = false;
  293. bool isStartUp = false;
  294. JC.CS.CountLocker needModularAwake = new JC.CS.CountLocker();
  295. void CheckAndStartUp()
  296. {
  297. if (needModularAwake.IsLocked())
  298. {
  299. StartUp();
  300. }
  301. else
  302. {
  303. Dormancy();
  304. }
  305. }
  306. void InitAutoDormancy()
  307. {
  308. // GlobalEventCenter.ins.onGameSceneLoad += () => {
  309. // needModularAwake.Lock();
  310. // CheckAndStartUp();
  311. // };
  312. // GlobalEventCenter.ins.onGameSceneDestroy += () => {
  313. // needModularAwake.Unlock();
  314. // CheckAndStartUp();
  315. // };
  316. // GlobalEventCenter.ins.onSimulateMouseAwakeChanged += (waked) => {
  317. // if (waked) needModularAwake.Lock();
  318. // else needModularAwake.Unlock();;
  319. // CheckAndStartUp();
  320. // };
  321. // GlobalEventCenter.ins.onDeviceCalibrateViewAwakeChanged += (waked) => {
  322. // if (waked) needModularAwake.Lock();
  323. // else needModularAwake.Unlock();;
  324. // CheckAndStartUp();
  325. // };
  326. //暂时关闭自动休眠,默认是需要模块保持激活
  327. needModularAwake.Lock();
  328. }
  329. void InitWhenConenct()
  330. {
  331. canAutoDormancy = true;
  332. List<string> cmds = new List<string>();
  333. cmds.Add("b"); //确保开启stm32
  334. cmds.Add("b"); //获取初始电量
  335. cmds.Add("1"); //开启发送逻辑
  336. Action onComplete = null;
  337. if (needModularAwake.IsLocked())
  338. {
  339. cmds.Add("w"); //红外灯开启
  340. cmds.Add("3"); //九轴开启
  341. onComplete = () =>
  342. {
  343. isStartUp = true;
  344. };
  345. }
  346. else
  347. {
  348. cmds.Add("s"); //红外灯关闭
  349. cmds.Add("S"); //Stm32关闭
  350. cmds.Add("4"); //九轴关闭
  351. onComplete = () =>
  352. {
  353. isStartUp = false;
  354. };
  355. }
  356. SendCDM(null, onComplete, cmds.ToArray());
  357. }
  358. void DestroyWhenDisconenct()
  359. {
  360. canAutoDormancy = false;
  361. sendCMD_CheckAndDoStop(null);
  362. }
  363. //启动
  364. void StartUp()
  365. {
  366. SendCDM(() =>
  367. {
  368. return !isStartUp;
  369. }, () =>
  370. {
  371. isStartUp = true;
  372. }, "b", "w", "3");
  373. }
  374. //休眠
  375. void Dormancy()
  376. {
  377. SendCDM(() =>
  378. {
  379. return isStartUp;
  380. }, () =>
  381. {
  382. isStartUp = false;
  383. }, "4", "s", "S");
  384. }
  385. void SendCDM(Func<bool> canDo, Action onComplete, params string[] cmds)
  386. {
  387. CmdToSend cmdToSend = new CmdToSend(cmds, onComplete, canDo);
  388. if (isSendCmdLocked)
  389. {
  390. cmdWaitingList.Enqueue(cmdToSend);
  391. return;
  392. }
  393. sendCMD_NotCheck(cmdToSend);
  394. }
  395. void sendCMD_NotCheck(CmdToSend cmdToSend)
  396. {
  397. if (cmdToSend.canDo != null && !cmdToSend.canDo.Invoke())
  398. {
  399. sendCMD_CheckNext();
  400. return;
  401. }
  402. isSendCmdLocked = true;
  403. Sequence sequence = DOTween.Sequence();
  404. sequence.PrependInterval(0.3f);
  405. foreach (var cmd in cmdToSend.cmds)
  406. {
  407. sequence.AppendCallback(() =>
  408. {
  409. bool stopped = sendCMD_CheckAndDoStop(sequence);
  410. if (!stopped) WriteData(cmd);
  411. });
  412. sequence.AppendInterval(0.5f);
  413. }
  414. sequence.AppendCallback(() =>
  415. {
  416. bool stopped = sendCMD_CheckAndDoStop(sequence);
  417. if (!stopped)
  418. {
  419. isSendCmdLocked = false;
  420. cmdToSend.onComplete?.Invoke();
  421. sendCMD_CheckNext();
  422. }
  423. });
  424. sequence.SetUpdate(true);
  425. }
  426. void sendCMD_CheckNext()
  427. {
  428. if (cmdWaitingList.Count <= 0) return;
  429. CmdToSend cmdToSend = cmdWaitingList.Dequeue();
  430. sendCMD_NotCheck(cmdToSend);
  431. }
  432. bool sendCMD_CheckAndDoStop(Sequence sequence)
  433. {
  434. if (canAutoDormancy) return false;
  435. isStartUp = false;
  436. isSendCmdLocked = false;
  437. cmdWaitingList.Clear();
  438. if (sequence != null) sequence.Kill();
  439. return true;
  440. }
  441. #endregion
  442. public void RequestBattery()
  443. {
  444. if (!isStartUp) return;
  445. if (isSendCmdLocked) return;
  446. WriteData("b");
  447. }
  448. public void ReplyInfraredShoot()
  449. {
  450. if (isSendCmdLocked) return;
  451. WriteData("I");
  452. }
  453. void CallDelay(float delayTime, TweenCallback callback)
  454. {
  455. Sequence sequence = DOTween.Sequence();
  456. sequence.PrependInterval(delayTime).AppendCallback(callback);
  457. sequence.SetUpdate(true);
  458. }
  459. public void WriteData(string data)
  460. {
  461. #if UNITY_ANDROID
  462. if (DebugDeviceCMD.ins) DebugDeviceCMD.ins.ShowCMD(data);
  463. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristicWrite.getName());
  464. ch.setService(bluetoothService.getName());
  465. bluetoothHelper.WriteCharacteristic(ch, data);
  466. #elif UNITY_STANDALONE_WIN
  467. BleUDP.ins.SendMsg(data);
  468. #endif
  469. }
  470. void Log(string text)
  471. {
  472. if (textUI)
  473. {
  474. textUI.text = text;
  475. }
  476. }
  477. }