BluetoothAim.cs 18 KB

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