BluetoothAim.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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. void InitWhenConenct() {
  217. canAutoDormancy = true;
  218. List<string> cmds = new List<string>();
  219. cmds.Add("b"); //确保开启stm32
  220. cmds.Add("b"); //获取初始电量
  221. cmds.Add("1"); //开启发送逻辑
  222. Action onComplete = null;
  223. if (needModularAwake.IsLocked()) {
  224. cmds.Add("w"); //红外灯开启
  225. cmds.Add("3"); //九轴开启
  226. onComplete = () => {
  227. isStartUp = true;
  228. };
  229. } else {
  230. cmds.Add("s"); //红外灯关闭
  231. cmds.Add("S"); //Stm32关闭
  232. cmds.Add("4"); //九轴关闭
  233. onComplete = () => {
  234. isStartUp = false;
  235. };
  236. }
  237. SendCDM(null, onComplete, cmds.ToArray());
  238. }
  239. void DestroyWhenDisconenct() {
  240. canAutoDormancy = false;
  241. sendCMD_CheckAndDoStop(null);
  242. }
  243. //启动
  244. void StartUp() {
  245. SendCDM(() => {
  246. return !isStartUp;
  247. }, () => {
  248. isStartUp = true;
  249. }, "b", "w", "3");
  250. }
  251. //休眠
  252. void Dormancy() {
  253. SendCDM(() => {
  254. return isStartUp;
  255. }, () => {
  256. isStartUp = false;
  257. }, "4", "s", "S");
  258. }
  259. void SendCDM(Func<bool> canDo, Action onComplete, params string[] cmds) {
  260. CmdToSend cmdToSend = new CmdToSend(cmds, onComplete, canDo);
  261. if (isSendCmdLocked) {
  262. cmdWaitingList.Enqueue(cmdToSend);
  263. return;
  264. }
  265. sendCMD_NotCheck(cmdToSend);
  266. }
  267. void sendCMD_NotCheck(CmdToSend cmdToSend) {
  268. if (cmdToSend.canDo != null && !cmdToSend.canDo.Invoke()) {
  269. sendCMD_CheckNext();
  270. return;
  271. }
  272. isSendCmdLocked = true;
  273. Sequence sequence = DOTween.Sequence();
  274. sequence.PrependInterval(0.3f);
  275. foreach (var cmd in cmdToSend.cmds) {
  276. sequence.AppendCallback(() => {
  277. bool stopped = sendCMD_CheckAndDoStop(sequence);
  278. if (!stopped) WriteData(cmd);
  279. });
  280. sequence.AppendInterval(0.5f);
  281. }
  282. sequence.AppendCallback(() => {
  283. bool stopped = sendCMD_CheckAndDoStop(sequence);
  284. if (!stopped) {
  285. isSendCmdLocked = false;
  286. cmdToSend.onComplete?.Invoke();
  287. sendCMD_CheckNext();
  288. }
  289. });
  290. sequence.SetUpdate(true);
  291. }
  292. void sendCMD_CheckNext() {
  293. if (cmdWaitingList.Count <= 0) return;
  294. CmdToSend cmdToSend = cmdWaitingList.Dequeue();
  295. sendCMD_NotCheck(cmdToSend);
  296. }
  297. bool sendCMD_CheckAndDoStop(Sequence sequence) {
  298. if (canAutoDormancy) return false;
  299. isStartUp = false;
  300. isSendCmdLocked = false;
  301. cmdWaitingList.Clear();
  302. if (sequence != null) sequence.Kill();
  303. return true;
  304. }
  305. #endregion
  306. void OpenInfrared()
  307. {
  308. WriteData("1");
  309. Log("红外线准备完成\n" + deviceName);
  310. }
  311. void OpenReceiveData()
  312. {
  313. WriteData("3");
  314. Log("瞄准模块准备完成\n" + deviceName);
  315. }
  316. public void RequestBattery() {
  317. if (!isStartUp) return;
  318. if (isSendCmdLocked) return;
  319. WriteData("b");
  320. }
  321. public void ReplyInfraredShoot() {
  322. if (isSendCmdLocked) return;
  323. WriteData("I");
  324. }
  325. void CallDelay(float delayTime, TweenCallback callback)
  326. {
  327. Sequence sequence = DOTween.Sequence();
  328. sequence.PrependInterval(delayTime).AppendCallback(callback);
  329. sequence.SetUpdate(true);
  330. }
  331. public void WriteData(string data)
  332. {
  333. if (DebugDeviceCMD.ins) DebugDeviceCMD.ins.ShowCMD(data);
  334. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristicWrite.getName());
  335. ch.setService(bluetoothService.getName());
  336. bluetoothHelper.WriteCharacteristic(ch, data);
  337. }
  338. void Log(string text)
  339. {
  340. if (textUI)
  341. {
  342. textUI.text = text;
  343. }
  344. }
  345. }
  346. // public class BluetoothAim : MonoBehaviour
  347. // {
  348. // BluetoothHelper bluetoothHelper;
  349. // BluetoothHelperCharacteristic characteristicWrite;
  350. // BluetoothHelperService bluetoothService;
  351. // string targetDeviceName = "Bbow_20210501";
  352. // string deviceName = "";
  353. // bool canConnect = true;
  354. // [SerializeField] Text textUI;
  355. // public BluetoothStatusEnum status = BluetoothStatusEnum.Connect;
  356. // public bool hasData = false;
  357. // public long hasDataTime;
  358. // public static bool scanLock = false; //防止同时扫描冲突
  359. // public static BluetoothAim ins;
  360. // void Start() {
  361. // ins = this;
  362. // }
  363. // void OnDestroy()
  364. // {
  365. // if (bluetoothHelper != null)
  366. // {
  367. // bluetoothHelper.Disconnect();
  368. // }
  369. // }
  370. // private bool userDoConnect = false;
  371. // private bool doConnect = false;
  372. // public void DoConnect() {
  373. // if (status == BluetoothStatusEnum.Connect) {
  374. // userDoConnect = true;
  375. // doConnect = true;
  376. // SetStatus(BluetoothStatusEnum.Connecting);
  377. // } else if (status == BluetoothStatusEnum.ConnectSuccess) {
  378. // userDoConnect = false;
  379. // doConnect = false;
  380. // OnDisconnect();
  381. // bluetoothHelper.Disconnect();
  382. // }
  383. // }
  384. // void OnDisconnect() {
  385. // hasData = false;
  386. // canConnect = true;
  387. // SetStatus(BluetoothStatusEnum.ConnectFail);
  388. // BowCamera.isTouchMode = true;
  389. // }
  390. // void Update()
  391. // {
  392. // if (userDoConnect && status == BluetoothStatusEnum.Connect) {
  393. // DoConnect();
  394. // }
  395. // if (doConnect) Connect();
  396. // }
  397. // void SetStatus(BluetoothStatusEnum statusValue)
  398. // {
  399. // status = statusValue;
  400. // if (status == BluetoothStatusEnum.ConnectFail) {
  401. // Sequence sequence = DOTween.Sequence();
  402. // sequence.AppendInterval(2f);
  403. // sequence.AppendCallback(delegate() {
  404. // if (status == BluetoothStatusEnum.ConnectFail) {
  405. // status = BluetoothStatusEnum.Connect;
  406. // }
  407. // });
  408. // sequence.SetUpdate(true);
  409. // DeviceReconnectView.Show();
  410. // }
  411. // }
  412. // void Connect()
  413. // {
  414. // if (BluetoothShoot.scanLock)
  415. // {
  416. // return;
  417. // }
  418. // if (!canConnect)
  419. // {
  420. // return;
  421. // }
  422. // doConnect = false;
  423. // scanLock = true;
  424. // canConnect = false;
  425. // SetStatus(BluetoothStatusEnum.Connecting);
  426. // try
  427. // {
  428. // BluetoothHelper.BLE = true;
  429. // bluetoothHelper = BluetoothHelper.GetNewInstance();
  430. // bluetoothHelper.OnConnected += (BluetoothHelper helper) =>
  431. // {
  432. // Log("连接成功\n" + helper.getDeviceName());
  433. // SetStatus(BluetoothStatusEnum.ConnectSuccess);
  434. // BowCamera.isTouchMode = false;
  435. // foreach (BluetoothHelperService service in helper.getGattServices())
  436. // {
  437. // if (service.getName().ToLower().StartsWith("0000fff0"))
  438. // {
  439. // bluetoothService = service;
  440. // foreach (BluetoothHelperCharacteristic characteristic in service.getCharacteristics())
  441. // {
  442. // if (characteristic.getName().ToLower().StartsWith("0000fff2"))
  443. // {
  444. // characteristicWrite = characteristic;
  445. // }
  446. // else if (characteristic.getName().ToLower().StartsWith("0000fff1"))
  447. // {
  448. // BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristic.getName());
  449. // ch.setService(bluetoothService.getName());
  450. // bluetoothHelper.Subscribe(ch);
  451. // }
  452. // }
  453. // }
  454. // }
  455. // CallDelay(1, OpenInfrared);
  456. // CallDelay(2, OpenReceiveData);
  457. // CallDelay(3, RequestBattery);
  458. // };
  459. // bluetoothHelper.OnConnectionFailed += (BluetoothHelper helper) =>
  460. // {
  461. // Log("连接失败\n" + helper.getDeviceName());
  462. // OnDisconnect();
  463. // };
  464. // bluetoothHelper.OnCharacteristicChanged += (helper, value, characteristic) =>
  465. // {
  466. // if (!hasData) hasDataTime = JC.CS.Utility.GetTimestamp();
  467. // hasData = true;
  468. // byte[] bytes = value;
  469. // // Log(String.Join(",", bytes));
  470. // BluetoothClient.UploadData(0, bytes);
  471. // if (AimHandler.ins)
  472. // {
  473. // AimHandler.ins.OnDataReceived(bytes);
  474. // }
  475. // };
  476. // bluetoothHelper.OnScanEnded += (BluetoothHelper helper, LinkedList<BluetoothDevice> nearbyDevices) =>
  477. // {
  478. // scanLock = false;
  479. // foreach (BluetoothDevice device in nearbyDevices)
  480. // {
  481. // if (device.DeviceName == targetDeviceName)
  482. // {
  483. // deviceName = device.DeviceName;
  484. // bluetoothHelper.setDeviceName(deviceName);
  485. // bluetoothHelper.Connect();
  486. // Log("发现设备\n" + device.DeviceName);
  487. // return;
  488. // }
  489. // }
  490. // canConnect = true;
  491. // Log("没有发现设备");
  492. // SetStatus(BluetoothStatusEnum.ConnectFail);
  493. // };
  494. // bluetoothHelper.ScanNearbyDevices();
  495. // Log("正在扫描设备");
  496. // }
  497. // catch (Exception e)
  498. // {
  499. // Debug.Log(e.Message);
  500. // canConnect = true;
  501. // Log("请打开蓝牙");
  502. // }
  503. // }
  504. // void OpenInfrared()
  505. // {
  506. // WriteData("1");
  507. // Log("红外线准备完成\n" + deviceName);
  508. // }
  509. // void OpenReceiveData()
  510. // {
  511. // WriteData("3");
  512. // Log("瞄准模块准备完成\n" + deviceName);
  513. // }
  514. // public void RequestBattery() {
  515. // WriteData("b");
  516. // }
  517. // public void ReplyInfraredShoot() {
  518. // WriteData("I");
  519. // }
  520. // void CallDelay(float delayTime, TweenCallback callback)
  521. // {
  522. // Sequence sequence = DOTween.Sequence();
  523. // sequence.PrependInterval(delayTime).AppendCallback(callback);
  524. // sequence.SetUpdate(true);
  525. // }
  526. // public void WriteData(string data)
  527. // {
  528. // BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristicWrite.getName());
  529. // ch.setService(bluetoothService.getName());
  530. // bluetoothHelper.WriteCharacteristic(ch, data);
  531. // }
  532. // void Log(string text)
  533. // {
  534. // if (textUI)
  535. // {
  536. // textUI.text = text;
  537. // }
  538. // }
  539. // }