BluetoothAim.cs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410
  1. using ArduinoBluetoothAPI;
  2. using System;
  3. using UnityEngine;
  4. using System.Collections.Generic;
  5. using UnityEngine.UI;
  6. using DG.Tweening;
  7. using SmartBowSDK;
  8. using System.Collections;
  9. /* 蓝牙瞄准模块 */
  10. /* 管理1p和2p蓝牙连接,脚本外调用逻辑如果同时连接1p和2p设备,以前的逻辑还是以1p为主,如果只连2p,则使用2p数据*/
  11. public class BluetoothAim : MonoBehaviour
  12. {
  13. #region 弓箭蓝牙模块基本信息
  14. readonly string targetDeviceName = "Bbow_20210501 | ARTEMIS Pro";//HOUYI Pro
  15. readonly string targetDeviceNameHOUYIPro = "HOUYI Pro";
  16. readonly string targetDeviceNameGun = "Pistol | Pistol M9 | Bbow_20210501";
  17. string targetDeviceService
  18. {
  19. get
  20. {
  21. if (CommonConfig.devicePlan == 0 || CommonConfig.devicePlan == 3)
  22. {
  23. #if UNITY_ANDROID
  24. return "0000fff0";
  25. #else
  26. return "fff0";
  27. #endif
  28. }
  29. return "6e400001";
  30. }
  31. }
  32. string targetDeviceCharacteristicWrite
  33. {
  34. get
  35. {
  36. if (CommonConfig.devicePlan == 0 || CommonConfig.devicePlan == 3)
  37. {
  38. #if UNITY_ANDROID
  39. return "0000fff2";
  40. #else
  41. return "fff2";
  42. #endif
  43. }
  44. return "6e400002";
  45. }
  46. }
  47. string targetDeviceCharacteristicNotify
  48. {
  49. get
  50. {
  51. if (CommonConfig.devicePlan == 0 || CommonConfig.devicePlan == 3)
  52. {
  53. #if UNITY_ANDROID
  54. return "0000fff1";
  55. #else
  56. return "fff1";
  57. #endif
  58. }
  59. return "6e400003";
  60. }
  61. }
  62. #endregion
  63. //当前选择的设备
  64. BluetoothPlayer currentBLEPlayer = BluetoothPlayer.FIRST_PLAYER;
  65. //1p蓝牙连接
  66. BluetoothHelper bluetoothHelper;
  67. BluetoothHelperCharacteristic characteristicWrite;
  68. BluetoothHelperService bluetoothService;
  69. string deviceName = "";
  70. bool canConnect = true;
  71. [SerializeField] Text textUI;
  72. public BluetoothStatusEnum status = BluetoothStatusEnum.Connect;
  73. int dataCount = 0;
  74. public bool hasData = false;
  75. public long hasDataTime;
  76. public static bool scanLock = false; //防止同时扫描冲突
  77. public static BluetoothAim ins;
  78. //根据设备情况来看是否需要解密,目前就是枪需要进行解密操作
  79. public bool NeedDecryption = false;
  80. public BluetoothWindows firstBluetoothWindows { get; set; }
  81. void Start()
  82. {
  83. ins = this;
  84. InitAutoDormancy();
  85. #if UNITY_STANDALONE_WIN || UNITY_EDITOR
  86. // new GameObject("BleUDP").AddComponent<BleUDP>();
  87. firstBluetoothWindows = new BluetoothWindows();
  88. firstBluetoothWindows.OnConnected = OnConnected_windows1;
  89. firstBluetoothWindows.OnConnectionFailed = OnConnectionFailed_windows1;
  90. firstBluetoothWindows.OnCharacteristicChanged = OnCharacteristicChanged_windows1;
  91. //window蓝牙连接
  92. if (currentBLEPlayer == BluetoothPlayer.FIRST_PLAYER)
  93. {
  94. Debug.Log("FIRST_PLAYER BleWinHelper.RegisterTo");
  95. BleWinHelper.RegisterTo(gameObject, firstBluetoothWindows,"1P");
  96. }
  97. #endif
  98. }
  99. void OnDestroy()
  100. {
  101. //删除ble。1p,2p 都删除
  102. DisconnectBleHelper();
  103. DisconnectSmartBowHelper2P();
  104. }
  105. private bool userDoConnect = false;
  106. private bool doConnect = false;
  107. public Func<bool> action_DoConnectInterceptor;
  108. public void DoConnect()
  109. {
  110. if (action_DoConnectInterceptor != null) {
  111. if (action_DoConnectInterceptor.Invoke()) return;
  112. }
  113. if (status == BluetoothStatusEnum.Connect)
  114. {
  115. connectCanceled = false;
  116. userDoConnect = true;
  117. doConnect = true;
  118. SetStatus(BluetoothStatusEnum.Connecting);
  119. }
  120. else if (status == BluetoothStatusEnum.ConnectSuccess)
  121. {
  122. userDoConnect = false;
  123. doConnect = false;
  124. OnDisconnect();
  125. DisconnectBleHelper();
  126. //#if UNITY_STANDALONE_WIN || UNITY_EDITOR
  127. // //BleUDP.ins.Disconnect();
  128. // if (firstBluetoothWindows.Disconnect()) SetStatus(BluetoothStatusEnum.Connect);
  129. //#else
  130. // DisconnectBleHelper();
  131. //#endif
  132. }
  133. }
  134. //连接取消,退回登录时需要取消连接(扫描)
  135. [NonSerialized] public bool connectCanceled = false;
  136. void OnDisconnect()
  137. {
  138. curMac = null;
  139. dataCount = 0;
  140. hasData = false;
  141. canConnect = true;
  142. SetStatus(BluetoothStatusEnum.ConnectFail);
  143. BowCamera.isTouchMode = true;
  144. DestroyWhenDisconenct();
  145. if (AimHandler.ins) AimHandler.ins.SetMsOldDefault();
  146. }
  147. float notUserDoConnectTime = 0;
  148. void Update()
  149. {
  150. updateSmartBowHelper2P();
  151. if (userDoConnect && status == BluetoothStatusEnum.Connect)
  152. {
  153. DoConnect();
  154. }
  155. if (doConnect) Connect();
  156. if (CommonConfig.StandaloneMode)
  157. {
  158. if (!userDoConnect && status == BluetoothStatusEnum.Connect)
  159. {
  160. if (notUserDoConnectTime == 0)
  161. {
  162. DoConnect();
  163. notUserDoConnectTime = 0.1f;
  164. }
  165. else
  166. {
  167. notUserDoConnectTime += Time.deltaTime;
  168. if (notUserDoConnectTime > 2.5f)
  169. {
  170. DoConnect();
  171. notUserDoConnectTime = 0.1f;
  172. }
  173. }
  174. }
  175. }
  176. }
  177. void SetStatus(BluetoothStatusEnum statusValue)
  178. {
  179. status = statusValue;
  180. if (status == BluetoothStatusEnum.ConnectFail)
  181. {
  182. Sequence sequence = DOTween.Sequence();
  183. sequence.AppendInterval(2f);
  184. sequence.AppendCallback(delegate ()
  185. {
  186. if (status == BluetoothStatusEnum.ConnectFail)
  187. {
  188. status = BluetoothStatusEnum.Connect;
  189. }
  190. });
  191. sequence.SetUpdate(true);
  192. SimulateMouseController.ins?.SetBleConnected(false);
  193. } else if (status == BluetoothStatusEnum.ConnectSuccess) {
  194. SimulateMouseController.ins?.SetBleConnected(true);
  195. }
  196. }
  197. void DisconnectBleHelper()
  198. {
  199. if (BluetoothWindows.IsWindows())
  200. {
  201. if (firstBluetoothWindows.Disconnect())
  202. SetStatus(BluetoothStatusEnum.Connect);
  203. return;
  204. }
  205. if (bluetoothHelper != null) bluetoothHelper.Disconnect();
  206. }
  207. void DisconnectSmartBowHelper2P() {
  208. //2p
  209. if (smartBowHelper2P != null) smartBowHelper2P.Disconnect();
  210. }
  211. void Connect()
  212. {
  213. //if (BluetoothShoot.scanLock)
  214. //{
  215. // return;
  216. //}
  217. if (!canConnect)
  218. {
  219. return;
  220. }
  221. doConnect = false;
  222. doConnect2P = false;
  223. scanLock = true;
  224. canConnect = false;
  225. _scanCanRetryCount = 4;
  226. SetStatus(BluetoothStatusEnum.Connecting);
  227. #if UNITY_STANDALONE_WIN || UNITY_EDITOR
  228. //ConnectBleByUDP();
  229. firstBluetoothWindows.Connect();
  230. #else
  231. ConnectBleHelper();
  232. #endif
  233. }
  234. int _scanCanRetryCount = 4;
  235. void ConnectBleHelper()
  236. {
  237. #if UNITY_ANDROID
  238. PopupMgr.ins.ClearAllTip();
  239. if (BluetoothHelperAndroid.IsBluetoothEnabled() == false)
  240. {
  241. Debug.Log("BluetoothHelperAndroid.IsBluetoothEnabled():"+ BluetoothHelperAndroid.IsBluetoothEnabled());
  242. HandleConnectException(TextAutoLanguage2.GetTextByKey("ble-exception1"));
  243. return;
  244. }
  245. if (BluetoothHelperAndroid.RequestBluetoothPermissions(ConnectBleHelper, (permission) => {
  246. Debug.Log("permission ==== :" + permission);
  247. if (permission.Contains("LOCATION"))
  248. {
  249. HandleConnectException(TextAutoLanguage2.GetTextByKey("ble-exception2"));
  250. }
  251. else if (permission.Contains("BLUETOOTH"))
  252. {
  253. HandleConnectException(TextAutoLanguage2.GetTextByKey("ble-exception3"));
  254. }
  255. })) return;
  256. #endif
  257. try
  258. {
  259. BluetoothHelper.BLE = true;
  260. bluetoothHelper = BluetoothHelper.GetNewInstance();
  261. bluetoothHelper.OnConnected += (BluetoothHelper helper) =>
  262. {
  263. Log("连接成功\n" + helper.getDeviceName());
  264. SetStatus(BluetoothStatusEnum.ConnectSuccess);
  265. SetMainConnectDeviceType();
  266. if (connectCanceled) {
  267. Debug.Log("ble connectCanceled");
  268. DoConnect();
  269. return;
  270. }
  271. BowCamera.isTouchMode = false;
  272. foreach (BluetoothHelperService service in helper.getGattServices())
  273. {
  274. if (service.getName().ToLower().StartsWith(targetDeviceService))
  275. {
  276. bluetoothService = service;
  277. foreach (BluetoothHelperCharacteristic characteristic in service.getCharacteristics())
  278. {
  279. if (characteristic.getName().ToLower().StartsWith(targetDeviceCharacteristicWrite))
  280. {
  281. characteristicWrite = characteristic;
  282. }
  283. else if (characteristic.getName().ToLower().StartsWith(targetDeviceCharacteristicNotify))
  284. {
  285. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristic.getName());
  286. ch.setService(bluetoothService.getName());
  287. bluetoothHelper.Subscribe(ch);
  288. }
  289. }
  290. }
  291. }
  292. // CallDelay(1, OpenInfrared);
  293. // CallDelay(2, OpenReceiveData);
  294. // CallDelay(3, RequestBattery);
  295. if (CommonConfig.EnableDecryption && NeedDecryption)
  296. {
  297. // 这里验证指令,开始请求授权
  298. // 启动轮询协程
  299. StartCoroutine(PollingCoroutine());
  300. }
  301. else {
  302. //除了pc,Android 直接连接
  303. CallDelay(2, () =>
  304. {
  305. if (status != BluetoothStatusEnum.ConnectSuccess) return;
  306. InitWhenConenct();
  307. if (CommonConfig.StandaloneMode)
  308. {
  309. if (UnityEngine.SceneManagement.SceneManager.GetActiveScene().name == "Home"
  310. && PersistenHandler.ins.menuBackCtr.views.Count == 0
  311. && !FindObjectOfType<NewUserGuider>())
  312. {
  313. ViewMgr.Instance.ShowView<GameStartView>();
  314. }
  315. }
  316. });
  317. }
  318. };
  319. bluetoothHelper.OnConnectionFailed += (BluetoothHelper helper) =>
  320. {
  321. Log("连接失败\n" + helper.getDeviceName());
  322. OnDisconnect();
  323. };
  324. bluetoothHelper.OnCharacteristicChanged += (helper, value, characteristic) =>
  325. {
  326. OnCharacteristicChanged(helper, value, characteristic);
  327. };
  328. bluetoothHelper.OnScanEnded += (BluetoothHelper helper, LinkedList<BluetoothDevice> nearbyDevices) =>
  329. {
  330. scanLock = false;
  331. if (connectCanceled) {
  332. userDoConnect = false;
  333. canConnect = true;
  334. status = BluetoothStatusEnum.Connect;
  335. Debug.Log("ble connectCanceled");
  336. return;
  337. }
  338. foreach (BluetoothDevice device in nearbyDevices)
  339. {
  340. Log("发现设备 " + device.DeviceName);
  341. //if (device.DeviceName == targetDeviceName)
  342. if (AimHandler.ins.aimDeviceInfo.type == (int)AimDeviceType.HOUYIPRO)
  343. { //需要判断是否是红外弓箭
  344. //targetDeviceNameHOUYIPro targetDeviceNameHOUYIPro{ HOUYI Pro }
  345. if (targetDeviceNameHOUYIPro.Contains(device.DeviceName))
  346. {
  347. BLEConnectByName(device.DeviceName);
  348. Log("匹配HOUYIPRO设备 " + device.DeviceName);
  349. return;
  350. }
  351. }
  352. else if (AimHandler.ins.aimDeviceInfo.type == (int)AimDeviceType.ARTEMISPRO)
  353. { //需要判断是否是ARTEMISPro弓箭
  354. if (targetDeviceName.Contains(device.DeviceName))
  355. {
  356. BLEConnectByName(device.DeviceName);
  357. Log("匹配ARTEMISPro设备 " + device.DeviceName);
  358. return;
  359. }
  360. }
  361. else if (AimHandler.ins.aimDeviceInfo.type == (int)AimDeviceType.Gun)
  362. {
  363. //需要判断是否是枪
  364. if (targetDeviceNameGun.Contains(device.DeviceName))
  365. {
  366. BLEConnectByName(device.DeviceName);
  367. Log("匹配枪设备 " + device.DeviceName);
  368. return;
  369. }
  370. }
  371. else
  372. { //其余的九轴连接
  373. //不允许匹配HOUYIPRO,因为这个没有九轴 targetDeviceName { Bbow_20210501 }
  374. if (targetDeviceName.Contains(device.DeviceName))
  375. {
  376. BLEConnectByName(device.DeviceName);
  377. Log("匹配普通设备设备 " + device.DeviceName);
  378. return;
  379. }
  380. }
  381. }
  382. if (_scanCanRetryCount > 0) {
  383. _scanCanRetryCount--;
  384. scanLock = true;
  385. ConnectBleHelper();
  386. } else {
  387. userDoConnect = false;
  388. canConnect = true;
  389. Log("没有发现设备");
  390. TextAutoLanguage2.GetTextByKey("ble-dev-notfound");
  391. SetStatus(BluetoothStatusEnum.ConnectFail);
  392. }
  393. };
  394. bluetoothHelper.ScanNearbyDevices();
  395. Log("正在扫描设备");
  396. }
  397. catch (Exception e)
  398. {
  399. Debug.LogError(e);
  400. HandleConnectException(TextAutoLanguage2.GetTextByKey("ble-please-open-ble"));
  401. }
  402. }
  403. void BLEConnectByName(string name) {
  404. deviceName = name;
  405. bluetoothHelper.setDeviceName(deviceName);
  406. bluetoothHelper.Connect();
  407. }
  408. void HandleConnectException(string errorText)
  409. {
  410. scanLock = false;
  411. canConnect = true;
  412. // SetStatus(BluetoothStatusEnum.ConnectFail);
  413. status = BluetoothStatusEnum.Connect;
  414. userDoConnect = false;
  415. PopupMgr.ins.ShowTip(errorText);
  416. }
  417. // 协程来处理轮询
  418. // 目前仅手枪支持该指令。
  419. // 调用 AUTHOR_SendReq 方法,传递系统Tick值(在这里用一个示例值)
  420. private bool isPolling = false;
  421. private int PollingCoroutineCount = 4;
  422. private IEnumerator PollingCoroutine()
  423. {
  424. // 发送请求
  425. // SendEncrypt();
  426. // 设置轮询标志
  427. isPolling = true;
  428. PollingCoroutineCount = 4;
  429. uint systemTick = (uint)DateTime.Now.Ticks;
  430. while (isPolling)
  431. {
  432. // 等待一秒
  433. yield return new WaitForSeconds(1f);
  434. SendEncrypt(systemTick);
  435. PollingCoroutineCount--;
  436. }
  437. }
  438. /// <summary>
  439. /// 1、加密字节由系统生成的随机码加密而成;
  440. /// 2、蓝牙每次断开并重新连接后,会重新生成随机加密值;
  441. /// 3、当设备未发送正确的解密信息时,APP会每秒发送1次请求,直到解密成功。
  442. /// </summary>
  443. /// <param name="systemTick"></param>
  444. private void SendEncrypt(uint systemTick) {
  445. byte[] sendByte = BluetoothDecryptor.AUTHOR_SendReq(systemTick);
  446. Debug.Log("请求sendByte:" + BitConverter.ToString(sendByte));
  447. WriteByteData(sendByte);
  448. }
  449. // 模拟从硬件读取数据
  450. public void StopEncrypt()
  451. {
  452. isPolling = false;
  453. }
  454. void ConnectBleByUDP()
  455. {
  456. try
  457. {
  458. BleUDP.ins.OnConnected = () =>
  459. {
  460. Log("连接成功\n" + deviceName);
  461. SetStatus(BluetoothStatusEnum.ConnectSuccess);
  462. BowCamera.isTouchMode = false;
  463. InitWhenConenct();
  464. };
  465. BleUDP.ins.OnConnectionFailed = () =>
  466. {
  467. Log("连接失败\n" + deviceName);
  468. OnDisconnect();
  469. };
  470. BleUDP.ins.OnCharacteristicChanged = (byte[] value) =>
  471. {
  472. //if (!hasData) {
  473. // hasDataTime = JCUnityLib.TimeUtils.GetTimestamp();
  474. // UploadMacAddress(value);
  475. //}
  476. //hasData = true;
  477. if (status != BluetoothStatusEnum.ConnectSuccess) return;
  478. if (!hasData)
  479. {
  480. hasData = true;
  481. hasDataTime = JCUnityLib.TimeUtils.GetTimestamp();
  482. }
  483. dataCount++;
  484. if (curMac == null && dataCount < 500)
  485. {
  486. UploadMacAddress(value);
  487. }
  488. byte[] bytes = value;
  489. // Log(String.Join(",", bytes));
  490. BluetoothClient.UploadData(0, bytes);
  491. if (AimHandler.ins)
  492. {
  493. AimHandler.ins.OnDataReceived(bytes);
  494. }
  495. };
  496. BleUDP.ins.OnScanEnded = () =>
  497. {
  498. scanLock = false;
  499. deviceName = targetDeviceName;
  500. BleUDP.ins.Connect();
  501. Log("发现设备\n" + deviceName);
  502. };
  503. BleUDP.ins.ScanNearbyDevices();
  504. }
  505. catch (Exception e)
  506. {
  507. Debug.LogError(e.Message);
  508. Debug.LogError(e.StackTrace);
  509. scanLock = false;
  510. canConnect = true;
  511. SetStatus(BluetoothStatusEnum.ConnectFail);
  512. }
  513. }
  514. #region 自动进入/退出休眠状态, 这里做程指令发送队列,为了控制连续发送指令的间隔,避免硬件收不到或处理不过来
  515. class CmdToSend
  516. {
  517. public string[] cmds;
  518. public Action onComplete;
  519. public Func<bool> canDo;
  520. public CmdToSend(string[] cmds, Action onComplete, Func<bool> canDo)
  521. {
  522. this.cmds = cmds;
  523. this.onComplete = onComplete;
  524. this.canDo = canDo;
  525. }
  526. }
  527. Queue<CmdToSend> cmdWaitingList = new Queue<CmdToSend>();
  528. bool isSendCmdLocked = false;
  529. bool canAutoDormancy = false;
  530. bool isStartUp = false;
  531. JCUnityLib.CountLock needModularAwake = new JCUnityLib.CountLock();
  532. void CheckAndStartUp()
  533. {
  534. if (needModularAwake.IsLocked())
  535. {
  536. StartUp();
  537. }
  538. else
  539. {
  540. Dormancy();
  541. }
  542. }
  543. void InitAutoDormancy()
  544. {
  545. // GlobalEventCenter.ins.onGameSceneLoad += () => {
  546. // needModularAwake.Lock();
  547. // CheckAndStartUp();
  548. // };
  549. // GlobalEventCenter.ins.onGameSceneDestroy += () => {
  550. // needModularAwake.Unlock();
  551. // CheckAndStartUp();
  552. // };
  553. // GlobalEventCenter.ins.onSimulateMouseAwakeChanged += (waked) => {
  554. // if (waked) needModularAwake.Lock();
  555. // else needModularAwake.Unlock();;
  556. // CheckAndStartUp();
  557. // };
  558. // GlobalEventCenter.ins.onDeviceCalibrateViewAwakeChanged += (waked) => {
  559. // if (waked) needModularAwake.Lock();
  560. // else needModularAwake.Unlock();;
  561. // CheckAndStartUp();
  562. // };
  563. //暂时关闭自动休眠,默认是需要模块保持激活
  564. needModularAwake.Lock();
  565. }
  566. void InitWhenConenct()
  567. {
  568. canAutoDormancy = true;
  569. List<string> cmds = new List<string>();
  570. cmds.Add("M"); //获取Mac地址
  571. cmds.Add("I"); //获取设备信息
  572. cmds.Add("b"); //确保开启stm32
  573. cmds.Add("b"); //获取初始电量
  574. cmds.Add("1"); //开启发送逻辑
  575. Action onComplete = null;
  576. if (needModularAwake.IsLocked())
  577. {
  578. cmds.Add("w"); //红外灯开启
  579. cmds.Add("3"); //九轴开启
  580. onComplete = () =>
  581. {
  582. isStartUp = true;
  583. };
  584. }
  585. else
  586. {
  587. cmds.Add("s"); //红外灯关闭
  588. cmds.Add("S"); //Stm32关闭
  589. cmds.Add("4"); //九轴关闭
  590. onComplete = () =>
  591. {
  592. isStartUp = false;
  593. };
  594. }
  595. SendCDM(null, onComplete, cmds.ToArray());
  596. }
  597. void DestroyWhenDisconenct()
  598. {
  599. canAutoDormancy = false;
  600. sendCMD_CheckAndDoStop(null);
  601. }
  602. //启动
  603. void StartUp()
  604. {
  605. SendCDM(() =>
  606. {
  607. return !isStartUp;
  608. }, () =>
  609. {
  610. isStartUp = true;
  611. }, "b", "w", "3");
  612. }
  613. //休眠
  614. void Dormancy()
  615. {
  616. SendCDM(() =>
  617. {
  618. return isStartUp;
  619. }, () =>
  620. {
  621. isStartUp = false;
  622. }, "4", "s", "S");
  623. }
  624. void SendCDM(Func<bool> canDo, Action onComplete, params string[] cmds)
  625. {
  626. CmdToSend cmdToSend = new CmdToSend(cmds, onComplete, canDo);
  627. if (isSendCmdLocked)
  628. {
  629. cmdWaitingList.Enqueue(cmdToSend);
  630. return;
  631. }
  632. sendCMD_NotCheck(cmdToSend);
  633. }
  634. void sendCMD_NotCheck(CmdToSend cmdToSend)
  635. {
  636. if (cmdToSend.canDo != null && !cmdToSend.canDo.Invoke())
  637. {
  638. sendCMD_CheckNext();
  639. return;
  640. }
  641. isSendCmdLocked = true;
  642. Sequence sequence = DOTween.Sequence();
  643. sequence.PrependInterval(0.3f);
  644. foreach (var cmd in cmdToSend.cmds)
  645. {
  646. sequence.AppendCallback(() =>
  647. {
  648. bool stopped = sendCMD_CheckAndDoStop(sequence);
  649. if (!stopped) WriteData(cmd);
  650. });
  651. sequence.AppendInterval(0.5f);
  652. }
  653. sequence.AppendCallback(() =>
  654. {
  655. bool stopped = sendCMD_CheckAndDoStop(sequence);
  656. if (!stopped)
  657. {
  658. isSendCmdLocked = false;
  659. cmdToSend.onComplete?.Invoke();
  660. sendCMD_CheckNext();
  661. }
  662. });
  663. sequence.SetUpdate(true);
  664. }
  665. void sendCMD_CheckNext()
  666. {
  667. if (cmdWaitingList.Count <= 0) return;
  668. CmdToSend cmdToSend = cmdWaitingList.Dequeue();
  669. sendCMD_NotCheck(cmdToSend);
  670. }
  671. bool sendCMD_CheckAndDoStop(Sequence sequence)
  672. {
  673. if (canAutoDormancy) return false;
  674. isStartUp = false;
  675. isSendCmdLocked = false;
  676. cmdWaitingList.Clear();
  677. if (sequence != null) sequence.Kill();
  678. return true;
  679. }
  680. #endregion
  681. public void RequestBattery()
  682. {
  683. if (!isStartUp) return;
  684. if (isSendCmdLocked) return;
  685. WriteData("b");
  686. }
  687. /// <summary>
  688. /// 获取设备信息 手枪、HOUYI Pro 和 ARTEMIS Pro
  689. /// </summary>
  690. public void RequestDeviceInfo()
  691. {
  692. if (isSendCmdLocked) return;
  693. WriteData("I");
  694. }
  695. /// <summary>
  696. /// 旧的红外射箭指令
  697. /// </summary>
  698. public void ReplyInfraredShoot()
  699. {
  700. if (isSendCmdLocked) return;
  701. WriteData("I");
  702. }
  703. void CallDelay(float delayTime, TweenCallback callback)
  704. {
  705. Sequence sequence = DOTween.Sequence();
  706. sequence.PrependInterval(delayTime).AppendCallback(callback);
  707. sequence.SetUpdate(true);
  708. }
  709. public void WriteData(string data)
  710. {
  711. //Debug.Log("WriteData:" + data);
  712. #if UNITY_STANDALONE_WIN || UNITY_EDITOR
  713. //BleUDP.ins.SendMsg(data);
  714. firstBluetoothWindows.Write(data);
  715. #else
  716. if (DebugDeviceCMD.ins) DebugDeviceCMD.ins.ShowCMD(data);
  717. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristicWrite.getName());
  718. ch.setService(bluetoothService.getName());
  719. bluetoothHelper.WriteCharacteristic(ch, data);
  720. #endif
  721. }
  722. public void WriteByteData(byte[] data)
  723. {
  724. #if UNITY_STANDALONE_WIN || UNITY_EDITOR
  725. firstBluetoothWindows.WriteByte(data);
  726. #else
  727. BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristicWrite.getName());
  728. ch.setService(bluetoothService.getName());
  729. bluetoothHelper.WriteCharacteristic(ch, data);
  730. #endif
  731. }
  732. void Log(string text)
  733. {
  734. if (textUI)
  735. {
  736. textUI.text = text;
  737. }
  738. Debug.Log(string.Format("[{0}]{1}", typeof(BluetoothAim).Name, text));
  739. }
  740. [NonSerialized] public string curMac;
  741. void UploadMacAddress(byte[] bytes) {
  742. string mac = System.Text.Encoding.ASCII.GetString(bytes);
  743. if (mac != null) mac = mac.Trim();
  744. if (CheckIsMacValid(mac)) {
  745. SideTipView.ShowTip("Mac获取成功:" + mac, Color.white);
  746. //需要增加一个判断,判断是否对应的mac设备。不是需要进行重新连接
  747. if (!AimHandler.ins.aimDeviceInfo.bInitMac)
  748. {
  749. Debug.Log("设置设备mac:"+ mac);
  750. AimHandler.ins.SetAimDeviceMac(mac);
  751. }
  752. else if (AimHandler.ins.aimDeviceInfo.mac != mac) {
  753. Debug.Log("设备不一样,断开连接");
  754. DoConnect();
  755. //延迟一点时间后重新触发扫描
  756. CallDelay(4, () =>
  757. {
  758. Debug.Log("CallDelay 重新连接");
  759. DoConnect();
  760. });
  761. return;
  762. }
  763. curMac = mac;
  764. LoginMgr.myUserInfo.mac = mac;
  765. UserComp.Instance.saveMac();
  766. } else {
  767. SideTipView.ShowTip("Mac获取失败", Color.yellow);
  768. }
  769. }
  770. bool CheckIsMacValid(string mac) {
  771. if (mac == null) return false;
  772. if (!mac.StartsWith("{")) return false;
  773. if (!mac.EndsWith("}")) return false;
  774. if (!mac.Contains(":")) return false;
  775. char[] validChars = {'{','}',':','0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
  776. foreach (var c in mac.ToCharArray()) {
  777. if (Array.IndexOf(validChars, c) == -1) return false;
  778. }
  779. if (mac.Length != 19) return false;
  780. string macNoneFrame = mac.Substring(1, mac.Length - 2);
  781. string[] macNoneFrameSplits = macNoneFrame.Split(':');
  782. if (macNoneFrameSplits.Length != 6) return false;
  783. foreach (var item in macNoneFrameSplits) {
  784. if (item.Length != 2) return false;
  785. foreach (var c in item.ToCharArray())
  786. if (Array.IndexOf(validChars, c) < 3) return false;
  787. }
  788. return true;
  789. }
  790. #region 2p蓝牙部分,使用了SmartBowSDK
  791. //2p蓝牙连接 使用 SmartBowSDK
  792. SmartBowHelper smartBowHelper2P;
  793. //陀螺仪校准进度
  794. public int smartBowHelper2_Progress { get => (int)(smartBowHelper2P.GetGyrProgress() * 100); }
  795. bool doConnect2P = false;
  796. bool userDoConnect2P = false;
  797. int _scanCanRetryCount2P = 4;
  798. bool canConnect2P = true;
  799. bool lerpForRotation2P = true;
  800. float lerpTimeRate2P = 7;
  801. private Quaternion newRotation2P = Quaternion.identity;
  802. //数据存储标识
  803. string userTags = "smartbow";
  804. int deviceId2 = 2;
  805. public void onCreateSmartBowHelper2P() {
  806. smartBowHelper2P = SmartBowHelper.NewInstance();
  807. smartBowHelper2P.OnBluetoothModuleInited += () =>
  808. {
  809. Debug.Log("OnBluetoothModuleInited");
  810. //判断是否是同一个mac
  811. //需要增加一个判断,判断是否对应的mac设备。不是需要进行重新连接
  812. string mac = smartBowHelper2P.GetMacAddress();
  813. if (!AimHandler.ins.aimDeviceInfo.bInitMac)
  814. {
  815. Debug.Log("smartBowHelper2P 设置设备mac:" + mac);
  816. AimHandler.ins.SetAimDeviceMac(mac);
  817. }
  818. else if (AimHandler.ins.aimDeviceInfo.mac != mac)
  819. {
  820. Debug.Log("设备不一样,断开连接");
  821. DoConnect2P();
  822. //延迟一点时间后重新触发扫描
  823. CallDelay(4, () =>
  824. {
  825. Debug.Log("CallDelay 重新连接");
  826. DoConnect2P();
  827. });
  828. return;
  829. }
  830. UpdateConnectText();
  831. smartBowHelper2P.StartRotationSensor();
  832. smartBowHelper2P.StartShootingSensor();
  833. //if (SB_EventSystem.ins)
  834. //{
  835. // //唤起/隐藏虚拟鼠标
  836. // SB_EventSystem.ins.AwakenSimulateMouse();
  837. //}
  838. };
  839. smartBowHelper2P.OnBluetoothError += (error, message) =>
  840. {
  841. Debug.Log("smartBowHelper2P error:" + error);
  842. if (error == BluetoothError.ScanNotFoundTargetDevice)
  843. {
  844. scanLock = false;
  845. PopupMgr.ins.ShowTip("连接失败,未发现目标设备!");
  846. if (_scanCanRetryCount2P > 0)
  847. {
  848. _scanCanRetryCount2P--;
  849. scanLock = true;
  850. ConnectSmartBowHelper2P();
  851. }
  852. else
  853. {
  854. userDoConnect2P = false;
  855. canConnect2P = true;
  856. Log("没有发现设备");
  857. TextAutoLanguage2.GetTextByKey("ble-dev-notfound");
  858. }
  859. return;
  860. }
  861. PopupMgr.ins.ShowTip(message);
  862. };
  863. smartBowHelper2P.OnBluetoothStatusChanged += (oldStatus, newStatus) =>
  864. {
  865. UpdateConnectText();
  866. };
  867. smartBowHelper2P.OnRotationUpdate += (r) =>
  868. {
  869. newRotation2P = r;
  870. //GameController.ins.aimCrossHairs[playerIndex].UpdatePositionByModuleRotation(r);
  871. //if (SB_EventSystem.ins && SB_EventSystem.ins.simulateMouseIsAwaked) SB_EventSystem.ins.MoveSimulateMouse(r);
  872. };
  873. smartBowHelper2P.OnShooting += OnShot2P;
  874. smartBowHelper2P.OnFunctionKeyPress += () =>
  875. {
  876. //如果是双人场景,触发提示
  877. if (UnityEngine.SceneManagement.SceneManager.GetActiveScene().name == "GameDouble")
  878. {
  879. if (GameObject.Find("AutoResetViewNewRight")) return;
  880. GameObject resetView = Instantiate(Resources.Load<GameObject>("AutoResetViewNew"));
  881. resetView.name = "AutoResetViewNewRight";
  882. AutoResetViewNew autoResetViewNewScript = resetView.GetComponent<AutoResetViewNew>();
  883. autoResetViewNewScript.setPosRight();
  884. autoResetViewNewScript.action_OnDestroy += () =>
  885. {
  886. smartBowHelper2P.ResetAim();
  887. };
  888. }
  889. else {
  890. smartBowHelper2P.ResetAim();
  891. }
  892. };
  893. #if UNITY_STANDALONE_WIN || UNITY_EDITOR
  894. //用户2window连接 BluetoothWindows.IsWindows() &&
  895. if ( currentBLEPlayer == BluetoothPlayer.SECONDE_PLAYER)
  896. {
  897. Debug.Log("SECONDE_PLAYER BleWinHelper.RegisterTo");
  898. BleWinHelper com = BleWinHelper.RegisterTo(smartBowHelper2P.gameObject, smartBowHelper2P.CreateBluetoothWindows(),"2P");
  899. }
  900. #endif
  901. }
  902. void OnShot2P(float speed)
  903. {
  904. if (GameController.ins.GetArmBowDoublePlayer(PlayerType.SecondPlayer) != null)
  905. {
  906. //本地双人模式下处理2P ,1P在 ShootCheck 类处理
  907. GameController.ins.GetArmBowDoublePlayer(PlayerType.SecondPlayer).ADS_fire(true, speed);
  908. }
  909. }
  910. void UpdateConnectText()
  911. {
  912. var newStatus = smartBowHelper2P.GetBluetoothStatus();
  913. if (newStatus == SmartBowSDK.BluetoothStatusEnum.None) {
  914. if (GameController.ins) {
  915. GameController.ins.GetBowCameraDoublePlayer(PlayerType.SecondPlayer).isTouchMode = true;
  916. }
  917. Debug.Log("<color=blue>未连接</color>(点击连接)");
  918. scanLock = false;
  919. if (_scanCanRetryCount2P > 0)
  920. {
  921. _scanCanRetryCount2P--;
  922. scanLock = true;
  923. ConnectSmartBowHelper2P();
  924. }
  925. else
  926. {
  927. userDoConnect2P = false;
  928. canConnect2P = true;
  929. Log("没有发现设备");
  930. PopupMgr.ins.ShowTip("连接失败,未发现目标设备!");
  931. TextAutoLanguage2.GetTextByKey("ble-dev-notfound");
  932. }
  933. }else if (newStatus == SmartBowSDK.BluetoothStatusEnum.Connecting) {
  934. Debug.Log("<color=#FF670D>连接中</color>");
  935. if (GameController.ins)
  936. {
  937. GameController.ins.GetBowCameraDoublePlayer(PlayerType.SecondPlayer).isTouchMode = false;
  938. }
  939. }else if (newStatus == SmartBowSDK.BluetoothStatusEnum.Connected)
  940. {
  941. if (GameController.ins) {
  942. GameController.ins.GetBowCameraDoublePlayer(PlayerType.SecondPlayer).isTouchMode = false;
  943. }
  944. if (smartBowHelper2P.IsBluetoothModuleInited()) Debug.Log("<color=green>已连接</color>(点击断开)");
  945. else Debug.Log("<color=green>已连接</color><color=blue>(正在初始化)</color>");
  946. }
  947. }
  948. public void ConnectSmartBowHelper2P() {
  949. //#if UNITY_ANDROID
  950. // PopupMgr.ins.ClearAllTip();
  951. // if (BluetoothHelperAndroid.IsBluetoothEnabled() == false)
  952. // {
  953. // HandleConnectException(TextAutoLanguage2.GetTextByKey("ble-exception1"));
  954. // return;
  955. // }
  956. // if (BluetoothHelperAndroid.RequestBluetoothPermissions(ConnectSmartBowHelper2P, (permission) => {
  957. // if (permission.Contains("LOCATION"))
  958. // {
  959. // HandleConnectException(TextAutoLanguage2.GetTextByKey("ble-exception2"));
  960. // }
  961. // else if (permission.Contains("BLUETOOTH"))
  962. // {
  963. // HandleConnectException(TextAutoLanguage2.GetTextByKey("ble-exception3"));
  964. // }
  965. // })) return;
  966. //#endif
  967. if (smartBowHelper2P == null)
  968. {
  969. onCreateSmartBowHelper2P();
  970. CallDelay(1, () =>
  971. {
  972. Debug.Log("Connect*********");
  973. smartBowHelper2P.Connect(userTags,deviceId2,true);//不在sdk 判断mac
  974. });
  975. }
  976. else {
  977. smartBowHelper2P.Connect(userTags, deviceId2,true);
  978. }
  979. }
  980. public void DoConnect2P()
  981. {
  982. Debug.Log("DoConnect2P");
  983. if (smartBowHelper2P == null || smartBowHelper2P.GetBluetoothStatus() == SmartBowSDK.BluetoothStatusEnum.None)
  984. {
  985. connectCanceled = false;
  986. userDoConnect2P = true;
  987. doConnect2P = true;;
  988. Connect2P();
  989. }
  990. else if (smartBowHelper2P.GetBluetoothStatus() == SmartBowSDK.BluetoothStatusEnum.Connected)
  991. {
  992. userDoConnect2P = false;
  993. doConnect2P = false;
  994. canConnect2P = true;
  995. DisconnectSmartBowHelper2P();
  996. }
  997. }
  998. void Connect2P()
  999. {
  1000. //if (BluetoothShoot.scanLock)
  1001. //{
  1002. // return;
  1003. //}
  1004. if (!canConnect2P)
  1005. {
  1006. return;
  1007. }
  1008. doConnect = false;
  1009. doConnect2P = false;
  1010. scanLock = true;
  1011. canConnect2P = false;
  1012. _scanCanRetryCount2P = 4;
  1013. //SetStatus2P(BluetoothStatusEnum.Connecting);
  1014. ConnectSmartBowHelper2P();
  1015. }
  1016. //初始化陀螺仪
  1017. public void OnCalibrateGyr2P()
  1018. {
  1019. if (smartBowHelper2P.IsGyrCalibrating()) smartBowHelper2P.StopGyrCalibration();
  1020. else smartBowHelper2P.StartGyrCalibration();
  1021. }
  1022. //初始化地磁计
  1023. public void OnCalibrateMag2P()
  1024. {
  1025. smartBowHelper2P.StartMagCalibration();
  1026. }
  1027. #endregion
  1028. #region 当前选择操作的设备 如1p或者2p
  1029. public SmartBowHelper getSmartBowHelper2P() {
  1030. return smartBowHelper2P;
  1031. }
  1032. public void setBLEPlayer(BluetoothPlayer blePlayer)
  1033. {
  1034. //切换蓝牙用户时候,判断是否正在连接,如果正在匹配连接的话,取消连接状态
  1035. if (blePlayer != currentBLEPlayer) {
  1036. Debug.Log("Set BluetoothPlayer status:" + status);
  1037. onCancelAllConnecting();
  1038. }
  1039. currentBLEPlayer = blePlayer;
  1040. Debug.Log("Set BluetoothPlayer:" + currentBLEPlayer);
  1041. }
  1042. public BluetoothPlayer getBLEPlayer()
  1043. {
  1044. //Debug.Log("Get BluetoothPlayer:" + currentBLEPlayer);
  1045. return currentBLEPlayer;
  1046. }
  1047. //更新跟随点位置
  1048. public void UpdateCameraToLookNewPoint2P() {
  1049. if (CameraToLookNew.ins != null)
  1050. {
  1051. Transform m_controlObj = CameraToLookNew.ins.transform;
  1052. if (lerpForRotation2P)
  1053. m_controlObj.localRotation = Quaternion.Lerp(m_controlObj.localRotation, newRotation2P, Time.deltaTime * lerpTimeRate2P);
  1054. else
  1055. m_controlObj.localRotation = newRotation2P;
  1056. }
  1057. }
  1058. public int get2PBattery() {
  1059. return smartBowHelper2P == null? 0 : smartBowHelper2P.GetBattery();
  1060. }
  1061. //主更新调用
  1062. void updateSmartBowHelper2P() {
  1063. UpdateCameraToLookNewPoint2P();
  1064. }
  1065. #endregion
  1066. //取消正在连接的连接
  1067. public void onCancelAllConnecting(BluetoothStatusEnum _bluetoothStatus = BluetoothStatusEnum.ConnectFail) {
  1068. // status != BluetoothStatusEnum.ConnectSuccess
  1069. Debug.LogWarning("onCancelAllConnecting 1:" + status);
  1070. #if UNITY_STANDALONE_WIN || UNITY_EDITOR
  1071. //BleUDP.ins != null
  1072. //BluetoothWindows.IsWindows() &&
  1073. if (status == BluetoothStatusEnum.Connecting)
  1074. {
  1075. //Debug.LogWarning("onCancelAllConnecting 2:" + status);
  1076. userDoConnect = false;
  1077. doConnect = false;
  1078. OnDisconnect();
  1079. // BleUDP.ins.Disconnect();
  1080. firstBluetoothWindows.Disconnect();
  1081. SetStatus(_bluetoothStatus);
  1082. Debug.LogWarning("onCancelAllConnecting 3:" + status);
  1083. }
  1084. #else
  1085. if (bluetoothHelper != null && status == BluetoothStatusEnum.Connecting)
  1086. {
  1087. Debug.LogWarning("onCancelAllConnecting 2:" + status);
  1088. userDoConnect = false;
  1089. doConnect = false;
  1090. OnDisconnect();
  1091. DisconnectBleHelper();
  1092. SetStatus(_bluetoothStatus);
  1093. }
  1094. #endif
  1095. //smartBowHelper2P.GetBluetoothStatus() != SmartBowSDK.BluetoothStatusEnum.Connected
  1096. if (smartBowHelper2P != null && smartBowHelper2P.GetBluetoothStatus() == SmartBowSDK.BluetoothStatusEnum.Connecting)
  1097. {
  1098. userDoConnect2P = false;
  1099. doConnect2P = false;
  1100. canConnect2P = true;
  1101. DisconnectSmartBowHelper2P();
  1102. //smartBowHelper2P.Disconnect();
  1103. Debug.Log("onCancelAllConnecting smartBowHelper2P 2:" + smartBowHelper2P.GetBluetoothStatus());
  1104. }
  1105. }
  1106. #region 判断是否是1p设备连接的是HOUYIPRO信息
  1107. public bool isMainConnectToHOUYIPRO() {
  1108. bool _isHOUYIPRO = false;
  1109. foreach (AimDeviceInfo p in AimHandler.ins.aimDeviceInfos.arry)
  1110. {
  1111. if ((int)BluetoothPlayer.FIRST_PLAYER == p.id && p.type == (int)AimDeviceType.HOUYIPRO)
  1112. {
  1113. _isHOUYIPRO = true;
  1114. }
  1115. }
  1116. if (_isHOUYIPRO)
  1117. {
  1118. //如果是。判断是否连接
  1119. return status == BluetoothStatusEnum.ConnectSuccess;
  1120. }
  1121. else {
  1122. return false;
  1123. }
  1124. }
  1125. #endregion
  1126. #region 判断是否是1p设备连接的是ARTEMISPRO信息
  1127. public bool isMainConnectToARTEMISPRO()
  1128. {
  1129. bool _isARTEMISPRO = false;
  1130. foreach (AimDeviceInfo p in AimHandler.ins.aimDeviceInfos.arry)
  1131. {
  1132. if ((int)BluetoothPlayer.FIRST_PLAYER == p.id && p.type == (int)AimDeviceType.ARTEMISPRO)
  1133. {
  1134. _isARTEMISPRO = true;
  1135. }
  1136. }
  1137. if (_isARTEMISPRO)
  1138. {
  1139. //如果是。判断是否连接
  1140. return status == BluetoothStatusEnum.ConnectSuccess;
  1141. }
  1142. else
  1143. {
  1144. return false;
  1145. }
  1146. }
  1147. #endregion
  1148. #region 判断是否是1p设备连接的是红外信息,有多种红外设备
  1149. public bool isMainConnectToInfraredDevice()
  1150. {
  1151. bool _isInfraredDevice = false;
  1152. foreach (AimDeviceInfo p in AimHandler.ins.aimDeviceInfos.arry)
  1153. {
  1154. if ((int)BluetoothPlayer.FIRST_PLAYER == p.id && (p.type == (int)AimDeviceType.ARTEMISPRO || p.type == (int)AimDeviceType.HOUYIPRO))
  1155. {
  1156. _isInfraredDevice = true;
  1157. }
  1158. }
  1159. if (_isInfraredDevice)
  1160. {
  1161. //如果是。判断是否连接
  1162. return status == BluetoothStatusEnum.ConnectSuccess;
  1163. }
  1164. else
  1165. {
  1166. return false;
  1167. }
  1168. }
  1169. #endregion
  1170. #region 判断是否是1p设备连接的是Gun信息
  1171. public bool isMainConnectToGun()
  1172. {
  1173. bool _isGun = false;
  1174. foreach (AimDeviceInfo p in AimHandler.ins.aimDeviceInfos.arry)
  1175. {
  1176. if ((int)BluetoothPlayer.FIRST_PLAYER == p.id && p.type == (int)AimDeviceType.Gun)
  1177. {
  1178. _isGun = true;
  1179. }
  1180. }
  1181. if (_isGun)
  1182. {
  1183. //如果是。判断是否连接
  1184. return status == BluetoothStatusEnum.ConnectSuccess;
  1185. }
  1186. else
  1187. {
  1188. return false;
  1189. }
  1190. }
  1191. #endregion
  1192. /// <summary>
  1193. /// 设置设备类型
  1194. /// </summary>
  1195. public void SetMainConnectDeviceType() {
  1196. //1号玩家连接蓝牙成功时候,设置一次 GlobalData.MyDeviceMode
  1197. foreach (AimDeviceInfo p in AimHandler.ins.aimDeviceInfos.arry)
  1198. {
  1199. if ((int)BluetoothPlayer.FIRST_PLAYER == p.id)
  1200. {
  1201. if (p.type == (int)AimDeviceType.Gun)
  1202. {
  1203. //设置枪
  1204. HomeView.ins.MyTopBarView.onChangeType(1);
  1205. }
  1206. else
  1207. {
  1208. //其余默认是弓箭
  1209. HomeView.ins.MyTopBarView.onChangeType(0);
  1210. }
  1211. }
  1212. }
  1213. }
  1214. #region 用户1 window ble 连接和部分共用代码
  1215. void OnConnected_windows1()
  1216. {
  1217. Log("[WinBle_1P]连接成功\n" + deviceName);
  1218. SetStatus(BluetoothStatusEnum.ConnectSuccess);
  1219. BowCamera.isTouchMode = false;
  1220. if (CommonConfig.EnableDecryption && NeedDecryption)
  1221. {
  1222. // 这里验证指令,开始请求授权
  1223. // 启动轮询协程
  1224. StartCoroutine(PollingCoroutine());
  1225. }
  1226. else
  1227. {
  1228. //除了pc,Android 直接连接
  1229. InitWhenConenct();
  1230. }
  1231. }
  1232. void OnConnectionFailed_windows1()
  1233. {
  1234. Log("连接失败\n" + deviceName);
  1235. OnDisconnect();
  1236. }
  1237. void OnCharacteristicChanged_windows1(string deviceId,byte[] value)
  1238. {
  1239. OnCharacteristicChanged(null, value, null);
  1240. }
  1241. void OnCharacteristicChanged(BluetoothHelper helper, byte[] value, BluetoothHelperCharacteristic characteristic) {
  1242. if (status != BluetoothStatusEnum.ConnectSuccess) return;
  1243. if (!hasData)
  1244. {
  1245. hasData = true;
  1246. hasDataTime = JCUnityLib.TimeUtils.GetTimestamp();
  1247. }
  1248. if (CommonConfig.EnableDecryption && NeedDecryption)
  1249. {
  1250. //Pc 版本先走校验流程
  1251. if (!BluetoothDecryptor.AUTHOR_IsDecrypt())
  1252. {
  1253. if (value[0] == 0x5a)
  1254. {
  1255. // 从硬件读取数据
  1256. if (value != null && value.Length > 0)
  1257. {
  1258. Debug.Log("接收到数据:" + BitConverter.ToString(value));
  1259. BluetoothDecryptor.AUTHOR_Decrypt(value);
  1260. if (BluetoothDecryptor.AUTHOR_IsDecrypt())
  1261. {
  1262. Debug.Log("解密成功!");
  1263. //解密成功后
  1264. StopEncrypt();
  1265. //开始连接其他信息
  1266. InitWhenConenct();
  1267. }
  1268. else
  1269. {
  1270. Debug.Log("解密失败!");
  1271. //SideTipView.ShowTip("设备通信失败,断开连接", Color.yellow);
  1272. //断开连接等操作
  1273. if (PollingCoroutineCount <= 0)
  1274. {
  1275. StopEncrypt();
  1276. DoConnect();
  1277. }
  1278. }
  1279. }
  1280. }
  1281. return;
  1282. }
  1283. }
  1284. dataCount++;
  1285. if (curMac == null && dataCount < 500)
  1286. {
  1287. UploadMacAddress(value);
  1288. }
  1289. byte[] bytes = value;
  1290. // Log(String.Join(",", bytes));
  1291. BluetoothClient.UploadData(0, bytes);
  1292. if (AimHandler.ins)
  1293. {
  1294. AimHandler.ins.OnDataReceived(bytes);
  1295. }
  1296. }
  1297. #endregion
  1298. }