BluetoothAim.cs 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140
  1. using System;
  2. using UnityEngine;
  3. using System.Collections.Generic;
  4. using UnityEngine.UI;
  5. using DG.Tweening;
  6. using SmartBowSDK;
  7. using System.Collections;
  8. using UnityEngine.SceneManagement;
  9. using SmartBowSDK.CMD;
  10. using AppUI.Manager.View;
  11. using AppUI.View.Home.Main;
  12. using UHomeView = AppUI.View.Home.Main.HomeView;
  13. using SdkAimDeviceInfo = SmartBowSDK.AimDeviceInfo;
  14. namespace AppUI.Bluetooth
  15. {
  16. /* 蓝牙瞄准模块(AppUI) */
  17. /* 1P/2P 连接与 CompanionDeviceManager(CMD)统一经 SmartBowHelper → SDK,AppUI 不维护 CMDManager */
  18. public class BluetoothAim : MonoBehaviour
  19. {
  20. #region 2p蓝牙使用的是sdk,所以需要另外定义
  21. //2p时候过滤的名字
  22. readonly string targetDeviceName2P = "Bbow_20210501 | HOUYI Pro | Pistol | Pistol M9 | ARTEMIS Pro | Pistol M17 | Rifle M416";
  23. #endregion
  24. #region 弓箭蓝牙模块基本信息
  25. readonly string targetDeviceNameAxis = "Bbow_20210501 | ARTEMIS | HOUYI | HOUYI Pro | ARTEMIS Pro";
  26. readonly string targetDeviceName = "Bbow_20210501 | ARTEMIS Pro";//HOUYI Pro
  27. readonly string targetDeviceNameARTEMISPro = "ARTEMIS Pro | Bbow_20210501";
  28. readonly string targetDeviceNameHOUYIPro = "HOUYI Pro";
  29. readonly string targetDeviceNameGun = "Pistol | Pistol M9 | Bbow_20210501";
  30. readonly string targetDeviceNameGun_M17 = "Pistol M17";
  31. readonly string targetDeviceNameGun_M416 = "Rifle M416";
  32. #endregion
  33. //当前选择的设备
  34. BluetoothPlayer currentBLEPlayer = BluetoothPlayer.FIRST_PLAYER;
  35. #region 1p蓝牙使用的是sdk
  36. //1p蓝牙连接 使用 SmartBowSDK
  37. SmartBowHelper smartBowHelper1P;
  38. string userTags1P = "smartbow";
  39. int deviceId1P = 1;
  40. int _scanCanRetryCount1P = 4;
  41. #endregion
  42. string deviceName = "";
  43. bool canConnect = true;
  44. [SerializeField] Text textUI;
  45. public BluetoothStatusEnum status = BluetoothStatusEnum.Connect;
  46. public bool hasData = false;
  47. public long hasDataTime;
  48. public static bool scanLock = false; //防止同时扫描冲突
  49. //根据设备情况来看是否需要解密,目前就是枪需要进行解密操作
  50. public bool NeedDecryption = false;
  51. AimHandler DeviceAim => SmartBowDeviceHub.ins?.Aim;
  52. //首页初始化时候调用一次连接
  53. public bool bStartConnect = false;
  54. bool _suppressHomeAutoConnect;
  55. /// <summary>DeviceView 手动选型/侧滑连接期间为 true,跳过 HomeView 延迟自动连接。</summary>
  56. public void SetSuppressHomeAutoConnect(bool suppress) => _suppressHomeAutoConnect = suppress;
  57. public bool IsHomeAutoConnectSuppressed => _suppressHomeAutoConnect;
  58. public static void Init() => SmartBowDeviceHub.EnsureReady();
  59. private void Awake()
  60. {
  61. #if UNITY_ANDROID
  62. if (CommonConfig.bUseCMD)
  63. SmartBowLogger.isDebug = true;
  64. #endif
  65. }
  66. void OnDestroy()
  67. {
  68. //删除ble。1p,2p 都删除
  69. DisconnectSmartBowHelper1P();
  70. DisconnectSmartBowHelper2P();
  71. }
  72. /// <summary>
  73. /// 首页初始化的时候,如果是第一次。尝试连接蓝牙。只进行一次
  74. /// </summary>
  75. public void HomeViewConnectBLE()
  76. {
  77. if (!UserPlayer.IsLoginReadyForHomeBle())
  78. {
  79. Debug.Log("[初始化自动连接蓝牙] 登录未完成或 AuthLoginMask 显示中,跳过 Home 自动连接");
  80. return;
  81. }
  82. if (_suppressHomeAutoConnect)
  83. {
  84. Debug.Log("[初始化自动连接蓝牙] DeviceView 手动连接中,跳过 Home 自动连接");
  85. return;
  86. }
  87. if (bStartConnect) return;
  88. if (DeviceAim == null) return;
  89. bStartConnect = true;
  90. //当已经连接过一把弓(1P)时,下一次打开 APP,1P 就自动处于连接的状态;用户只要打1.开 APP 和打开模块就可以自动连接,减少连接设备的操作。
  91. Debug.Log("[初始化自动连接蓝牙] 自动开始连接上一次连接的设备 1P?");
  92. DeviceAim.OnGetAimDeviceInfos();
  93. if (DeviceAim.GetAimDeviceInfo(BluetoothPlayer.FIRST_PLAYER) != null)
  94. {
  95. //如果需要连接
  96. if (status != BluetoothStatusEnum.ConnectSuccess)
  97. {
  98. //setBLEPlayer(BluetoothPlayer.FIRST_PLAYER);
  99. Debug.Log("[初始化自动连接蓝牙] 当前选择的操作用户:" + getBLEPlayer());
  100. //DeviceAim.SetAimDeviceSelectIndex(0);
  101. //第一次进入从存储的资料获取 aimDeviceInfo
  102. DeviceAim.onCreateAimDeviceInfoById();
  103. DoConnect();
  104. }
  105. }
  106. }
  107. private bool userDoConnect = false;
  108. private bool doConnect = false;
  109. public Func<bool> action_DoConnectInterceptor;
  110. public void DoConnect()
  111. {
  112. if (action_DoConnectInterceptor != null)
  113. {
  114. if (action_DoConnectInterceptor.Invoke()) return;
  115. }
  116. if (status == BluetoothStatusEnum.Connect)
  117. {
  118. connectCanceled = false;
  119. userDoConnect = true;
  120. doConnect = true;
  121. SetStatus(BluetoothStatusEnum.Connecting);
  122. }
  123. else if (status == BluetoothStatusEnum.ConnectSuccess)
  124. {
  125. userDoConnect = false;
  126. doConnect = false;
  127. OnDisconnect();
  128. DisconnectSmartBowHelper1P();
  129. //#if UNITY_STANDALONE_WIN || UNITY_EDITOR
  130. // //BleUDP.ins.Disconnect();
  131. // if (firstBluetoothWindows.Disconnect()) SetStatus(BluetoothStatusEnum.Connect);
  132. //#else
  133. // DisconnectBleHelper();
  134. //#endif
  135. }
  136. }
  137. //连接取消,退回登录时需要取消连接(扫描)
  138. [NonSerialized] public bool connectCanceled = false;
  139. void OnDisconnect()
  140. {
  141. curMac = null;
  142. hasData = false;
  143. canConnect = true;
  144. SetStatus(BluetoothStatusEnum.ConnectFail);
  145. BowCamera.isTouchMode = true;
  146. if (DeviceAim != null) DeviceAim.SetMsOldDefault();
  147. DisconnectSmartBowHelper1P();
  148. }
  149. void Update()
  150. {
  151. updateSmartBowHelper2P();
  152. if (userDoConnect && status == BluetoothStatusEnum.Connect)
  153. {
  154. DoConnect();
  155. }
  156. if (doConnect) Connect();
  157. }
  158. void SetStatus(BluetoothStatusEnum statusValue)
  159. {
  160. status = statusValue;
  161. if (status == BluetoothStatusEnum.ConnectFail)
  162. {
  163. Sequence sequence = DOTween.Sequence();
  164. sequence.AppendInterval(2f);
  165. sequence.AppendCallback(delegate ()
  166. {
  167. if (status == BluetoothStatusEnum.ConnectFail)
  168. {
  169. status = BluetoothStatusEnum.Connect;
  170. }
  171. });
  172. sequence.SetUpdate(true);
  173. SimulateMouseController.ins?.SetBleConnected(false);
  174. }
  175. else if (status == BluetoothStatusEnum.ConnectSuccess)
  176. {
  177. SimulateMouseController.ins?.SetBleConnected(true);
  178. }
  179. SmartBowDeviceHub.ins?.NotifyStateChanged();
  180. }
  181. void DisconnectSmartBowHelper1P()
  182. {
  183. DeviceAim?.UnbindSdk1P();
  184. if (smartBowHelper1P != null) smartBowHelper1P.Disconnect();
  185. }
  186. void DisconnectSmartBowHelper2P()
  187. {
  188. //2p
  189. if (smartBowHelper2P != null) smartBowHelper2P.Disconnect();
  190. }
  191. void Connect()
  192. {
  193. //if (BluetoothShoot.scanLock)
  194. //{
  195. // return;
  196. //}
  197. if (!canConnect)
  198. {
  199. return;
  200. }
  201. doConnect = false;
  202. doConnect2P = false;
  203. scanLock = true;
  204. canConnect = false;
  205. _scanCanRetryCount1P = 4;
  206. SetStatus(BluetoothStatusEnum.Connecting);
  207. ConnectSmartBowHelper1P();
  208. }
  209. #region 1p蓝牙部分,使用了SmartBowSDK
  210. string Get1PDeviceFilterNames()
  211. {
  212. int firstPlayerType = DeviceAim.GetDeviceType(BluetoothPlayer.FIRST_PLAYER);
  213. if (firstPlayerType == (int)AimDeviceType.HOUYIPRO)
  214. return targetDeviceNameHOUYIPro;
  215. if (firstPlayerType == (int)AimDeviceType.ARTEMISPRO)
  216. return targetDeviceNameARTEMISPro;
  217. if (firstPlayerType == (int)AimDeviceType.Gun)
  218. return targetDeviceNameGun;
  219. if (firstPlayerType == (int)AimDeviceType.PistolM17)
  220. return targetDeviceNameGun_M17;
  221. if (firstPlayerType == (int)AimDeviceType.RifleM416)
  222. return targetDeviceNameGun_M416;
  223. return targetDeviceNameAxis;
  224. }
  225. /// <summary>CompanionDeviceManager 扫描用:把 "A | B" 转为 (A|B) 正则。</summary>
  226. string ToRegex(string names)
  227. {
  228. if (string.IsNullOrEmpty(names))
  229. return "";
  230. var parts = names.Split('|');
  231. for (int i = 0; i < parts.Length; i++)
  232. parts[i] = parts[i].Trim();
  233. return "(" + string.Join("|", parts) + ")";
  234. }
  235. void Apply1PDeviceFilters()
  236. {
  237. string filterNames = Get1PDeviceFilterNames();
  238. SdkAimDeviceInfo firstPlayer = DeviceAim.GetAimDeviceInfo(BluetoothPlayer.FIRST_PLAYER);
  239. if (firstPlayer == null)
  240. {
  241. smartBowHelper1P.SetIsConnectName(true);
  242. smartBowHelper1P.SetConnectMacStr("");
  243. if (smartBowHelper1P.GetUseCompanionDeviceManagerStatus())
  244. smartBowHelper1P.SetFilters(ToRegex(filterNames));
  245. else
  246. smartBowHelper1P.SetFilters(filterNames);
  247. return;
  248. }
  249. if (firstPlayer.bInitMac)
  250. {
  251. smartBowHelper1P.SetIsConnectName(false);
  252. smartBowHelper1P.SetConnectMacStr(firstPlayer.mac);
  253. smartBowHelper1P.SetFilters("");
  254. }
  255. else
  256. {
  257. smartBowHelper1P.SetIsConnectName(true);
  258. smartBowHelper1P.SetConnectMacStr("");
  259. if (smartBowHelper1P.GetUseCompanionDeviceManagerStatus())
  260. smartBowHelper1P.SetFilters(ToRegex(filterNames));
  261. else
  262. smartBowHelper1P.SetFilters(filterNames);
  263. }
  264. }
  265. public void onCreateSmartBowHelper1P()
  266. {
  267. smartBowHelper1P = SmartBowHelper.NewInstance();
  268. #if UNITY_ANDROID
  269. if (CommonConfig.bUseCMD)
  270. {
  271. smartBowHelper1P.UseCompanionDeviceManager(true);
  272. }
  273. #endif
  274. Apply1PDeviceFilters();
  275. smartBowHelper1P.OnBluetoothModuleInited += () =>
  276. {
  277. scanLock = false;
  278. canConnect = true;
  279. userDoConnect = false;
  280. doConnect = false;
  281. if (connectCanceled)
  282. {
  283. Debug.Log("ble connectCanceled");
  284. DoConnect();
  285. return;
  286. }
  287. string mac = smartBowHelper1P.GetMacAddress();
  288. SdkAimDeviceInfo firstPlayer = DeviceAim.GetAimDeviceInfo(BluetoothPlayer.FIRST_PLAYER);
  289. if (firstPlayer != null && !firstPlayer.bInitMac)
  290. {
  291. Debug.Log("smartBowHelper1P 设置设备mac:" + mac);
  292. DeviceAim.SetAimDeviceMac(mac);
  293. }
  294. else if (firstPlayer != null && !string.IsNullOrEmpty(mac) && firstPlayer.mac != mac)
  295. {
  296. Debug.Log("设备不一样,断开连接");
  297. DoConnect();
  298. CallDelay(4, () =>
  299. {
  300. Debug.Log("CallDelay 重新连接");
  301. DoConnect();
  302. });
  303. return;
  304. }
  305. //if (!string.IsNullOrEmpty(mac))
  306. //{
  307. // curMac = mac;
  308. // LoginMgr.myUserInfo.mac = mac;
  309. // UserComp.Instance.saveMac();
  310. //}
  311. BowCamera.isTouchMode = false;
  312. hasData = true;
  313. hasDataTime = JCUnityLib.TimeUtils.GetTimestamp();
  314. smartBowHelper1P.StartRotationSensor();
  315. smartBowHelper1P.StartShootingSensor();
  316. SetMainConnectDeviceType();
  317. };
  318. smartBowHelper1P.OnCMDState += (state, message) =>
  319. {
  320. userDoConnect = false;
  321. doConnect = false;
  322. canConnect = true;
  323. scanLock = false;
  324. DisconnectSmartBowHelper1P();
  325. PopupMgr.ins.ShowTip(message);
  326. SetStatus(BluetoothStatusEnum.ConnectFail);
  327. };
  328. smartBowHelper1P.OnBluetoothError += (error, message) =>
  329. {
  330. Debug.Log("smartBowHelper1P error:" + error+ ",message:"+ message);
  331. if (error == BluetoothError.ScanNotFoundTargetDevice)
  332. {
  333. scanLock = false;
  334. //PopupMgr.ins.ShowTip("连接失败,未发现目标设备!");
  335. if (_scanCanRetryCount1P > 0)
  336. {
  337. _scanCanRetryCount1P--;
  338. scanLock = true;
  339. ConnectSmartBowHelper1P();
  340. }
  341. else
  342. {
  343. userDoConnect = false;
  344. canConnect = true;
  345. Log("没有发现设备");
  346. SetStatus(BluetoothStatusEnum.ConnectFail);
  347. }
  348. return;
  349. }
  350. //PopupMgr.ins.ShowTip(message);
  351. };
  352. smartBowHelper1P.OnBluetoothStatusChanged += (oldStatus, newStatus) =>
  353. {
  354. Sync1PStatusFromSDK(newStatus);
  355. SmartBowDeviceHub.ins?.NotifyStateChanged();
  356. };
  357. smartBowHelper1P.OnDeviceAndSystemInfoEvent += (connectPlatform, bleDeviceType) =>
  358. InvokeOnDeviceAndSystemInfoEvent(connectPlatform, bleDeviceType);
  359. DeviceAim?.BindSdk1P(smartBowHelper1P);
  360. SmartBowDeviceHub.ins?.RegisterHelper1P(smartBowHelper1P);
  361. }
  362. void Sync1PStatusFromSDK(SmartBowSDK.BluetoothStatusEnum newStatus)
  363. {
  364. if (newStatus == SmartBowSDK.BluetoothStatusEnum.None)
  365. {
  366. if (status == BluetoothStatusEnum.Connecting || status == BluetoothStatusEnum.ConnectSuccess)
  367. SetStatus(BluetoothStatusEnum.Connect);
  368. }
  369. else if (newStatus == SmartBowSDK.BluetoothStatusEnum.Connecting)
  370. {
  371. SetStatus(BluetoothStatusEnum.Connecting);
  372. }
  373. else if (newStatus == SmartBowSDK.BluetoothStatusEnum.Connected)
  374. {
  375. SetStatus(BluetoothStatusEnum.ConnectSuccess);
  376. }
  377. }
  378. public void ConnectSmartBowHelper1P()
  379. {
  380. if (smartBowHelper1P == null)
  381. {
  382. onCreateSmartBowHelper1P();
  383. CallDelay(0.2f, () =>
  384. {
  385. Apply1PDeviceFilters();
  386. smartBowHelper1P.Connect(userTags1P, deviceId1P, false);
  387. });
  388. }
  389. else
  390. {
  391. // 断开时 UnbindSdk1P,复用 helper 重连须重新订阅 rotation/shoot 等事件
  392. DeviceAim?.BindSdk1P(smartBowHelper1P);
  393. SmartBowDeviceHub.ins?.RegisterHelper1P(smartBowHelper1P);
  394. Apply1PDeviceFilters();
  395. smartBowHelper1P.Connect(userTags1P, deviceId1P, false);
  396. }
  397. }
  398. public SmartBowHelper getSmartBowHelper1P()
  399. {
  400. return smartBowHelper1P;
  401. }
  402. #endregion
  403. void HandleConnectException(string errorText)
  404. {
  405. scanLock = false;
  406. canConnect = true;
  407. // SetStatus(BluetoothStatusEnum.ConnectFail);
  408. status = BluetoothStatusEnum.Connect;
  409. userDoConnect = false;
  410. PopupMgr.ins.ShowTip(errorText);
  411. }
  412. void CallDelay(float delayTime, TweenCallback callback)
  413. {
  414. Sequence sequence = DOTween.Sequence();
  415. sequence.PrependInterval(delayTime).AppendCallback(callback);
  416. sequence.SetUpdate(true);
  417. }
  418. void Log(string text)
  419. {
  420. if (textUI)
  421. {
  422. textUI.text = text;
  423. }
  424. Debug.Log(string.Format("[{0}]{1}", typeof(BluetoothAim).Name, text));
  425. }
  426. [NonSerialized] public string curMac;
  427. #region 2p蓝牙部分,使用了SmartBowSDK
  428. //2p蓝牙连接 使用 SmartBowSDK
  429. SmartBowHelper smartBowHelper2P;
  430. //陀螺仪校准进度
  431. public int smartBowHelper2_Progress { get => (int)(smartBowHelper2P.GetGyrProgress() * 100); }
  432. bool doConnect2P = false;
  433. bool userDoConnect2P = false;
  434. int _scanCanRetryCount2P = 4;
  435. bool canConnect2P = true;
  436. public bool bNoNeedToReconnect { get; set; } = true;//是否需要重连
  437. bool lerpForRotation2P = true;
  438. float lerpTimeRate2P = 7;
  439. private Quaternion newRotation2P = Quaternion.identity;
  440. //数据存储标识
  441. string userTags = "smartbow";
  442. int deviceId2 = 2;
  443. public void onCreateSmartBowHelper2P()
  444. {
  445. smartBowHelper2P = SmartBowHelper.NewInstance();
  446. #if UNITY_ANDROID
  447. if (CommonConfig.bUseCMD)
  448. {
  449. //使用CMD API连接,这个只支持Android
  450. smartBowHelper2P.UseCompanionDeviceManager(true);
  451. }
  452. #endif
  453. if (smartBowHelper2P.GetUseCompanionDeviceManagerStatus())
  454. smartBowHelper2P.SetFilters(ToRegex(targetDeviceName2P));
  455. else
  456. smartBowHelper2P.SetFilters(targetDeviceName2P);
  457. smartBowHelper2P.OnBluetoothModuleInited += () =>
  458. {
  459. Debug.Log("OnBluetoothModuleInited");
  460. //判断是否是同一个mac
  461. //需要增加一个判断,判断是否对应的mac设备。不是需要进行重新连接
  462. string mac = smartBowHelper2P.GetMacAddress();
  463. SdkAimDeviceInfo secondPlayer = DeviceAim.GetAimDeviceInfo(BluetoothPlayer.SECOND_PLAYER);
  464. if (secondPlayer != null && !secondPlayer.bInitMac)
  465. {
  466. Debug.Log("smartBowHelper2P 设置设备mac:" + mac);
  467. DeviceAim.SetAimDeviceMac(mac);
  468. }
  469. else if (secondPlayer != null && secondPlayer.mac != mac)
  470. {
  471. Debug.Log("设备不一样,断开连接");
  472. DoConnect2P();
  473. //延迟一点时间后重新触发扫描
  474. CallDelay(4, () =>
  475. {
  476. Debug.Log("CallDelay 重新连接");
  477. DoConnect2P();
  478. });
  479. return;
  480. }
  481. UpdateConnectText();
  482. smartBowHelper2P.StartRotationSensor();
  483. smartBowHelper2P.StartShootingSensor();
  484. //if (SB_EventSystem.ins)
  485. //{
  486. // //唤起/隐藏虚拟鼠标
  487. // SB_EventSystem.ins.AwakenSimulateMouse();
  488. //}
  489. };
  490. smartBowHelper2P.OnCMDState += (state, message) =>
  491. {
  492. userDoConnect2P = false;
  493. doConnect2P = false;
  494. canConnect2P = true;
  495. DisconnectSmartBowHelper2P();
  496. PopupMgr.ins.ShowTip(message);
  497. };
  498. smartBowHelper2P.OnBluetoothError += (error, message) =>
  499. {
  500. Debug.Log("smartBowHelper2P error:" + error + ",message:" + message);
  501. if (error == BluetoothError.ScanNotFoundTargetDevice)
  502. {
  503. scanLock = false;
  504. //PopupMgr.ins.ShowTip("连接失败,未发现目标设备!");
  505. if (_scanCanRetryCount2P > 0)
  506. {
  507. _scanCanRetryCount2P--;
  508. scanLock = true;
  509. ConnectSmartBowHelper2P();
  510. }
  511. else
  512. {
  513. userDoConnect2P = false;
  514. canConnect2P = true;
  515. Log("没有发现设备");
  516. }
  517. return;
  518. }
  519. //PopupMgr.ins.ShowTip(message);
  520. };
  521. smartBowHelper2P.OnBluetoothStatusChanged += (oldStatus, newStatus) =>
  522. {
  523. UpdateConnectText();
  524. SmartBowDeviceHub.ins?.NotifyStateChanged();
  525. };
  526. smartBowHelper2P.OnRotationUpdate += (r) =>
  527. {
  528. newRotation2P = r;
  529. //GameController.ins.aimCrossHairs[playerIndex].UpdatePositionByModuleRotation(r);
  530. //if (SB_EventSystem.ins && SB_EventSystem.ins.simulateMouseIsAwaked) SB_EventSystem.ins.MoveSimulateMouse(r);
  531. };
  532. smartBowHelper2P.OnShooting += DeviceAim.OnShot2P;
  533. smartBowHelper2P.OnFunctionKeyPress += () =>
  534. {
  535. //如果是双人场景,触发提示
  536. if (SceneManager.GetActiveScene().name == "GameDouble")
  537. {
  538. if (GameObject.Find("AutoResetViewNewRight")) return;
  539. GameObject resetView = Instantiate(Resources.Load<GameObject>("AutoResetViewNew"));
  540. resetView.name = "AutoResetViewNewRight";
  541. AutoResetViewNew autoResetViewNewScript = resetView.GetComponent<AutoResetViewNew>();
  542. autoResetViewNewScript.setTextKey("new-user-guider_tip_视角归位-瞄准-infraredD");
  543. autoResetViewNewScript.setPosRight();
  544. autoResetViewNewScript.action_OnDestroy += () =>
  545. {
  546. smartBowHelper2P.ResetAim();
  547. };
  548. }
  549. else if (SceneManager.GetActiveScene().name == "InfraredGameDouble" || SceneManager.GetActiveScene().name == "WildAttackDouble")
  550. {
  551. if (GameObject.Find("AutoResetViewNewRight")) return;
  552. GameObject resetView = Instantiate(Resources.Load<GameObject>("AutoResetViewNew"));
  553. resetView.name = "AutoResetViewNewRight";
  554. AutoResetViewNew autoResetViewNewScript = resetView.GetComponent<AutoResetViewNew>();
  555. autoResetViewNewScript.setTextKey("new-user-guider_tip_视角归位-瞄准-infraredD");
  556. autoResetViewNewScript.setPosRight();
  557. autoResetViewNewScript.action_OnDestroy += () =>
  558. {
  559. if (SceneManager.GetActiveScene().name == "InfraredGameDouble")
  560. {
  561. InfraredDemo._ins?.SetAdjustPointsOffset(PlayerType.SecondPlayer);
  562. }
  563. else if (SceneManager.GetActiveScene().name == "WildAttackDouble")
  564. {
  565. WildAttack.GameMananger.GetInstance().ResetAim(WildAttack.PlayerTypeEnum.Second);
  566. }
  567. };
  568. }
  569. //else if (SceneManager.GetActiveScene().name.Equals("WildAttackDouble"))
  570. //{
  571. // //双人场景直接校准2P
  572. // WildAttack.GameMananger.GetInstance().ResetAim(WildAttack.PlayerTypeEnum.Second);
  573. //}
  574. else
  575. {
  576. smartBowHelper2P.ResetAim();
  577. }
  578. };
  579. //#if UNITY_STANDALONE_WIN || UNITY_EDITOR
  580. // //用户2window连接 BluetoothWindows.IsWindows() &&
  581. // if (currentBLEPlayer == BluetoothPlayer.SECONDE_PLAYER)
  582. // {
  583. // Debug.Log("SECONDE_PLAYER BleWinHelper.RegisterTo");
  584. // BleWinHelper com = BleWinHelper.RegisterTo(smartBowHelper2P.gameObject, smartBowHelper2P.CreateBluetoothWindows(), "2P");
  585. // }
  586. //#endif
  587. SmartBowDeviceHub.ins?.RegisterHelper2P(smartBowHelper2P);
  588. }
  589. void UpdateConnectText()
  590. {
  591. var newStatus = smartBowHelper2P.GetBluetoothStatus();
  592. if (newStatus == SmartBowSDK.BluetoothStatusEnum.None)
  593. {
  594. if (GameController.ins)
  595. {
  596. GameController.ins.GetBowCameraDoublePlayer(PlayerType.SecondPlayer).isTouchMode = true;
  597. }
  598. Debug.Log("<color=blue>未连接</color>(点击连接)");
  599. if (!bNoNeedToReconnect) return;
  600. scanLock = false;
  601. if (_scanCanRetryCount2P > 0)
  602. {
  603. _scanCanRetryCount2P--;
  604. scanLock = true;
  605. ConnectSmartBowHelper2P();
  606. }
  607. else
  608. {
  609. userDoConnect2P = false;
  610. canConnect2P = true;
  611. Log("没有发现设备");
  612. //PopupMgr.ins.ShowTip("连接失败,未发现目标设备!");
  613. }
  614. }
  615. else if (newStatus == SmartBowSDK.BluetoothStatusEnum.Connecting)
  616. {
  617. Debug.Log("<color=#FF670D>连接中</color>");
  618. if (GameController.ins)
  619. {
  620. GameController.ins.GetBowCameraDoublePlayer(PlayerType.SecondPlayer).isTouchMode = false;
  621. }
  622. }
  623. else if (newStatus == SmartBowSDK.BluetoothStatusEnum.Connected)
  624. {
  625. if (GameController.ins)
  626. {
  627. GameController.ins.GetBowCameraDoublePlayer(PlayerType.SecondPlayer).isTouchMode = false;
  628. }
  629. if (smartBowHelper2P.IsBluetoothModuleInited()) Debug.Log("<color=green>已连接</color>(点击断开)");
  630. else Debug.Log("<color=green>已连接</color><color=blue>(正在初始化)</color>");
  631. }
  632. }
  633. public void ConnectSmartBowHelper2P()
  634. {
  635. //#if UNITY_ANDROID
  636. // PopupMgr.ins.ClearAllTip();
  637. // if (BluetoothHelperAndroid.IsBluetoothEnabled() == false)
  638. // {
  639. // HandleConnectException(TextAutoLanguage2.GetTextByKey("ble-exception1"));
  640. // return;
  641. // }
  642. // if (BluetoothHelperAndroid.RequestBluetoothPermissions(ConnectSmartBowHelper2P, (permission) => {
  643. // if (permission.Contains("LOCATION"))
  644. // {
  645. // HandleConnectException(TextAutoLanguage2.GetTextByKey("ble-exception2"));
  646. // }
  647. // else if (permission.Contains("BLUETOOTH"))
  648. // {
  649. // HandleConnectException(TextAutoLanguage2.GetTextByKey("ble-exception3"));
  650. // }
  651. // })) return;
  652. //#endif
  653. if (smartBowHelper2P == null)
  654. {
  655. onCreateSmartBowHelper2P();
  656. CallDelay(1, () =>
  657. {
  658. smartBowHelper2P.Connect(userTags, deviceId2, true);//不在sdk 判断mac
  659. });
  660. }
  661. else
  662. {
  663. smartBowHelper2P.Connect(userTags, deviceId2, true);
  664. }
  665. }
  666. public void DoConnect2P()
  667. {
  668. Debug.Log("DoConnect2P");
  669. if (smartBowHelper2P == null || smartBowHelper2P.GetBluetoothStatus() == SmartBowSDK.BluetoothStatusEnum.None)
  670. {
  671. //connectCanceled = false;
  672. userDoConnect2P = true;
  673. doConnect2P = true;
  674. bNoNeedToReconnect = true;
  675. Connect2P();
  676. }
  677. else if (smartBowHelper2P.GetBluetoothStatus() == SmartBowSDK.BluetoothStatusEnum.Connected)
  678. {
  679. userDoConnect2P = false;
  680. doConnect2P = false;
  681. canConnect2P = true;
  682. DisconnectSmartBowHelper2P();
  683. }
  684. }
  685. void Connect2P()
  686. {
  687. //if (BluetoothShoot.scanLock)
  688. //{
  689. // return;
  690. //}
  691. if (!canConnect2P)
  692. {
  693. return;
  694. }
  695. doConnect = false;
  696. doConnect2P = false;
  697. scanLock = true;
  698. canConnect2P = false;
  699. _scanCanRetryCount2P = 4;
  700. //SetStatus2P(BluetoothStatusEnum.Connecting);
  701. ConnectSmartBowHelper2P();
  702. }
  703. //初始化陀螺仪
  704. public void OnCalibrateGyr2P()
  705. {
  706. if (smartBowHelper2P.IsGyrCalibrating()) smartBowHelper2P.StopGyrCalibration();
  707. else smartBowHelper2P.StartGyrCalibration();
  708. }
  709. //初始化地磁计
  710. public void OnCalibrateMag2P()
  711. {
  712. smartBowHelper2P.StartMagCalibration();
  713. }
  714. #endregion
  715. #region 当前选择操作的设备 如1p或者2p
  716. public SmartBowHelper getSmartBowHelper2P()
  717. {
  718. return smartBowHelper2P;
  719. }
  720. public void setBLEPlayer(BluetoothPlayer blePlayer)
  721. {
  722. //切换蓝牙用户时候,判断是否正在连接,如果正在匹配连接的话,取消连接状态
  723. if (blePlayer != currentBLEPlayer)
  724. {
  725. Debug.Log("Set BluetoothPlayer status:" + status);
  726. onCancelAllConnecting();
  727. }
  728. currentBLEPlayer = blePlayer;
  729. Debug.Log("Set BluetoothPlayer:" + currentBLEPlayer);
  730. }
  731. public BluetoothPlayer getBLEPlayer()
  732. {
  733. //Debug.Log("Get BluetoothPlayer:" + currentBLEPlayer);
  734. return currentBLEPlayer;
  735. }
  736. //更新跟随点位置
  737. public void UpdateCameraToLookNewPoint2P()
  738. {
  739. if (SceneManager.GetActiveScene().name != "InfraredGameDouble")
  740. {
  741. if (CameraToLookNew.ins != null)
  742. {
  743. Transform m_controlObj = CameraToLookNew.ins.transform;
  744. if (lerpForRotation2P)
  745. m_controlObj.localRotation = Quaternion.Lerp(m_controlObj.localRotation, newRotation2P, Time.deltaTime * lerpTimeRate2P);
  746. else
  747. m_controlObj.localRotation = newRotation2P;
  748. }
  749. }
  750. }
  751. public int get2PBattery()
  752. {
  753. return smartBowHelper2P == null ? 0 : smartBowHelper2P.GetBattery();
  754. }
  755. //主更新调用
  756. void updateSmartBowHelper2P()
  757. {
  758. UpdateCameraToLookNewPoint2P();
  759. }
  760. #endregion
  761. //取消正在连接的连接
  762. public void onCancelAllConnecting(BluetoothStatusEnum _bluetoothStatus = BluetoothStatusEnum.ConnectFail)
  763. {
  764. // status != BluetoothStatusEnum.ConnectSuccess
  765. //Debug.LogWarning("onCancelAllConnecting 1:" + status);
  766. if (status == BluetoothStatusEnum.Connecting)
  767. {
  768. userDoConnect = false;
  769. doConnect = false;
  770. OnDisconnect();
  771. DisconnectSmartBowHelper1P();
  772. SetStatus(_bluetoothStatus);
  773. }
  774. if (smartBowHelper1P != null && smartBowHelper1P.GetBluetoothStatus() == SmartBowSDK.BluetoothStatusEnum.Connecting)
  775. {
  776. userDoConnect = false;
  777. doConnect = false;
  778. canConnect = true;
  779. DisconnectSmartBowHelper1P();
  780. }
  781. //smartBowHelper2P.GetBluetoothStatus() != SmartBowSDK.BluetoothStatusEnum.Connected
  782. if (smartBowHelper2P != null && smartBowHelper2P.GetBluetoothStatus() == SmartBowSDK.BluetoothStatusEnum.Connecting)
  783. {
  784. userDoConnect2P = false;
  785. doConnect2P = false;
  786. canConnect2P = true;
  787. DisconnectSmartBowHelper2P();
  788. //smartBowHelper2P.Disconnect();
  789. Debug.Log("onCancelAllConnecting smartBowHelper2P 2:" + smartBowHelper2P.GetBluetoothStatus());
  790. }
  791. }
  792. #region 判断是否是1p设备连接的是HOUYIPRO信息
  793. public bool isMainConnectToHOUYIPRO()
  794. {
  795. bool _isHOUYIPRO = DeviceAim != null
  796. && DeviceAim.GetDeviceType(BluetoothPlayer.FIRST_PLAYER) == (int)AimDeviceType.HOUYIPRO;
  797. if (_isHOUYIPRO)
  798. {
  799. if (CommonConfig.bDisableBluetooth)
  800. {
  801. return true;
  802. }
  803. else
  804. {
  805. //如果是。判断是否连接
  806. return status == BluetoothStatusEnum.ConnectSuccess;
  807. }
  808. }
  809. else
  810. {
  811. return false;
  812. }
  813. }
  814. #endregion
  815. #region 判断是否是1p设备连接的是ARTEMISPRO信息
  816. public bool isMainConnectToARTEMISPRO()
  817. {
  818. bool _isARTEMISPRO = DeviceAim != null
  819. && DeviceAim.GetDeviceType(BluetoothPlayer.FIRST_PLAYER) == (int)AimDeviceType.ARTEMISPRO;
  820. if (_isARTEMISPRO)
  821. {
  822. if (CommonConfig.bDisableBluetooth)
  823. {
  824. return true;
  825. }
  826. else
  827. {
  828. //如果是。判断是否连接
  829. return status == BluetoothStatusEnum.ConnectSuccess;
  830. }
  831. }
  832. else
  833. {
  834. return false;
  835. }
  836. }
  837. #endregion
  838. #region 判断是否是1p设备连接的是红外信息,有多种红外设备
  839. public bool isMainConnectToInfraredDevice()
  840. {
  841. if (DeviceAim == null)
  842. return false;
  843. int type = DeviceAim.GetDeviceType(BluetoothPlayer.FIRST_PLAYER);
  844. bool _isInfraredDevice = type == (int)AimDeviceType.ARTEMISPRO
  845. || type == (int)AimDeviceType.HOUYIPRO;
  846. if (_isInfraredDevice)
  847. {
  848. if (CommonConfig.bDisableBluetooth)
  849. {
  850. return true;
  851. }
  852. else
  853. {
  854. //如果是。判断是否连接
  855. return status == BluetoothStatusEnum.ConnectSuccess;
  856. }
  857. }
  858. else
  859. {
  860. return false;
  861. }
  862. }
  863. #endregion
  864. #region 判断是否是1p设备连接的是Gun信息
  865. public bool isMainConnectToGun()
  866. {
  867. if (DeviceAim == null)
  868. return false;
  869. int type = DeviceAim.GetDeviceType(BluetoothPlayer.FIRST_PLAYER);
  870. bool _isGun = type == (int)AimDeviceType.Gun
  871. || type == (int)AimDeviceType.PistolM17
  872. || type == (int)AimDeviceType.RifleM416;
  873. if (_isGun)
  874. {
  875. if (CommonConfig.bDisableBluetooth)
  876. {
  877. return true;
  878. }
  879. else
  880. {
  881. //如果是。判断是否连接
  882. return status == BluetoothStatusEnum.ConnectSuccess;
  883. }
  884. }
  885. else
  886. {
  887. return false;
  888. }
  889. }
  890. /// <summary>
  891. /// 获取连接枪的类型
  892. /// </summary>
  893. /// <returns></returns>
  894. public (bool isGun, AimDeviceType gunType) isMainConnectToGunType()
  895. {
  896. AimDeviceType aimDeviceType = AimDeviceType.NONE;
  897. if (DeviceAim == null)
  898. return (false, aimDeviceType);
  899. int type = DeviceAim.GetDeviceType(BluetoothPlayer.FIRST_PLAYER);
  900. bool _isGun = type == (int)AimDeviceType.Gun
  901. || type == (int)AimDeviceType.PistolM17
  902. || type == (int)AimDeviceType.RifleM416;
  903. if (_isGun)
  904. aimDeviceType = (AimDeviceType)type;
  905. if (_isGun)
  906. {
  907. if (CommonConfig.bDisableBluetooth)
  908. {
  909. return (true, aimDeviceType);
  910. }
  911. else
  912. {
  913. //如果是。判断是否连接
  914. return (status == BluetoothStatusEnum.ConnectSuccess, aimDeviceType);
  915. }
  916. }
  917. else
  918. {
  919. return (false, aimDeviceType);
  920. }
  921. }
  922. #endregion
  923. /// <summary>
  924. /// 设置设备类型(1P 连接成功后同步顶部栏 / GlobalData;HomeView 未就绪时仍写入 PlayerPrefs)。
  925. /// </summary>
  926. public void SetMainConnectDeviceType()
  927. {
  928. AimHandler aim = DeviceAim;
  929. if (aim == null) return;
  930. int type = aim.GetDeviceType(BluetoothPlayer.FIRST_PLAYER);
  931. int topBarIndex = 0;
  932. if (type == (int)AimDeviceType.Gun
  933. || type == (int)AimDeviceType.PistolM17
  934. || type == (int)AimDeviceType.RifleM416)
  935. topBarIndex = 1;
  936. HomeViewTopBar topBar = UHomeView.ins?.MyTopBarView;
  937. if (topBar != null)
  938. {
  939. topBar.onChangeType(topBarIndex);
  940. return;
  941. }
  942. GlobalData.MyDeviceMode = (DeviceMode)topBarIndex;
  943. PlayerPrefs.SetInt("DeviceModeKey", topBarIndex);
  944. PlayerPrefs.Save();
  945. }
  946. #region 管理部分监听通信
  947. /// <summary>
  948. /// 监听枪状态
  949. /// </summary>
  950. public BleDeviceEvent OnBleDeviceState;
  951. /// <summary>
  952. /// 硬件对应的事件
  953. /// </summary>
  954. public delegate void BleDeviceEvent(BluetoothDeviceType bleDeviceType, BluetoothDeviceStatus gunStatusEnum);
  955. internal void InvokeOnBleDevice(BluetoothDeviceType bleDeviceType, BluetoothDeviceStatus gunStatusEnum)
  956. {
  957. try
  958. {
  959. OnBleDeviceState?.Invoke(bleDeviceType, gunStatusEnum);
  960. }
  961. catch (Exception e)
  962. {
  963. Debug.LogError(e);
  964. }
  965. }
  966. /// <summary>
  967. /// 记录硬件反馈的设备状态和连接的设备平台信息
  968. /// </summary>
  969. public BluetoothDeviceType myBluetoothDeviceType = BluetoothDeviceType.NONE;
  970. public ConnectPlatform myConnectPlatform = ConnectPlatform.NONE;
  971. /// <summary>
  972. /// 监听设备状态和连接的设备平台信息
  973. /// </summary>
  974. public DeviceAndSystemInfoEvent OnDeviceAndSystemInfoEvent;
  975. /// <summary>
  976. /// 硬件对应的事件初始化回调
  977. /// </summary>
  978. public delegate void DeviceAndSystemInfoEvent(ConnectPlatform connectPlatform, BluetoothDeviceType bleDeviceType);
  979. internal void InvokeOnDeviceAndSystemInfoEvent(ConnectPlatform connectPlatform, BluetoothDeviceType bleDeviceType)
  980. {
  981. try
  982. {
  983. myConnectPlatform = connectPlatform;
  984. myBluetoothDeviceType = bleDeviceType;
  985. OnDeviceAndSystemInfoEvent?.Invoke(connectPlatform, bleDeviceType);
  986. }
  987. catch (Exception e)
  988. {
  989. Debug.LogError(e);
  990. }
  991. }
  992. /// <summary>
  993. /// 获取一次当前记录的信息
  994. /// </summary>
  995. public void GetDeviceAndSystemInfoEvent()
  996. {
  997. OnDeviceAndSystemInfoEvent?.Invoke(myConnectPlatform, myBluetoothDeviceType);
  998. }
  999. /// <summary>
  1000. /// 返回一个存储用户的新手教程字符串
  1001. /// </summary>
  1002. /// <returns></returns>
  1003. public string GetInfraredGuiderKey()
  1004. {
  1005. return $"hideInfraredGuider-{LoginMgr.myUserInfo.id}-{myBluetoothDeviceType}";
  1006. }
  1007. /// <summary>
  1008. /// 清除当前红外记录的存储的所有key内容
  1009. /// </summary>
  1010. public void ClearAllInfraredGuider()
  1011. {
  1012. int userId = LoginMgr.myUserInfo.id;
  1013. foreach (BluetoothDeviceType type in Enum.GetValues(typeof(BluetoothDeviceType)))
  1014. {
  1015. string key = $"hideInfraredGuider-{userId}-{type}";
  1016. PlayerPrefs.DeleteKey(key);
  1017. }
  1018. PlayerPrefs.Save();
  1019. }
  1020. #endregion
  1021. }
  1022. }