BluetoothAim.cs 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361
  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. };
  824. }
  825. else
  826. {
  827. smartBowHelper2P.ResetAim();
  828. }
  829. };
  830. #if UNITY_STANDALONE_WIN || UNITY_EDITOR
  831. //用户2window连接 BluetoothWindows.IsWindows() &&
  832. if ( currentBLEPlayer == BluetoothPlayer.SECONDE_PLAYER)
  833. {
  834. Debug.Log("SECONDE_PLAYER BleWinHelper.RegisterTo");
  835. BleWinHelper com = BleWinHelper.RegisterTo(smartBowHelper2P.gameObject, smartBowHelper2P.CreateBluetoothWindows(),"2P");
  836. }
  837. #endif
  838. }
  839. void OnShot2P(float speed)
  840. {
  841. if (GameController.ins.GetArmBowDoublePlayer(PlayerType.SecondPlayer) != null)
  842. {
  843. //本地双人模式下处理2P ,1P在 ShootCheck 类处理
  844. GameController.ins.GetArmBowDoublePlayer(PlayerType.SecondPlayer).ADS_fire(true, speed);
  845. }
  846. }
  847. void UpdateConnectText()
  848. {
  849. var newStatus = smartBowHelper2P.GetBluetoothStatus();
  850. if (newStatus == SmartBowSDK.BluetoothStatusEnum.None) {
  851. if (GameController.ins) {
  852. GameController.ins.GetBowCameraDoublePlayer(PlayerType.SecondPlayer).isTouchMode = true;
  853. }
  854. Debug.Log("<color=blue>未连接</color>(点击连接)");
  855. if (!bNoNeedToReconnect) return;
  856. scanLock = false;
  857. if (_scanCanRetryCount2P > 0)
  858. {
  859. _scanCanRetryCount2P--;
  860. scanLock = true;
  861. ConnectSmartBowHelper2P();
  862. }
  863. else
  864. {
  865. userDoConnect2P = false;
  866. canConnect2P = true;
  867. Log("没有发现设备");
  868. PopupMgr.ins.ShowTip("连接失败,未发现目标设备!");
  869. TextAutoLanguage2.GetTextByKey("ble-dev-notfound");
  870. }
  871. }else if (newStatus == SmartBowSDK.BluetoothStatusEnum.Connecting) {
  872. Debug.Log("<color=#FF670D>连接中</color>");
  873. if (GameController.ins)
  874. {
  875. GameController.ins.GetBowCameraDoublePlayer(PlayerType.SecondPlayer).isTouchMode = false;
  876. }
  877. }else if (newStatus == SmartBowSDK.BluetoothStatusEnum.Connected)
  878. {
  879. if (GameController.ins) {
  880. GameController.ins.GetBowCameraDoublePlayer(PlayerType.SecondPlayer).isTouchMode = false;
  881. }
  882. if (smartBowHelper2P.IsBluetoothModuleInited()) Debug.Log("<color=green>已连接</color>(点击断开)");
  883. else Debug.Log("<color=green>已连接</color><color=blue>(正在初始化)</color>");
  884. }
  885. }
  886. public void ConnectSmartBowHelper2P() {
  887. if (smartBowHelper2P == null)
  888. {
  889. onCreateSmartBowHelper2P();
  890. CallDelay(1, () =>
  891. {
  892. smartBowHelper2P.Connect(userTags,deviceId2,true);//不在sdk 判断mac
  893. });
  894. }
  895. else {
  896. smartBowHelper2P.Connect(userTags, deviceId2,true);
  897. }
  898. }
  899. public void DoConnect2P()
  900. {
  901. Debug.Log("DoConnect2P");
  902. if (smartBowHelper2P == null || smartBowHelper2P.GetBluetoothStatus() == SmartBowSDK.BluetoothStatusEnum.None)
  903. {
  904. //connectCanceled = false;
  905. userDoConnect2P = true;
  906. doConnect2P = true;
  907. bNoNeedToReconnect = true;
  908. Connect2P();
  909. }
  910. else if (smartBowHelper2P.GetBluetoothStatus() == SmartBowSDK.BluetoothStatusEnum.Connected)
  911. {
  912. userDoConnect2P = false;
  913. doConnect2P = false;
  914. canConnect2P = true;
  915. DisconnectSmartBowHelper2P();
  916. }
  917. }
  918. void Connect2P()
  919. {
  920. //if (BluetoothShoot.scanLock)
  921. //{
  922. // return;
  923. //}
  924. if (!canConnect2P)
  925. {
  926. return;
  927. }
  928. doConnect = false;
  929. doConnect2P = false;
  930. scanLock = true;
  931. canConnect2P = false;
  932. _scanCanRetryCount2P = 4;
  933. //SetStatus2P(BluetoothStatusEnum.Connecting);
  934. ConnectSmartBowHelper2P();
  935. }
  936. //初始化陀螺仪
  937. public void OnCalibrateGyr2P()
  938. {
  939. if (smartBowHelper2P.IsGyrCalibrating()) smartBowHelper2P.StopGyrCalibration();
  940. else smartBowHelper2P.StartGyrCalibration();
  941. }
  942. //初始化地磁计
  943. public void OnCalibrateMag2P()
  944. {
  945. smartBowHelper2P.StartMagCalibration();
  946. }
  947. #endregion
  948. #region 当前选择操作的设备 如1p或者2p
  949. public SmartBowHelper getSmartBowHelper2P() {
  950. return smartBowHelper2P;
  951. }
  952. public void setBLEPlayer(BluetoothPlayer blePlayer)
  953. {
  954. //切换蓝牙用户时候,判断是否正在连接,如果正在匹配连接的话,取消连接状态
  955. if (blePlayer != currentBLEPlayer) {
  956. Debug.Log("Set BluetoothPlayer status:" + status);
  957. onCancelAllConnecting();
  958. }
  959. currentBLEPlayer = blePlayer;
  960. Debug.Log("Set BluetoothPlayer:" + currentBLEPlayer);
  961. }
  962. public BluetoothPlayer getBLEPlayer()
  963. {
  964. //Debug.Log("Get BluetoothPlayer:" + currentBLEPlayer);
  965. return currentBLEPlayer;
  966. }
  967. //更新跟随点位置
  968. public void UpdateCameraToLookNewPoint2P() {
  969. if (SceneManager.GetActiveScene().name != "InfraredGameDouble") {
  970. if (CameraToLookNew.ins != null)
  971. {
  972. Transform m_controlObj = CameraToLookNew.ins.transform;
  973. if (lerpForRotation2P)
  974. m_controlObj.localRotation = Quaternion.Lerp(m_controlObj.localRotation, newRotation2P, Time.deltaTime * lerpTimeRate2P);
  975. else
  976. m_controlObj.localRotation = newRotation2P;
  977. }
  978. }
  979. }
  980. public int get2PBattery() {
  981. return smartBowHelper2P == null? 0 : smartBowHelper2P.GetBattery();
  982. }
  983. //主更新调用
  984. void updateSmartBowHelper2P() {
  985. UpdateCameraToLookNewPoint2P();
  986. }
  987. #endregion
  988. //取消正在连接的连接
  989. public void onCancelAllConnecting(BluetoothStatusEnum _bluetoothStatus = BluetoothStatusEnum.ConnectFail) {
  990. // status != BluetoothStatusEnum.ConnectSuccess
  991. Debug.LogWarning("onCancelAllConnecting 1:" + status);
  992. #if UNITY_STANDALONE_WIN || UNITY_EDITOR
  993. //BleUDP.ins != null
  994. //BluetoothWindows.IsWindows() &&
  995. if (status == BluetoothStatusEnum.Connecting)
  996. {
  997. //Debug.LogWarning("onCancelAllConnecting 2:" + status);
  998. userDoConnect = false;
  999. doConnect = false;
  1000. OnDisconnect();
  1001. // BleUDP.ins.Disconnect();
  1002. firstBluetoothWindows.Disconnect();
  1003. SetStatus(_bluetoothStatus);
  1004. Debug.LogWarning("onCancelAllConnecting 3:" + status);
  1005. }
  1006. #else
  1007. if (bluetoothHelper != null && status == BluetoothStatusEnum.Connecting)
  1008. {
  1009. Debug.LogWarning("onCancelAllConnecting 2:" + status);
  1010. userDoConnect = false;
  1011. doConnect = false;
  1012. OnDisconnect();
  1013. DisconnectBleHelper();
  1014. SetStatus(_bluetoothStatus);
  1015. }
  1016. #endif
  1017. //smartBowHelper2P.GetBluetoothStatus() != SmartBowSDK.BluetoothStatusEnum.Connected
  1018. if (smartBowHelper2P != null && smartBowHelper2P.GetBluetoothStatus() == SmartBowSDK.BluetoothStatusEnum.Connecting)
  1019. {
  1020. userDoConnect2P = false;
  1021. doConnect2P = false;
  1022. canConnect2P = true;
  1023. DisconnectSmartBowHelper2P();
  1024. //smartBowHelper2P.Disconnect();
  1025. Debug.Log("onCancelAllConnecting smartBowHelper2P 2:" + smartBowHelper2P.GetBluetoothStatus());
  1026. }
  1027. }
  1028. #region 判断是否是1p设备连接的是HOUYIPRO信息
  1029. public bool isMainConnectToHOUYIPRO() {
  1030. bool _isHOUYIPRO = false;
  1031. foreach (AimDeviceInfo p in AimHandler.ins.aimDeviceInfos.arry)
  1032. {
  1033. if ((int)BluetoothPlayer.FIRST_PLAYER == p.id && p.type == (int)AimDeviceType.HOUYIPRO)
  1034. {
  1035. _isHOUYIPRO = true;
  1036. }
  1037. }
  1038. if (_isHOUYIPRO)
  1039. {
  1040. if (CommonConfig.bDisableBluetooth)
  1041. {
  1042. return true;
  1043. }
  1044. else
  1045. {
  1046. //如果是。判断是否连接
  1047. return status == BluetoothStatusEnum.ConnectSuccess;
  1048. }
  1049. }
  1050. else {
  1051. return false;
  1052. }
  1053. }
  1054. #endregion
  1055. #region 判断是否是1p设备连接的是ARTEMISPRO信息
  1056. public bool isMainConnectToARTEMISPRO()
  1057. {
  1058. bool _isARTEMISPRO = false;
  1059. foreach (AimDeviceInfo p in AimHandler.ins.aimDeviceInfos.arry)
  1060. {
  1061. if ((int)BluetoothPlayer.FIRST_PLAYER == p.id && p.type == (int)AimDeviceType.ARTEMISPRO)
  1062. {
  1063. _isARTEMISPRO = true;
  1064. }
  1065. }
  1066. if (_isARTEMISPRO)
  1067. {
  1068. if (CommonConfig.bDisableBluetooth)
  1069. {
  1070. return true;
  1071. }
  1072. else
  1073. {
  1074. //如果是。判断是否连接
  1075. return status == BluetoothStatusEnum.ConnectSuccess;
  1076. }
  1077. }
  1078. else
  1079. {
  1080. return false;
  1081. }
  1082. }
  1083. #endregion
  1084. #region 判断是否是1p设备连接的是红外信息,有多种红外设备-弓箭
  1085. public bool isMainConnectToInfraredDevice()
  1086. {
  1087. bool _isInfraredDevice = false;
  1088. foreach (AimDeviceInfo p in AimHandler.ins.aimDeviceInfos.arry)
  1089. {
  1090. if ((int)BluetoothPlayer.FIRST_PLAYER == p.id && (p.type == (int)AimDeviceType.ARTEMISPRO || p.type == (int)AimDeviceType.HOUYIPRO))
  1091. {
  1092. _isInfraredDevice = true;
  1093. }
  1094. }
  1095. if (_isInfraredDevice)
  1096. {
  1097. if (CommonConfig.bDisableBluetooth)
  1098. {
  1099. return true;
  1100. }
  1101. else {
  1102. //如果是。判断是否连接
  1103. return status == BluetoothStatusEnum.ConnectSuccess;
  1104. }
  1105. }
  1106. else
  1107. {
  1108. return false;
  1109. }
  1110. }
  1111. #endregion
  1112. #region 判断是否是1p设备连接的是Gun信息
  1113. public bool isMainConnectToGun()
  1114. {
  1115. bool _isGun = false;
  1116. foreach (AimDeviceInfo p in AimHandler.ins.aimDeviceInfos.arry)
  1117. {
  1118. if ((int)BluetoothPlayer.FIRST_PLAYER == p.id && p.type == (int)AimDeviceType.Gun)
  1119. {
  1120. _isGun = true;
  1121. }
  1122. }
  1123. if (_isGun)
  1124. {
  1125. if (CommonConfig.bDisableBluetooth)
  1126. {
  1127. return true;
  1128. }
  1129. else
  1130. {
  1131. //如果是。判断是否连接
  1132. return status == BluetoothStatusEnum.ConnectSuccess;
  1133. }
  1134. }
  1135. else
  1136. {
  1137. return false;
  1138. }
  1139. }
  1140. #endregion
  1141. /// <summary>
  1142. /// 设置设备类型
  1143. /// </summary>
  1144. public void SetMainConnectDeviceType() {
  1145. //1号玩家连接蓝牙成功时候,设置一次 GlobalData.MyDeviceMode
  1146. foreach (AimDeviceInfo p in AimHandler.ins.aimDeviceInfos.arry)
  1147. {
  1148. if ((int)BluetoothPlayer.FIRST_PLAYER == p.id)
  1149. {
  1150. if (p.type == (int)AimDeviceType.Gun)
  1151. {
  1152. //设置枪
  1153. HomeView.ins.MyTopBarView.onChangeType(1);
  1154. }
  1155. else
  1156. {
  1157. //其余默认是弓箭
  1158. HomeView.ins.MyTopBarView.onChangeType(0);
  1159. }
  1160. }
  1161. }
  1162. }
  1163. #region 用户1 window ble 连接和部分共用代码
  1164. void OnConnected_windows1()
  1165. {
  1166. Log("[WinBle_1P]连接成功\n" + deviceName);
  1167. SetStatus(BluetoothStatusEnum.ConnectSuccess);
  1168. BowCamera.isTouchMode = false;
  1169. if (CommonConfig.EnableDecryption && NeedDecryption)
  1170. {
  1171. // 这里验证指令,开始请求授权
  1172. // 启动轮询协程
  1173. StartCoroutine(PollingCoroutine());
  1174. }
  1175. else
  1176. {
  1177. //除了pc,Android 直接连接
  1178. InitWhenConenct();
  1179. }
  1180. }
  1181. void OnConnectionFailed_windows1()
  1182. {
  1183. Log("连接失败\n" + deviceName);
  1184. OnDisconnect();
  1185. }
  1186. void OnCharacteristicChanged_windows1(string deviceId,byte[] value)
  1187. {
  1188. OnCharacteristicChanged(null, value, null);
  1189. }
  1190. void OnCharacteristicChanged(BluetoothHelper helper, byte[] value, BluetoothHelperCharacteristic characteristic) {
  1191. if (status != BluetoothStatusEnum.ConnectSuccess) return;
  1192. if (!hasData)
  1193. {
  1194. hasData = true;
  1195. hasDataTime = JCUnityLib.TimeUtils.GetTimestamp();
  1196. }
  1197. if (CommonConfig.EnableDecryption && NeedDecryption)
  1198. {
  1199. //Pc 版本先走校验流程
  1200. if (!BluetoothDecryptor.AUTHOR_IsDecrypt())
  1201. {
  1202. if (value[0] == 0x5a)
  1203. {
  1204. // 从硬件读取数据
  1205. if (value != null && value.Length > 0)
  1206. {
  1207. Debug.Log("接收到数据:" + BitConverter.ToString(value));
  1208. BluetoothDecryptor.AUTHOR_Decrypt(value);
  1209. if (BluetoothDecryptor.AUTHOR_IsDecrypt())
  1210. {
  1211. Debug.Log("解密成功!");
  1212. //解密成功后
  1213. StopEncrypt();
  1214. //开始连接其他信息
  1215. InitWhenConenct();
  1216. }
  1217. else
  1218. {
  1219. Debug.Log("解密失败!");
  1220. //SideTipView.ShowTip("设备通信失败,断开连接", Color.yellow);
  1221. //断开连接等操作
  1222. if (PollingCoroutineCount <= 0)
  1223. {
  1224. StopEncrypt();
  1225. DoConnect();
  1226. }
  1227. }
  1228. }
  1229. }
  1230. return;
  1231. }
  1232. }
  1233. dataCount++;
  1234. if (curMac == null && dataCount < 500)
  1235. {
  1236. UploadMacAddress(value);
  1237. }
  1238. byte[] bytes = value;
  1239. if (AimHandler.ins)
  1240. {
  1241. AimHandler.ins.OnDataReceived(bytes);
  1242. }
  1243. }
  1244. #endregion
  1245. }