BluetoothAim.cs 50 KB

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