BluetoothAim.cs 43 KB

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