BluetoothAim.cs 45 KB

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