BluetoothAim.cs 55 KB

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