BluetoothAim.cs 20 KB

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