BluetoothAim.cs 16 KB

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