BluetoothAim.cs 16 KB

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