BluetoothAim.cs 48 KB

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