BluetoothAim.cs 15 KB

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