BluetoothAim.cs 44 KB

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