ConnetDevicesSingle.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. using ArduinoBluetoothAPI;
  4. using System;
  5. using System.Text;
  6. using UnityEngine.UI;
  7. using DG.Tweening;
  8. using System.Collections;
  9. namespace InfraredManager
  10. {
  11. public class ConnetDevicesSingle : MonoBehaviour
  12. {
  13. #region
  14. #endregion
  15. #region 连接弓箭蓝牙部分
  16. private BluetoothHelper bluetoothHelperBow;
  17. public BluetoothHelper mBluetoothHelperBow
  18. {
  19. get
  20. {
  21. return bluetoothHelperBow;
  22. }
  23. }
  24. private BluetoothHelperCharacteristic characteristicWriteBow;
  25. private BluetoothHelperService bluetoothServiceBow;
  26. private string bowTargetDeviceName = "Bbow_20210501";
  27. private string bowDeviceName = "";
  28. string bowDeviceService = "0000fff0";
  29. string bowDeviceCharacteristicWrite = "0000fff2";
  30. string bowDeviceCharacteristicNotify = "0000fff1";
  31. private bool isBowScanning;
  32. public bool mIsBowScanning
  33. {
  34. get
  35. {
  36. return isBowScanning;
  37. }
  38. }
  39. private bool isBowConnecting;
  40. public bool mIsBowConnecting
  41. {
  42. get
  43. {
  44. return isBowConnecting;
  45. }
  46. }
  47. private string data;
  48. private int _receivedDataCount = 0;
  49. public string macAddress = null;
  50. private string inputStr = "";
  51. #endregion
  52. private LinkedList<BluetoothDevice> devices;
  53. #region log输出
  54. public Action<string> OnLogAction;
  55. void logOutBow(string text)
  56. {
  57. Debug.Log("logOutBow:" + text);
  58. OnLogAction?.Invoke(text);
  59. }
  60. #endregion
  61. public static ConnetDevicesSingle ins;
  62. //默认关闭准心
  63. public bool bCrosshair = false;
  64. #region 红外Demo相关监听操作
  65. public Action<Vector3> posAction;
  66. public Action<int> infraredShootAction;
  67. public Action<bool> crosshairAction;
  68. #endregion
  69. void Awake()
  70. {
  71. //初始化
  72. ins = this;
  73. Debug.Log("ConnetDevicesSingle!");
  74. OnUpdateState();
  75. }
  76. //获取一次初始值
  77. public void OnInitConfig()
  78. {
  79. }
  80. public void OnUpdateState()
  81. {
  82. }
  83. public void ButtonShoot()
  84. {
  85. posAction?.Invoke(new Vector3(1 * Screen.width, 1 * Screen.height, 0));
  86. //调用游戏中的射箭接口
  87. if (ArmBow.ins)
  88. {
  89. ArmBow.ins.ADS_fire(true);
  90. }
  91. else
  92. {
  93. OnGameShoot?.Invoke(10);
  94. }
  95. }
  96. public void onShowCrosshair()
  97. {
  98. //显示游戏光标
  99. PlayerPrefs.SetInt("CrossHairImageActive", 1);
  100. bCrosshair = true;
  101. crosshairAction?.Invoke(true);
  102. }
  103. public void onHideCrosshair()
  104. {
  105. //隐藏游戏光标
  106. PlayerPrefs.SetInt("CrossHairImageActive", 0);
  107. bCrosshair = false;
  108. crosshairAction?.Invoke(false);
  109. }
  110. // Start is called before the first frame update
  111. void Start()
  112. {
  113. }
  114. public void ConnectBLE()
  115. {
  116. logOutBow("连接蓝牙 BluetoothHelperAndroid");
  117. if (BluetoothHelperAndroid.IsBluetoothEnabled() == false)
  118. {
  119. Debug.Log("蓝牙未打开!");
  120. logOutBow("蓝牙未打开!");
  121. return;
  122. }
  123. if (BluetoothHelperAndroid.RequestBluetoothPermissions(ConnectBLE, (permission) => {
  124. if (permission.Contains("LOCATION"))
  125. {
  126. logOutBow("LOCATION 权限未开!");
  127. }
  128. else if (permission.Contains("BLUETOOTH"))
  129. {
  130. logOutBow("蓝牙权限未开!");
  131. }
  132. })) return;
  133. data = "";
  134. try
  135. {
  136. BluetoothHelper.BLE = true;
  137. bluetoothHelperBow = BluetoothHelper.GetNewInstance();
  138. bluetoothHelperBow.OnConnected += OnConnected;
  139. bluetoothHelperBow.OnConnectionFailed += OnConnectionFailed;
  140. bluetoothHelperBow.OnScanEnded += OnScanEnded2;
  141. bluetoothHelperBow.OnCharacteristicChanged += (helper, value, characteristic) =>
  142. {
  143. //if (helper != bluetoothHelperBow) return;
  144. byte[] bytes = value;
  145. //九轴数据反馈
  146. //Debug.Log("Hex:"+ ToHexStrFromByte(bytes) +" ,长度:"+ bytes.Length);
  147. if (inputStr == "M") ParseMacAddress(value);
  148. if (bytes.Length != 27 && bytes.Length != 39)
  149. {
  150. if (bytes.Length == 2)
  151. {
  152. if (bytes[0] == 0x66 && bytes[1] == 0x31)
  153. {
  154. //短按功能键
  155. logOutBow("短按功能键");
  156. }
  157. else if (bytes[0] == 0x66 && bytes[1] == 0x32)
  158. {
  159. //长按功能键
  160. logOutBow("长按功能键");
  161. }
  162. else if (bytes[1] == 10)
  163. {
  164. //电量
  165. logOutBow("电量:"+ bytes[0]);
  166. }
  167. }
  168. else if (bytes[0] == 0x5b)
  169. {
  170. // Debug.Log("射箭:" + bytes.ToString());
  171. //logOutBow("射箭");
  172. //红外线检测到射箭
  173. OnInfraredDataReceived(bytes);
  174. }
  175. }
  176. if (inputStr != "") {
  177. Debug.Log("清除指令:"+ inputStr);
  178. inputStr = "";
  179. }
  180. };
  181. }
  182. catch (Exception e)
  183. {
  184. Debug.LogError(e);
  185. }
  186. StartCoroutine(delayStartBle());
  187. }
  188. //Bow扫描结束
  189. void OnScanEnded2(BluetoothHelper helper, LinkedList<BluetoothDevice> nearbyDevices)
  190. {
  191. Debug.Log("2 ended " + nearbyDevices.Count);
  192. logOutBow("2 ended " + nearbyDevices.Count);
  193. if (nearbyDevices.Count == 0)
  194. {
  195. isBowScanning = helper.ScanNearbyDevices();
  196. return;
  197. }
  198. isBowScanning = false;
  199. foreach (BluetoothDevice device in nearbyDevices)
  200. {
  201. Debug.Log(device.DeviceName);
  202. if (device.DeviceName == bowTargetDeviceName)
  203. {
  204. logOutBow("匹配设备 " + device.DeviceName);
  205. bowDeviceName = bowTargetDeviceName;
  206. helper.setDeviceName(bowDeviceName);
  207. helper.Connect();
  208. isBowConnecting = true;
  209. }
  210. }
  211. }
  212. void OnConnected(BluetoothHelper helper)
  213. {
  214. if (helper.getId() == bluetoothHelperBow.getId())
  215. {
  216. Debug.Log("2 连接成功:" + helper.getDeviceName());
  217. logOutBow("弓箭 连接成功:" + helper.getDeviceName());
  218. isBowConnecting = false;
  219. foreach (BluetoothHelperService service in helper.getGattServices())
  220. {
  221. if (service.getName().ToLower().StartsWith(bowDeviceService))
  222. {
  223. bluetoothServiceBow = service;
  224. foreach (BluetoothHelperCharacteristic characteristic in service.getCharacteristics())
  225. {
  226. if (characteristic.getName().ToLower().StartsWith(bowDeviceCharacteristicWrite))
  227. {
  228. characteristicWriteBow = characteristic;
  229. }
  230. else if (characteristic.getName().ToLower().StartsWith(bowDeviceCharacteristicNotify))
  231. {
  232. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristic.getName());
  233. ch.setService(bluetoothServiceBow.getName());
  234. bluetoothHelperBow.Subscribe(ch);
  235. }
  236. }
  237. }
  238. }
  239. StartCoroutine(InitWhenConnected());
  240. }
  241. }
  242. void OnConnectionFailed(BluetoothHelper helper)
  243. {
  244. Debug.Log("Connection lost");
  245. if (helper.getId() == bluetoothHelperBow.getId())
  246. {
  247. isBowConnecting = false;
  248. _receivedDataCount = 0;
  249. macAddress = null;
  250. moduleInited = false;
  251. logOutBow("弓箭断开连接");
  252. }
  253. }
  254. IEnumerator delayStartBle() {
  255. yield return new WaitForSeconds(1.0f);
  256. OnBowScanNearbyDevices();
  257. }
  258. //Connect bow ble
  259. public void OnBowScanNearbyDevices()
  260. {
  261. if (bluetoothHelperBow == null)
  262. {
  263. return;
  264. }
  265. if (!bluetoothHelperBow.isConnected() && !isBowScanning && !isBowConnecting)
  266. {
  267. //未连接,未扫描,不是连接中
  268. if (BluetoothHelperAndroid.IsBluetoothEnabled() == false)
  269. {
  270. Debug.Log("exception1");
  271. logOutBow("蓝牙未打开");
  272. return;
  273. }
  274. if (BluetoothHelperAndroid.RequestBluetoothPermissions(() =>
  275. {
  276. //开始扫描。调用最后一个bluetoothHelperBow扫描即可
  277. isBowScanning = bluetoothHelperBow.ScanNearbyDevices();
  278. logOutBow("开始扫描连接!");
  279. }, (permission) =>
  280. {
  281. if (permission.Contains("LOCATION"))
  282. {
  283. Debug.LogError("Exception:LOCATION");
  284. logOutBow("Exception:LOCATION");
  285. }
  286. else if (permission.Contains("BLUETOOTH"))
  287. {
  288. Debug.LogError("Exception: BLUETOOTH");
  289. logOutBow("Exception:BLUETOOTH");
  290. }
  291. })) return;
  292. isBowScanning = bluetoothHelperBow.ScanNearbyDevices();
  293. logOutBow("开始扫描连接!");
  294. }
  295. else if (!bluetoothHelperBow.isConnected() && isBowScanning)
  296. {
  297. //扫描中
  298. logOutBow("扫描中...");
  299. }
  300. else if (bluetoothHelperBow.isConnected())
  301. {
  302. logOutBow("断开Bow连接");
  303. //已连接,断开连接
  304. bluetoothHelperBow.Disconnect();
  305. }
  306. }
  307. private void Update()
  308. {
  309. LoopHandleCommands();
  310. }
  311. void OnDestroy()
  312. {
  313. if (bluetoothHelperBow != null)
  314. {
  315. bluetoothHelperBow.Disconnect();
  316. OnDisconnect();
  317. }
  318. }
  319. /// <summary>
  320. /// 字节数组转16进制字符串:空格分隔
  321. /// </summary>
  322. /// <param name="byteDatas"></param>
  323. /// <returns></returns>
  324. public string ToHexStrFromByte(byte[] byteDatas)
  325. {
  326. StringBuilder builder = new StringBuilder();
  327. for (int i = 0; i < byteDatas.Length; i++)
  328. {
  329. builder.Append(string.Format("{0:X2} ", byteDatas[i]));
  330. }
  331. return builder.ToString().Trim();
  332. }
  333. /// <summary>
  334. /// 字符串转16进制
  335. /// </summary>
  336. /// <param name="input">要转格式的字符串</param>
  337. public byte[] Convert16(string strText)
  338. {
  339. strText = strText.Replace(" ", "");
  340. strText = strText.Replace(" ", "");
  341. Debug.Log(strText);
  342. byte[] bText = new byte[strText.Length / 2];
  343. for (int i = 0; i < strText.Length / 2; i++)
  344. {
  345. bText[i] = Convert.ToByte(Convert.ToInt32(strText.Substring(i * 2, 2), 16));
  346. }
  347. return bText;
  348. }
  349. string getBytesToIndex(byte[] bytes, int index)
  350. {
  351. StringBuilder builderCrosshair = new StringBuilder();
  352. builderCrosshair.Append(string.Format("{0:X2}", bytes[index]));
  353. return builderCrosshair.ToString().Trim();
  354. }
  355. float onVectorValue(byte[] bytes, int startIndex)
  356. {
  357. //整数部分
  358. string intPartHex = string.Format("{0:X2}", bytes[startIndex]).ToString().Trim(); ;
  359. int intPartNumber = Convert.ToInt32(intPartHex, 16);
  360. StringBuilder builder = new StringBuilder();
  361. for (int i = 0; i < 2; i++)
  362. {
  363. builder.Append(string.Format("{0:X2}", bytes[i + startIndex + 1]));
  364. }
  365. string dataHex = builder.ToString().Trim();
  366. int decimalPartNumber = Convert.ToInt32(dataHex, 16);
  367. return intPartNumber + (float)decimalPartNumber / 32768;
  368. }
  369. #region 自动进入/退出休眠状态, 这里做程指令发送队列,为了控制连续发送指令的间隔,避免硬件收不到或处理不过来
  370. public bool moduleInited;
  371. private string _connectedHandlerID = "";
  372. IEnumerator InitWhenConnected()
  373. {
  374. string myConnectedHandlerID = Guid.NewGuid().ToString();
  375. _connectedHandlerID = myConnectedHandlerID;
  376. yield return new WaitForSecondsRealtime(2.2f);
  377. Queue<string> cmds = new Queue<string>(new string[] { "M", "b", "b", "1"});
  378. while (cmds.Count > 0)
  379. {
  380. if ( myConnectedHandlerID != _connectedHandlerID) yield break;
  381. string cmd = cmds.Dequeue();
  382. onWriteDataToBow(cmd);
  383. yield return new WaitForSecondsRealtime(0.3f);
  384. }
  385. if ( myConnectedHandlerID != _connectedHandlerID) yield break;
  386. //StartCoroutine(LoopRequestBattery(myConnectedHandlerID));
  387. moduleInited = true;
  388. //smartBowHelper.InvokeOnBluetoothModuleInited();
  389. StartCoroutine(RequestShoot(myConnectedHandlerID));
  390. }
  391. IEnumerator RequestShoot(string myConnectedHandlerID)
  392. {
  393. yield return new WaitForSeconds(1.0f);
  394. if (myConnectedHandlerID == _connectedHandlerID) {
  395. AddCommandToQueue("w");
  396. StartCoroutine(RequestAxis(myConnectedHandlerID));
  397. }
  398. }
  399. IEnumerator RequestAxis(string myConnectedHandlerID)
  400. {
  401. yield return new WaitForSeconds(1.0f);
  402. if (myConnectedHandlerID == _connectedHandlerID)
  403. {
  404. AddCommandToQueue("3");
  405. }
  406. }
  407. private List<string> _commands = new List<string>();
  408. void LoopHandleCommands()
  409. {
  410. if (bluetoothHelperBow == null) return;
  411. if (!bluetoothHelperBow.isConnected() || !moduleInited)
  412. {
  413. if (_commands.Count > 0) _commands.Clear();
  414. return;
  415. }
  416. if (Time.realtimeSinceStartup - _lastWriteDataTime < 0.2f) return;
  417. if (_commands.Count == 0) return;
  418. string cmd = _commands[0];
  419. _commands.RemoveAt(0);
  420. onWriteDataToBow(cmd);
  421. }
  422. bool AddCommandToQueue(string cmd)
  423. {
  424. if (bluetoothHelperBow == null) return false;
  425. if (!bluetoothHelperBow.isConnected() || !moduleInited) return false;
  426. //如果待插入的指令跟队尾的指令一样,就不要插入了,因为冗余的指令无意义
  427. if (_commands.Count > 0 && _commands[_commands.Count - 1].Equals(cmd)) return true;
  428. _commands.Add(cmd);
  429. return true;
  430. }
  431. public void RequestMac()
  432. {
  433. macAddress = null;
  434. AddCommandToQueue("M");
  435. }
  436. public void RequestBattery1()
  437. {
  438. AddCommandToQueue("b");
  439. }
  440. public void Request1()
  441. {
  442. AddCommandToQueue("1");
  443. }
  444. public void RequestOpen9Axis()
  445. {
  446. AddCommandToQueue("3");
  447. }
  448. public void RequestClose9Axis()
  449. {
  450. AddCommandToQueue("4");
  451. }
  452. public void RequestOpenInfrared()
  453. {
  454. AddCommandToQueue("w");
  455. }
  456. public void RequestCloseInfrared()
  457. {
  458. AddCommandToQueue("s");
  459. }
  460. #endregion
  461. #region 弓箭部分代码操作
  462. public Action<float> OnGameShoot;
  463. //[NonSerialized] public byte byteTime1;
  464. //[NonSerialized] public byte byteTime2;
  465. /**通过红外线数据进行射击 */
  466. /// <summary>
  467. /// 游戏里箭的速度
  468. /// </summary>
  469. public float gameArrowSpeed = 0;
  470. /// <summary>
  471. /// 上一次的射击数据ID
  472. /// </summary>
  473. private int _lastShootID = -1;
  474. /// <summary>
  475. /// 当收到红外数据时
  476. /// </summary>
  477. /// <param name="bytes"></param>
  478. public void OnInfraredDataReceived(byte[] bytes)
  479. {
  480. //序号
  481. int id = bytes[1];
  482. if (id == _lastShootID) return; //因为硬件为了避免丢包,会连续发几条相同射击通知过来
  483. _lastShootID = id;
  484. //时区1耗时
  485. float time1 = bytes[2] * 0.1f;
  486. //时区2耗时
  487. float time2 = bytes[3] * 0.1f;
  488. //时区耗时总和
  489. float totalTime = time1 + time2;
  490. //校验和
  491. int sumCheck = (bytes[0] + bytes[1] + bytes[2] + bytes[3]) & 0xff;
  492. //校验和比较结果
  493. bool sumCheckRes = sumCheck == bytes[4];
  494. //实体箭速度
  495. float solidArrowSpeed = 0.05f / (totalTime / 1000f);
  496. //通过动能定理求箭的速度(实体箭质量*实体箭速度^2=游戏中箭的质量*游戏中箭的速度^2)
  497. gameArrowSpeed = Mathf.Sqrt(solidArrowSpeed * solidArrowSpeed * CommonConfig.arrowWeight / UserSettings.ins.actualArrowWeight);
  498. //打印
  499. string logInfo = $"序号{id},时区1:{time1}毫秒,时区2:{time2}毫秒,校验:{sumCheckRes},实体箭速度:{solidArrowSpeed}m/s,游戏箭速度:{gameArrowSpeed}m/s";
  500. logOutBow( logInfo);
  501. //收到正确的射箭数据,就回复硬件,否则n毫秒后硬件会认为丢包而进行重传
  502. if (sumCheckRes) ReplyInfraredShoot();
  503. //通知九轴算法,因为射箭抖动会使算法计算的姿态角产生误差
  504. //打开准心的时候,直接调用射击接口
  505. if (ArmBow.ins)
  506. {
  507. ArmBow.ins.ADS_fire(true, gameArrowSpeed);
  508. }
  509. else if (DuckHunter.SmartBowController.Instance)
  510. {
  511. DuckHunter.SmartBowController.Instance.OnShooting(gameArrowSpeed);
  512. }
  513. //smartBowHelper.InvokeOnShooting(gameArrowSpeed);
  514. }
  515. //断开弓箭连接
  516. void OnDisconnect()
  517. {
  518. //DestroyWhenDisconenct();
  519. }
  520. public void RequestBattery()
  521. {
  522. onWriteDataToBow("b");
  523. }
  524. //回复弓箭红外
  525. public void ReplyInfraredShoot()
  526. {
  527. onWriteDataToBow("I");
  528. }
  529. private float _lastWriteDataTime;
  530. public void onWriteDataToBow(string data)
  531. {
  532. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristicWriteBow.getName());
  533. ch.setService(bluetoothServiceBow.getName());
  534. bluetoothHelperBow.WriteCharacteristic(ch, data);
  535. _lastWriteDataTime = Time.realtimeSinceStartup;
  536. //logOutBow("onWriteDataToBow:"+data);
  537. inputStr = data;
  538. }
  539. void ParseMacAddress(byte[] bytes)
  540. {
  541. //logOutBow("ParseMacAddress!");
  542. string mac = System.Text.Encoding.ASCII.GetString(bytes);
  543. if (mac != null) mac = mac.Trim();
  544. if (CheckIsMacValid(mac))
  545. {
  546. macAddress = mac;
  547. logOutBow("MacAddress解析成功:"+ macAddress);
  548. //获取MacAddress对应的校准记录
  549. }
  550. else logOutBow("MacAddress解析失败");
  551. }
  552. bool CheckIsMacValid(string mac)
  553. {
  554. if (mac == null) return false;
  555. if (!mac.StartsWith("{")) return false;
  556. if (!mac.EndsWith("}")) return false;
  557. if (!mac.Contains(":")) return false;
  558. char[] validChars = { '{', '}', ':', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
  559. foreach (var c in mac.ToCharArray())
  560. {
  561. if (Array.IndexOf(validChars, c) == -1) return false;
  562. }
  563. if (mac.Length != 19) return false;
  564. string macNoneFrame = mac.Substring(1, mac.Length - 2);
  565. string[] macNoneFrameSplits = macNoneFrame.Split(':');
  566. if (macNoneFrameSplits.Length != 6) return false;
  567. foreach (var item in macNoneFrameSplits)
  568. {
  569. if (item.Length != 2) return false;
  570. foreach (var c in item.ToCharArray())
  571. if (Array.IndexOf(validChars, c) < 3) return false;
  572. }
  573. return true;
  574. }
  575. #endregion
  576. }
  577. }