ConnetDevicesSingle.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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. namespace InfraredManager
  9. {
  10. public class ConnetDevicesSingle : MonoBehaviour
  11. {
  12. #region 连接弓箭蓝牙部分
  13. private BluetoothHelper bluetoothHelperBow;
  14. public BluetoothHelper mBluetoothHelperBow
  15. {
  16. get
  17. {
  18. return bluetoothHelperBow;
  19. }
  20. }
  21. private BluetoothHelperCharacteristic characteristicWriteBow;
  22. private BluetoothHelperService bluetoothServiceBow;
  23. private string bowTargetDeviceName = "Bbow_20210501";
  24. private string bowDeviceName = "";
  25. string bowDeviceService = "0000fff0";
  26. string bowDeviceCharacteristicWrite = "0000fff2";
  27. string bowDeviceCharacteristicNotify = "0000fff1";
  28. private bool isBowScanning;
  29. public bool mIsBowScanning
  30. {
  31. get
  32. {
  33. return isBowScanning;
  34. }
  35. }
  36. private bool isBowConnecting;
  37. public bool mIsBowConnecting
  38. {
  39. get
  40. {
  41. return isBowConnecting;
  42. }
  43. }
  44. private string data;
  45. #endregion
  46. private LinkedList<BluetoothDevice> devices;
  47. #region log输出
  48. public Action<string> OnLogAction;
  49. void logOutBow(string text)
  50. {
  51. Debug.Log("logOutBow:" + text);
  52. OnLogAction?.Invoke(text);
  53. }
  54. #endregion
  55. public static ConnetDevicesSingle ins;
  56. //默认关闭准心
  57. public bool bCrosshair = false;
  58. #region 红外Demo相关监听操作
  59. public Action<Vector3> posAction;
  60. public Action<int> infraredShootAction;
  61. public Action<bool> crosshairAction;
  62. #endregion
  63. void Awake()
  64. {
  65. //初始化
  66. ins = this;
  67. Debug.Log("ConnetDevicesSingle!");
  68. InitAutoDormancy();
  69. OnUpdateState();
  70. }
  71. //获取一次初始值
  72. public void OnInitConfig()
  73. {
  74. }
  75. public void OnUpdateState()
  76. {
  77. }
  78. public void ButtonShoot()
  79. {
  80. posAction?.Invoke(new Vector3(1 * Screen.width, 1 * Screen.height, 0));
  81. //调用游戏中的射箭接口
  82. if (ArmBow.ins)
  83. {
  84. ArmBow.ins.ADS_fire(true);
  85. }
  86. else
  87. {
  88. OnGameShoot?.Invoke(10);
  89. }
  90. }
  91. public void onShowCrosshair()
  92. {
  93. //显示游戏光标
  94. PlayerPrefs.SetInt("CrossHairImageActive", 1);
  95. bCrosshair = true;
  96. crosshairAction?.Invoke(true);
  97. }
  98. public void onHideCrosshair()
  99. {
  100. //隐藏游戏光标
  101. PlayerPrefs.SetInt("CrossHairImageActive", 0);
  102. bCrosshair = false;
  103. crosshairAction?.Invoke(false);
  104. }
  105. // Start is called before the first frame update
  106. void Start()
  107. {
  108. logOutBow("初始化BluetoothHelperAndroid");
  109. if (BluetoothHelperAndroid.IsBluetoothEnabled() == false)
  110. {
  111. Debug.Log("蓝牙未打开!");
  112. logOutBow("蓝牙未打开!");
  113. return;
  114. }
  115. data = "";
  116. try
  117. {
  118. BluetoothHelper.BLE = true;
  119. bluetoothHelperBow = BluetoothHelper.GetInstance();
  120. bluetoothHelperBow.OnConnected += OnConnected;
  121. bluetoothHelperBow.OnConnectionFailed += OnConnectionFailed;
  122. bluetoothHelperBow.OnScanEnded += OnScanEnded2;
  123. bluetoothHelperBow.OnCharacteristicChanged += (helper, value, characteristic) =>
  124. {
  125. // Debug.Log(characteristic.getName());
  126. // Debug.Log(System.Text.Encoding.ASCII.GetString(value));
  127. byte[] bytes = value;
  128. // Debug.Log("瞄准模块数据长度" + bytes.Length);
  129. if (bytes.Length != 27 && bytes.Length != 39)
  130. {
  131. if (bytes[0] == 0x5b)
  132. {
  133. //红外射击检测
  134. ShootByInfrared(bytes);
  135. }
  136. }
  137. };
  138. }
  139. catch (Exception e)
  140. {
  141. Debug.LogError(e);
  142. }
  143. }
  144. //Bow扫描结束
  145. void OnScanEnded2(BluetoothHelper helper, LinkedList<BluetoothDevice> nearbyDevices)
  146. {
  147. Debug.Log("2 ended " + nearbyDevices.Count);
  148. logOutBow("2 ended " + nearbyDevices.Count);
  149. if (nearbyDevices.Count == 0)
  150. {
  151. isBowScanning = helper.ScanNearbyDevices();
  152. return;
  153. }
  154. isBowScanning = false;
  155. foreach (BluetoothDevice device in nearbyDevices)
  156. {
  157. Debug.Log(device.DeviceName);
  158. if (device.DeviceName == bowTargetDeviceName)
  159. {
  160. logOutBow("匹配设备 " + device.DeviceName);
  161. bowDeviceName = bowTargetDeviceName;
  162. helper.setDeviceName(bowDeviceName);
  163. helper.Connect();
  164. isBowConnecting = true;
  165. }
  166. }
  167. }
  168. void OnConnected(BluetoothHelper helper)
  169. {
  170. if (helper.getId() == bluetoothHelperBow.getId())
  171. {
  172. Debug.Log("2 连接成功:" + helper.getDeviceName());
  173. logOutBow("弓箭 连接成功:" + helper.getDeviceName());
  174. isBowConnecting = false;
  175. foreach (BluetoothHelperService service in helper.getGattServices())
  176. {
  177. if (service.getName().ToLower().StartsWith(bowDeviceService))
  178. {
  179. bluetoothServiceBow = service;
  180. foreach (BluetoothHelperCharacteristic characteristic in service.getCharacteristics())
  181. {
  182. if (characteristic.getName().ToLower().StartsWith(bowDeviceCharacteristicWrite))
  183. {
  184. characteristicWriteBow = characteristic;
  185. }
  186. else if (characteristic.getName().ToLower().StartsWith(bowDeviceCharacteristicNotify))
  187. {
  188. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristic.getName());
  189. ch.setService(bluetoothServiceBow.getName());
  190. bluetoothHelperBow.Subscribe(ch);
  191. }
  192. }
  193. }
  194. }
  195. CallDelay(2, () =>
  196. {
  197. //if (status != BluetoothStatusEnum.ConnectSuccess) return;
  198. InitWhenConenct();
  199. });
  200. }
  201. }
  202. void OnConnectionFailed(BluetoothHelper helper)
  203. {
  204. Debug.Log("Connection lost");
  205. if (helper.getId() == bluetoothHelperBow.getId())
  206. {
  207. isBowConnecting = false;
  208. logOutBow("弓箭断开连接");
  209. }
  210. }
  211. //Connect bow ble
  212. public void OnBowScanNearbyDevices()
  213. {
  214. if (bluetoothHelperBow == null)
  215. return;
  216. if (!bluetoothHelperBow.isConnected() && !isBowScanning && !isBowConnecting)
  217. {
  218. //未连接,未扫描,不是连接中
  219. if (BluetoothHelperAndroid.IsBluetoothEnabled() == false)
  220. {
  221. Debug.Log("exception1");
  222. logOutBow("蓝牙未打开");
  223. return;
  224. }
  225. if (BluetoothHelperAndroid.RequestBluetoothPermissions(() =>
  226. {
  227. //开始扫描。调用最后一个bluetoothHelperBow扫描即可
  228. isBowScanning = bluetoothHelperBow.ScanNearbyDevices();
  229. logOutBow("开始扫描连接!");
  230. }, (permission) =>
  231. {
  232. if (permission.Contains("LOCATION"))
  233. {
  234. Debug.LogError("Exception:LOCATION");
  235. logOutBow("Exception:LOCATION");
  236. }
  237. else if (permission.Contains("BLUETOOTH"))
  238. {
  239. Debug.LogError("Exception: BLUETOOTH");
  240. logOutBow("Exception:BLUETOOTH");
  241. }
  242. })) return;
  243. isBowScanning = bluetoothHelperBow.ScanNearbyDevices();
  244. logOutBow("开始扫描连接!");
  245. }
  246. else if (!bluetoothHelperBow.isConnected() && isBowScanning)
  247. {
  248. //扫描中
  249. logOutBow("扫描中...");
  250. }
  251. else if (bluetoothHelperBow.isConnected())
  252. {
  253. logOutBow("断开Bow连接");
  254. //已连接,断开连接
  255. bluetoothHelperBow.Disconnect();
  256. }
  257. }
  258. void OnDestroy()
  259. {
  260. if (bluetoothHelperBow != null)
  261. {
  262. bluetoothHelperBow.Disconnect();
  263. OnDisconnect();
  264. }
  265. }
  266. /// <summary>
  267. /// 字节数组转16进制字符串:空格分隔
  268. /// </summary>
  269. /// <param name="byteDatas"></param>
  270. /// <returns></returns>
  271. public string ToHexStrFromByte(byte[] byteDatas)
  272. {
  273. StringBuilder builder = new StringBuilder();
  274. for (int i = 0; i < byteDatas.Length; i++)
  275. {
  276. builder.Append(string.Format("{0:X2} ", byteDatas[i]));
  277. }
  278. return builder.ToString().Trim();
  279. }
  280. /// <summary>
  281. /// 字符串转16进制
  282. /// </summary>
  283. /// <param name="input">要转格式的字符串</param>
  284. public byte[] Convert16(string strText)
  285. {
  286. strText = strText.Replace(" ", "");
  287. strText = strText.Replace(" ", "");
  288. Debug.Log(strText);
  289. byte[] bText = new byte[strText.Length / 2];
  290. for (int i = 0; i < strText.Length / 2; i++)
  291. {
  292. bText[i] = Convert.ToByte(Convert.ToInt32(strText.Substring(i * 2, 2), 16));
  293. }
  294. return bText;
  295. }
  296. string getBytesToIndex(byte[] bytes, int index)
  297. {
  298. StringBuilder builderCrosshair = new StringBuilder();
  299. builderCrosshair.Append(string.Format("{0:X2}", bytes[index]));
  300. return builderCrosshair.ToString().Trim();
  301. }
  302. float onVectorValue(byte[] bytes, int startIndex)
  303. {
  304. //整数部分
  305. string intPartHex = string.Format("{0:X2}", bytes[startIndex]).ToString().Trim(); ;
  306. int intPartNumber = Convert.ToInt32(intPartHex, 16);
  307. StringBuilder builder = new StringBuilder();
  308. for (int i = 0; i < 2; i++)
  309. {
  310. builder.Append(string.Format("{0:X2}", bytes[i + startIndex + 1]));
  311. }
  312. string dataHex = builder.ToString().Trim();
  313. int decimalPartNumber = Convert.ToInt32(dataHex, 16);
  314. return intPartNumber + (float)decimalPartNumber / 32768;
  315. }
  316. void CallDelay(float delayTime, TweenCallback callback)
  317. {
  318. Sequence sequence = DOTween.Sequence();
  319. sequence.PrependInterval(delayTime).AppendCallback(callback);
  320. sequence.SetUpdate(true);
  321. }
  322. #region 自动进入/退出休眠状态, 这里做程指令发送队列,为了控制连续发送指令的间隔,避免硬件收不到或处理不过来
  323. class CmdToSend
  324. {
  325. public string[] cmds;
  326. public Action onComplete;
  327. public Func<bool> canDo;
  328. public CmdToSend(string[] cmds, Action onComplete, Func<bool> canDo)
  329. {
  330. this.cmds = cmds;
  331. this.onComplete = onComplete;
  332. this.canDo = canDo;
  333. }
  334. }
  335. Queue<CmdToSend> cmdWaitingList = new Queue<CmdToSend>();
  336. bool isSendCmdLocked = false;
  337. bool canAutoDormancy = false;
  338. bool isStartUp = false;
  339. JCUnityLib.CountLock needModularAwake = new JCUnityLib.CountLock();
  340. void InitAutoDormancy()
  341. {
  342. //暂时关闭自动休眠,默认是需要模块保持激活
  343. needModularAwake.Lock();
  344. }
  345. void InitWhenConenct()
  346. {
  347. canAutoDormancy = true;
  348. List<string> cmds = new List<string>();
  349. cmds.Add("M"); //获取Mac地址
  350. cmds.Add("b"); //确保开启stm32
  351. cmds.Add("b"); //获取初始电量
  352. cmds.Add("1"); //开启发送逻辑
  353. Action onComplete = null;
  354. if (needModularAwake.IsLocked())
  355. {
  356. cmds.Add("w"); //红外灯开启
  357. //cmds.Add("3"); //九轴开启
  358. onComplete = () =>
  359. {
  360. isStartUp = true;
  361. };
  362. }
  363. else
  364. {
  365. cmds.Add("s"); //红外灯关闭
  366. cmds.Add("S"); //Stm32关闭
  367. //cmds.Add("4"); //九轴关闭
  368. onComplete = () =>
  369. {
  370. isStartUp = false;
  371. };
  372. }
  373. SendCDM(null, onComplete, cmds.ToArray());
  374. }
  375. void DestroyWhenDisconenct()
  376. {
  377. canAutoDormancy = false;
  378. sendCMD_CheckAndDoStop(null);
  379. }
  380. //启动
  381. void StartUp()
  382. {
  383. SendCDM(() =>
  384. {
  385. return !isStartUp;
  386. }, () =>
  387. {
  388. isStartUp = true;
  389. }, "b", "w", "3");
  390. }
  391. void SendCDM(Func<bool> canDo, Action onComplete, params string[] cmds)
  392. {
  393. CmdToSend cmdToSend = new CmdToSend(cmds, onComplete, canDo);
  394. if (isSendCmdLocked)
  395. {
  396. cmdWaitingList.Enqueue(cmdToSend);
  397. return;
  398. }
  399. sendCMD_NotCheck(cmdToSend);
  400. }
  401. void sendCMD_NotCheck(CmdToSend cmdToSend)
  402. {
  403. if (cmdToSend.canDo != null && !cmdToSend.canDo.Invoke())
  404. {
  405. sendCMD_CheckNext();
  406. return;
  407. }
  408. isSendCmdLocked = true;
  409. Sequence sequence = DOTween.Sequence();
  410. sequence.PrependInterval(0.3f);
  411. foreach (var cmd in cmdToSend.cmds)
  412. {
  413. sequence.AppendCallback(() =>
  414. {
  415. bool stopped = sendCMD_CheckAndDoStop(sequence);
  416. if (!stopped) onWriteDataToBow(cmd);
  417. });
  418. sequence.AppendInterval(0.5f);
  419. }
  420. sequence.AppendCallback(() =>
  421. {
  422. bool stopped = sendCMD_CheckAndDoStop(sequence);
  423. if (!stopped)
  424. {
  425. isSendCmdLocked = false;
  426. cmdToSend.onComplete?.Invoke();
  427. sendCMD_CheckNext();
  428. }
  429. });
  430. sequence.SetUpdate(true);
  431. }
  432. void sendCMD_CheckNext()
  433. {
  434. if (cmdWaitingList.Count <= 0) return;
  435. CmdToSend cmdToSend = cmdWaitingList.Dequeue();
  436. sendCMD_NotCheck(cmdToSend);
  437. }
  438. bool sendCMD_CheckAndDoStop(Sequence sequence)
  439. {
  440. if (canAutoDormancy) return false;
  441. isStartUp = false;
  442. isSendCmdLocked = false;
  443. cmdWaitingList.Clear();
  444. if (sequence != null) sequence.Kill();
  445. return true;
  446. }
  447. #endregion
  448. #region 弓箭部分代码操作
  449. public Action<float> OnGameShoot;
  450. [NonSerialized] public byte byteTime1;
  451. [NonSerialized] public byte byteTime2;
  452. /**通过红外线数据进行射击 */
  453. public void ShootByInfrared(byte[] bytes)
  454. {
  455. byteTime1 = bytes[2];
  456. byteTime1 = bytes[3];
  457. int id = bytes[1]; //序号
  458. float time1 = bytes[2] * 0.1f; //时区1耗时
  459. float time2 = bytes[3] * 0.1f; //时区2耗时
  460. float totalTime = time1 + time2;
  461. //校验和
  462. int sumCheck = bytes[0] + bytes[1] + bytes[2] + bytes[3];
  463. sumCheck &= 0xff;
  464. //校验和比较结果
  465. bool sumCheckRes = sumCheck == bytes[4];
  466. //弓轨速度
  467. float speed = 0.05f / (totalTime / 1000f);
  468. //通过动能定理求箭的速度(实体箭质量*实体箭速度^2=游戏中箭的质量*游戏中箭的速度^2)
  469. float shootSpeed = Mathf.Sqrt(speed * speed * CommonConfig.arrowWeight / UserSettings.ins.actualArrowWeight);
  470. //打印
  471. string logTxt = $"序号{id},时区1:{time1}毫秒,时区2:{time2}毫秒,校验:{sumCheckRes},弓轨速度:{speed}m/s,箭的速度:{shootSpeed}m/s";
  472. logOutBow(logTxt);
  473. // if (DebugForDevice.ins) DebugForDevice.ins.LogInfrared(logTxt);
  474. //收到射箭数据,就回复硬件,否则n毫秒后硬件会认为丢包进行重传
  475. try
  476. {
  477. if (sumCheckRes) ReplyInfraredShoot(); //如果数据正确,则回复硬件
  478. }
  479. catch (Exception) { }
  480. //打开准心的时候,直接调用射击接口
  481. if (ArmBow.ins)
  482. {
  483. ArmBow.ins.ADS_fire(true);
  484. }
  485. else if (DuckHunter.SmartBowController.Instance)
  486. {
  487. DuckHunter.SmartBowController.Instance.OnShooting(shootSpeed);
  488. }
  489. //else
  490. //{
  491. // OnGameShoot?.Invoke(shootSpeed);
  492. //}
  493. }
  494. //断开弓箭连接
  495. void OnDisconnect()
  496. {
  497. DestroyWhenDisconenct();
  498. }
  499. public void RequestBattery()
  500. {
  501. if (!isStartUp) return;
  502. if (isSendCmdLocked) return;
  503. onWriteDataToBow("b");
  504. }
  505. //回复弓箭红外
  506. public void ReplyInfraredShoot()
  507. {
  508. if (isSendCmdLocked) return;
  509. onWriteDataToBow("I");
  510. }
  511. public void onWriteDataToBow(string data)
  512. {
  513. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristicWriteBow.getName());
  514. ch.setService(bluetoothServiceBow.getName());
  515. bluetoothHelperBow.WriteCharacteristic(ch, data);
  516. }
  517. #endregion
  518. }
  519. }