BluetoothAim.cs 18 KB

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