BluetoothAim.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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. Log("请打开蓝牙");
  232. }
  233. }
  234. void ConnectBleByUDP()
  235. {
  236. try
  237. {
  238. BleUDP.ins.OnConnected = () =>
  239. {
  240. Log("连接成功\n" + deviceName);
  241. SetStatus(BluetoothStatusEnum.ConnectSuccess);
  242. BowCamera.isTouchMode = false;
  243. InitWhenConenct();
  244. };
  245. BleUDP.ins.OnConnectionFailed = () =>
  246. {
  247. Log("连接失败\n" + deviceName);
  248. OnDisconnect();
  249. };
  250. BleUDP.ins.OnCharacteristicChanged = (byte[] value) =>
  251. {
  252. if (!hasData) {
  253. hasDataTime = JC.CS.Utility.GetTimestamp();
  254. UploadMacAddress(value);
  255. }
  256. hasData = true;
  257. byte[] bytes = value;
  258. // Log(String.Join(",", bytes));
  259. BluetoothClient.UploadData(0, bytes);
  260. if (AimHandler.ins)
  261. {
  262. AimHandler.ins.OnDataReceived(bytes);
  263. }
  264. };
  265. BleUDP.ins.OnScanEnded = () =>
  266. {
  267. scanLock = false;
  268. deviceName = targetDeviceName;
  269. BleUDP.ins.Connect();
  270. Log("发现设备\n" + deviceName);
  271. };
  272. BleUDP.ins.ScanNearbyDevices();
  273. }
  274. catch (Exception e)
  275. {
  276. Debug.LogError(e.Message);
  277. Debug.LogError(e.StackTrace);
  278. scanLock = false;
  279. canConnect = true;
  280. SetStatus(BluetoothStatusEnum.ConnectFail);
  281. }
  282. }
  283. #region 自动进入/退出休眠状态, 这里做程指令发送队列,为了控制连续发送指令的间隔,避免硬件收不到或处理不过来
  284. class CmdToSend
  285. {
  286. public string[] cmds;
  287. public Action onComplete;
  288. public Func<bool> canDo;
  289. public CmdToSend(string[] cmds, Action onComplete, Func<bool> canDo)
  290. {
  291. this.cmds = cmds;
  292. this.onComplete = onComplete;
  293. this.canDo = canDo;
  294. }
  295. }
  296. Queue<CmdToSend> cmdWaitingList = new Queue<CmdToSend>();
  297. bool isSendCmdLocked = false;
  298. bool canAutoDormancy = false;
  299. bool isStartUp = false;
  300. JC.CS.CountLocker needModularAwake = new JC.CS.CountLocker();
  301. void CheckAndStartUp()
  302. {
  303. if (needModularAwake.IsLocked())
  304. {
  305. StartUp();
  306. }
  307. else
  308. {
  309. Dormancy();
  310. }
  311. }
  312. void InitAutoDormancy()
  313. {
  314. // GlobalEventCenter.ins.onGameSceneLoad += () => {
  315. // needModularAwake.Lock();
  316. // CheckAndStartUp();
  317. // };
  318. // GlobalEventCenter.ins.onGameSceneDestroy += () => {
  319. // needModularAwake.Unlock();
  320. // CheckAndStartUp();
  321. // };
  322. // GlobalEventCenter.ins.onSimulateMouseAwakeChanged += (waked) => {
  323. // if (waked) needModularAwake.Lock();
  324. // else needModularAwake.Unlock();;
  325. // CheckAndStartUp();
  326. // };
  327. // GlobalEventCenter.ins.onDeviceCalibrateViewAwakeChanged += (waked) => {
  328. // if (waked) needModularAwake.Lock();
  329. // else needModularAwake.Unlock();;
  330. // CheckAndStartUp();
  331. // };
  332. //暂时关闭自动休眠,默认是需要模块保持激活
  333. needModularAwake.Lock();
  334. }
  335. void InitWhenConenct()
  336. {
  337. canAutoDormancy = true;
  338. List<string> cmds = new List<string>();
  339. cmds.Add("M"); //获取Mac地址
  340. cmds.Add("b"); //确保开启stm32
  341. cmds.Add("b"); //获取初始电量
  342. cmds.Add("1"); //开启发送逻辑
  343. Action onComplete = null;
  344. if (needModularAwake.IsLocked())
  345. {
  346. cmds.Add("w"); //红外灯开启
  347. cmds.Add("3"); //九轴开启
  348. onComplete = () =>
  349. {
  350. isStartUp = true;
  351. };
  352. }
  353. else
  354. {
  355. cmds.Add("s"); //红外灯关闭
  356. cmds.Add("S"); //Stm32关闭
  357. cmds.Add("4"); //九轴关闭
  358. onComplete = () =>
  359. {
  360. isStartUp = false;
  361. };
  362. }
  363. SendCDM(null, onComplete, cmds.ToArray());
  364. }
  365. void DestroyWhenDisconenct()
  366. {
  367. canAutoDormancy = false;
  368. sendCMD_CheckAndDoStop(null);
  369. }
  370. //启动
  371. void StartUp()
  372. {
  373. SendCDM(() =>
  374. {
  375. return !isStartUp;
  376. }, () =>
  377. {
  378. isStartUp = true;
  379. }, "b", "w", "3");
  380. }
  381. //休眠
  382. void Dormancy()
  383. {
  384. SendCDM(() =>
  385. {
  386. return isStartUp;
  387. }, () =>
  388. {
  389. isStartUp = false;
  390. }, "4", "s", "S");
  391. }
  392. void SendCDM(Func<bool> canDo, Action onComplete, params string[] cmds)
  393. {
  394. CmdToSend cmdToSend = new CmdToSend(cmds, onComplete, canDo);
  395. if (isSendCmdLocked)
  396. {
  397. cmdWaitingList.Enqueue(cmdToSend);
  398. return;
  399. }
  400. sendCMD_NotCheck(cmdToSend);
  401. }
  402. void sendCMD_NotCheck(CmdToSend cmdToSend)
  403. {
  404. if (cmdToSend.canDo != null && !cmdToSend.canDo.Invoke())
  405. {
  406. sendCMD_CheckNext();
  407. return;
  408. }
  409. isSendCmdLocked = true;
  410. Sequence sequence = DOTween.Sequence();
  411. sequence.PrependInterval(0.3f);
  412. foreach (var cmd in cmdToSend.cmds)
  413. {
  414. sequence.AppendCallback(() =>
  415. {
  416. bool stopped = sendCMD_CheckAndDoStop(sequence);
  417. if (!stopped) WriteData(cmd);
  418. });
  419. sequence.AppendInterval(0.5f);
  420. }
  421. sequence.AppendCallback(() =>
  422. {
  423. bool stopped = sendCMD_CheckAndDoStop(sequence);
  424. if (!stopped)
  425. {
  426. isSendCmdLocked = false;
  427. cmdToSend.onComplete?.Invoke();
  428. sendCMD_CheckNext();
  429. }
  430. });
  431. sequence.SetUpdate(true);
  432. }
  433. void sendCMD_CheckNext()
  434. {
  435. if (cmdWaitingList.Count <= 0) return;
  436. CmdToSend cmdToSend = cmdWaitingList.Dequeue();
  437. sendCMD_NotCheck(cmdToSend);
  438. }
  439. bool sendCMD_CheckAndDoStop(Sequence sequence)
  440. {
  441. if (canAutoDormancy) return false;
  442. isStartUp = false;
  443. isSendCmdLocked = false;
  444. cmdWaitingList.Clear();
  445. if (sequence != null) sequence.Kill();
  446. return true;
  447. }
  448. #endregion
  449. public void RequestBattery()
  450. {
  451. if (!isStartUp) return;
  452. if (isSendCmdLocked) return;
  453. WriteData("b");
  454. }
  455. public void ReplyInfraredShoot()
  456. {
  457. if (isSendCmdLocked) return;
  458. WriteData("I");
  459. }
  460. void CallDelay(float delayTime, TweenCallback callback)
  461. {
  462. Sequence sequence = DOTween.Sequence();
  463. sequence.PrependInterval(delayTime).AppendCallback(callback);
  464. sequence.SetUpdate(true);
  465. }
  466. public void WriteData(string data)
  467. {
  468. #if UNITY_ANDROID
  469. if (DebugDeviceCMD.ins) DebugDeviceCMD.ins.ShowCMD(data);
  470. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristicWrite.getName());
  471. ch.setService(bluetoothService.getName());
  472. bluetoothHelper.WriteCharacteristic(ch, data);
  473. #elif UNITY_STANDALONE_WIN
  474. BleUDP.ins.SendMsg(data);
  475. #endif
  476. }
  477. void Log(string text)
  478. {
  479. if (textUI)
  480. {
  481. textUI.text = text;
  482. }
  483. }
  484. void UploadMacAddress(byte[] bytes) {
  485. if (hasData) return;
  486. string str = System.Text.Encoding.ASCII.GetString (bytes);
  487. if (str == null) return;
  488. if (str.Contains(":")) {
  489. if (!str.Equals(LoginMgr.myUserInfo.mac)) {
  490. LoginMgr.myUserInfo.mac = str;
  491. }
  492. UserPlayer.ins.call("userComp.saveMac", str);
  493. }
  494. }
  495. }