BluetoothAim.cs 47 KB

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