| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685 |
- using ArduinoBluetoothAPI;
- using System;
- using UnityEngine;
- using System.Collections.Generic;
- using UnityEngine.UI;
- using DG.Tweening;
- using SmartBowSDK;
- using System.Collections;
- using UnityEngine.SceneManagement;
- using BleWinHelper = SmartBowSDK_BleWinHelper.BleWinHelper;
- /* 蓝牙瞄准模块 */
- /* 管理1p和2p蓝牙连接,脚本外调用逻辑如果同时连接1p和2p设备,以前的逻辑还是以1p为主,如果只连2p,则使用2p数据*/
- public class BluetoothAim : MonoBehaviour
- {
- #region 2p蓝牙使用的是sdk,所以需要另外定义
- //2p时候过滤的名字
- readonly string targetDeviceName2P = "Bbow_20210501 | HOUYI Pro | Pistol | Pistol M9 | ARTEMIS Pro | Pistol M17 | Rifle M416";
- #endregion
- #region 弓箭蓝牙模块基本信息
- readonly string targetDeviceNameAxis = "Bbow_20210501 | ARTEMIS | HOUYI | HOUYI Pro | ARTEMIS Pro";
- readonly string targetDeviceName = "Bbow_20210501 | ARTEMIS Pro";//HOUYI Pro
- readonly string targetDeviceNameHOUYIPro = "HOUYI Pro";
- readonly string targetDeviceNameGun = "Pistol | Pistol M9 | Bbow_20210501";
- readonly string targetDeviceNameGun_M17 = "Pistol M17";
- readonly string targetDeviceNameGun_M416 = "Rifle M416";
- string targetDeviceService
- {
- get
- {
- if (CommonConfig.devicePlan == 0 || CommonConfig.devicePlan == 3)
- {
- #if UNITY_ANDROID
- return "0000fff0";
- #else
- return "fff0";
- #endif
- }
- return "6e400001";
- }
- }
- string targetDeviceCharacteristicWrite
- {
- get
- {
- if (CommonConfig.devicePlan == 0 || CommonConfig.devicePlan == 3)
- {
- #if UNITY_ANDROID
- return "0000fff2";
- #else
- return "fff2";
- #endif
- }
- return "6e400002";
- }
- }
- string targetDeviceCharacteristicNotify
- {
- get
- {
- if (CommonConfig.devicePlan == 0 || CommonConfig.devicePlan == 3)
- {
- #if UNITY_ANDROID
- return "0000fff1";
- #else
- return "fff1";
- #endif
- }
- return "6e400003";
- }
- }
- #endregion
- //当前选择的设备
- BluetoothPlayer currentBLEPlayer = BluetoothPlayer.FIRST_PLAYER;
- //1p蓝牙连接
- BluetoothHelper bluetoothHelper;
- BluetoothHelperCharacteristic characteristicWrite;
- BluetoothHelperService bluetoothService;
- string deviceName = "";
- bool canConnect = true;
- [SerializeField] Text textUI;
- public BluetoothStatusEnum status = BluetoothStatusEnum.Connect;
- int dataCount = 0;
- public bool hasData = false;
- public long hasDataTime;
- public static bool scanLock = false; //防止同时扫描冲突
- public static BluetoothAim ins;
- //根据设备情况来看是否需要解密,目前就是枪需要进行解密操作
- public bool NeedDecryption = false;
- public BluetoothWindows firstBluetoothWindows { get; set; }
- //首页初始化时候调用一次连接
- public bool bStartConnect = false;
- void Start()
- {
- ins = this;
- InitAutoDormancy();
- #if UNITY_STANDALONE_WIN || UNITY_EDITOR
- // new GameObject("BleUDP").AddComponent<BleUDP>();
- firstBluetoothWindows = new BluetoothWindows();
- firstBluetoothWindows.OnConnected = OnConnected_windows1;
- firstBluetoothWindows.OnConnectionFailed = OnConnectionFailed_windows1;
- firstBluetoothWindows.OnCharacteristicChanged = OnCharacteristicChanged_windows1;
- //window蓝牙连接
- if (currentBLEPlayer == BluetoothPlayer.FIRST_PLAYER)
- {
- Debug.Log("FIRST_PLAYER BleWinHelper.RegisterTo");
- BleWinHelper.RegisterTo(gameObject, firstBluetoothWindows, "1P");
- }
- #endif
- }
- void OnDestroy()
- {
- //删除ble。1p,2p 都删除
- DisconnectBleHelper();
- DisconnectSmartBowHelper2P();
- }
- /// <summary>
- /// 首页初始化的时候,如果是第一次。尝试连接蓝牙。只进行一次
- /// </summary>
- public void HomeViewConnectBLE()
- {
- if (bStartConnect) return;
- bStartConnect = true;
- //当已经连接过一把弓(1P)时,下一次打开 APP,1P 就自动处于连接的状态;用户只要打1.开 APP 和打开模块就可以自动连接,减少连接设备的操作。
- Debug.Log("[初始化自动连接蓝牙] 自动开始连接上一次连接的设备 1P?");
- AimHandler.ins.OnGetAimDeviceInfos();
- if (AimHandler.ins.aimDeviceInfos.arry.Count != 0)
- {
- //如果需要连接
- if (status != BluetoothStatusEnum.ConnectSuccess)
- {
- //setBLEPlayer(BluetoothPlayer.FIRST_PLAYER);
- Debug.Log("[初始化自动连接蓝牙] 当前选择的操作用户:" + getBLEPlayer());
- //AimHandler.ins.SetAimDeviceSelectIndex(0);
- //第一次进入从存储的资料获取 aimDeviceInfo
- AimHandler.ins.onCreateAimDeviceInfoById();
- DoConnect();
- }
- }
- }
- private bool userDoConnect = false;
- private bool doConnect = false;
- public Func<bool> action_DoConnectInterceptor;
- public void DoConnect()
- {
- if (action_DoConnectInterceptor != null)
- {
- if (action_DoConnectInterceptor.Invoke()) return;
- }
- if (status == BluetoothStatusEnum.Connect)
- {
- connectCanceled = false;
- userDoConnect = true;
- doConnect = true;
- SetStatus(BluetoothStatusEnum.Connecting);
- }
- else if (status == BluetoothStatusEnum.ConnectSuccess)
- {
- userDoConnect = false;
- doConnect = false;
- OnDisconnect();
- DisconnectBleHelper();
- //#if UNITY_STANDALONE_WIN || UNITY_EDITOR
- // //BleUDP.ins.Disconnect();
- // if (firstBluetoothWindows.Disconnect()) SetStatus(BluetoothStatusEnum.Connect);
- //#else
- // DisconnectBleHelper();
- //#endif
- }
- }
- //连接取消,退回登录时需要取消连接(扫描)
- [NonSerialized] public bool connectCanceled = false;
- void OnDisconnect()
- {
- curMac = null;
- dataCount = 0;
- hasData = false;
- canConnect = true;
- SetStatus(BluetoothStatusEnum.ConnectFail);
- BowCamera.isTouchMode = true;
- DestroyWhenDisconenct();
- if (AimHandler.ins) AimHandler.ins.SetMsOldDefault();
- }
- float notUserDoConnectTime = 0;
- void Update()
- {
- updateSmartBowHelper2P();
- if (userDoConnect && status == BluetoothStatusEnum.Connect)
- {
- DoConnect();
- }
- if (doConnect) Connect();
- //if (CommonConfig.StandaloneMode)
- //{
- // if (!userDoConnect && status == BluetoothStatusEnum.Connect)
- // {
- // if (notUserDoConnectTime == 0)
- // {
- // DoConnect();
- // notUserDoConnectTime = 0.1f;
- // }
- // else
- // {
- // notUserDoConnectTime += Time.deltaTime;
- // if (notUserDoConnectTime > 2.5f)
- // {
- // DoConnect();
- // notUserDoConnectTime = 0.1f;
- // }
- // }
- // }
- //}
- }
- void SetStatus(BluetoothStatusEnum statusValue)
- {
- status = statusValue;
- if (status == BluetoothStatusEnum.ConnectFail)
- {
- Sequence sequence = DOTween.Sequence();
- sequence.AppendInterval(2f);
- sequence.AppendCallback(delegate ()
- {
- if (status == BluetoothStatusEnum.ConnectFail)
- {
- status = BluetoothStatusEnum.Connect;
- }
- });
- sequence.SetUpdate(true);
- SimulateMouseController.ins?.SetBleConnected(false);
- }
- else if (status == BluetoothStatusEnum.ConnectSuccess)
- {
- SimulateMouseController.ins?.SetBleConnected(true);
- }
- }
- void DisconnectBleHelper()
- {
- if (BluetoothWindows.IsWindows())
- {
- if (firstBluetoothWindows.Disconnect())
- SetStatus(BluetoothStatusEnum.Connect);
- return;
- }
- if (bluetoothHelper != null) bluetoothHelper.Disconnect();
- }
- void DisconnectSmartBowHelper2P()
- {
- //2p
- if (smartBowHelper2P != null) smartBowHelper2P.Disconnect();
- }
- void Connect()
- {
- //if (BluetoothShoot.scanLock)
- //{
- // return;
- //}
- if (!canConnect)
- {
- return;
- }
- doConnect = false;
- doConnect2P = false;
- scanLock = true;
- canConnect = false;
- _scanCanRetryCount = 4;
- SetStatus(BluetoothStatusEnum.Connecting);
- #if UNITY_STANDALONE_WIN || UNITY_EDITOR
- //ConnectBleByUDP();
- firstBluetoothWindows.Connect();
- #else
- ConnectBleHelper();
- #endif
- }
- int _scanCanRetryCount = 4;
- void ConnectBleHelper()
- {
- #if UNITY_ANDROID
- PopupMgr.ins.ClearAllTip();
- if (BluetoothHelperAndroid.IsBluetoothEnabled() == false)
- {
- Debug.Log("BluetoothHelperAndroid.IsBluetoothEnabled():" + BluetoothHelperAndroid.IsBluetoothEnabled());
- HandleConnectException(TextAutoLanguage2.GetTextByKey("ble-exception1"));
- return;
- }
- if (BluetoothHelperAndroid.RequestBluetoothPermissions(ConnectBleHelper, (permission) =>
- {
- Debug.Log("permission ==== :" + permission);
- if (permission.Contains("LOCATION"))
- {
- HandleConnectException(TextAutoLanguage2.GetTextByKey("ble-exception2"));
- }
- else if (permission.Contains("BLUETOOTH"))
- {
- HandleConnectException(TextAutoLanguage2.GetTextByKey("ble-exception3"));
- }
- })) return;
- #endif
- try
- {
- BluetoothHelper.BLE = true;
- bluetoothHelper = BluetoothHelper.GetNewInstance();
- bluetoothHelper.OnConnected += (BluetoothHelper helper) =>
- {
- Log("连接成功\n" + helper.getDeviceName());
- SetStatus(BluetoothStatusEnum.ConnectSuccess);
- SetMainConnectDeviceType();
- if (connectCanceled)
- {
- Debug.Log("ble connectCanceled");
- DoConnect();
- return;
- }
- BowCamera.isTouchMode = false;
- foreach (BluetoothHelperService service in helper.getGattServices())
- {
- if (service.getName().ToLower().StartsWith(targetDeviceService))
- {
- bluetoothService = service;
- foreach (BluetoothHelperCharacteristic characteristic in service.getCharacteristics())
- {
- if (characteristic.getName().ToLower().StartsWith(targetDeviceCharacteristicWrite))
- {
- characteristicWrite = characteristic;
- }
- else if (characteristic.getName().ToLower().StartsWith(targetDeviceCharacteristicNotify))
- {
- BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristic.getName());
- ch.setService(bluetoothService.getName());
- bluetoothHelper.Subscribe(ch);
- }
- }
- }
- }
- // CallDelay(1, OpenInfrared);
- // CallDelay(2, OpenReceiveData);
- // CallDelay(3, RequestBattery);
- if (CommonConfig.EnableDecryption && NeedDecryption)
- {
- // 这里验证指令,开始请求授权
- // 启动轮询协程
- StartCoroutine(PollingCoroutine());
- }
- else
- {
- //除了pc,Android 直接连接
- CallDelay(2, () =>
- {
- if (status != BluetoothStatusEnum.ConnectSuccess) return;
- InitWhenConenct();
- //if (CommonConfig.StandaloneMode)
- //{
- // if (UnityEngine.SceneManagement.SceneManager.GetActiveScene().name == "Home"
- // && PersistenHandler.ins.menuBackCtr.views.Count == 0
- // && !FindObjectOfType<NewUserGuider>())
- // {
- // ViewMgr.Instance.ShowView<GameStartView>();
- // }
- //}
- });
- }
- };
- bluetoothHelper.OnConnectionFailed += (BluetoothHelper helper) =>
- {
- Log("连接失败\n" + helper.getDeviceName());
- OnDisconnect();
- };
- bluetoothHelper.OnCharacteristicChanged += (helper, value, characteristic) =>
- {
- OnCharacteristicChanged(helper, value, characteristic);
- };
- bluetoothHelper.OnScanEnded += (BluetoothHelper helper, LinkedList<BluetoothDevice> nearbyDevices) =>
- {
- scanLock = false;
- if (connectCanceled)
- {
- userDoConnect = false;
- canConnect = true;
- status = BluetoothStatusEnum.Connect;
- Debug.Log("ble connectCanceled");
- return;
- }
- foreach (BluetoothDevice device in nearbyDevices)
- {
- Log("发现设备 " + device.DeviceName);
- if (AimHandler.ins.aimDeviceInfo.type == (int)AimDeviceType.HOUYIPRO)
- { //需要判断是否是红外弓箭
- if (TryConnectDevice(targetDeviceNameHOUYIPro, device.DeviceName, "HOUYIPRO")) return;
- }
- else if (AimHandler.ins.aimDeviceInfo.type == (int)AimDeviceType.ARTEMISPRO)
- { //需要判断是否是ARTEMISPro弓箭
- if (TryConnectDevice(targetDeviceName, device.DeviceName, "ARTEMISPRO")) return;
- }
- else if (AimHandler.ins.aimDeviceInfo.type == (int)AimDeviceType.Gun)
- {
- if (TryConnectDevice(targetDeviceNameGun, device.DeviceName, "Pistol")) return;
- }
- else if (AimHandler.ins.aimDeviceInfo.type == (int)AimDeviceType.PistolM17)
- {
- if (TryConnectDevice(targetDeviceNameGun_M17, device.DeviceName, "PistolM17")) return;
- }
- else if (AimHandler.ins.aimDeviceInfo.type == (int)AimDeviceType.RifleM416)
- {
- if (TryConnectDevice(targetDeviceNameGun_M416, device.DeviceName, "RifleM416")) return;
- }
- else
- { //其余的九轴连接
- //不允许匹配HOUYIPRO,因为这个没有九轴 targetDeviceName { Bbow_20210501 }
- //if (targetDeviceName.Contains(device.DeviceName))
- //{
- // BLEConnectByName(device.DeviceName);
- // Log("匹配普通设备设备 " + device.DeviceName);
- // return;
- //}
- if (TryConnectDevice(targetDeviceNameAxis, device.DeviceName, device.DeviceName)) return;
-
- }
- }
- if (_scanCanRetryCount > 0)
- {
- _scanCanRetryCount--;
- scanLock = true;
- ConnectBleHelper();
- }
- else
- {
- userDoConnect = false;
- canConnect = true;
- Log("没有发现设备");
- TextAutoLanguage2.GetTextByKey("ble-dev-notfound");
- SetStatus(BluetoothStatusEnum.ConnectFail);
- }
- };
- bluetoothHelper.ScanNearbyDevices();
- Log("正在扫描设备");
- }
- catch (Exception e)
- {
- Debug.LogError(e);
- HandleConnectException(TextAutoLanguage2.GetTextByKey("ble-please-open-ble"));
- }
- }
- /// <summary>
- /// 精确匹配,大小写敏感,多设备名字用 " | " 分隔
- /// </summary>
- /// <param name="filterNames">过滤字符串</param>
- /// <param name="deviceName">真实连接名字</param>
- /// <param name="deviceTypeName">日志名字</param>
- /// <returns></returns>
- private bool TryConnectDevice(string filterNames, string deviceName, string deviceTypeName)
- {
- if (string.IsNullOrWhiteSpace(filterNames)) return false;
- string[] filterArray = filterNames.Split('|'); // 支持多个名字
- foreach (var f in filterArray)
- {
- if (string.Equals(f.Trim(), deviceName.Trim(), StringComparison.OrdinalIgnoreCase))
- {
- BLEConnectByName(deviceName);
- Log($"匹配设备 {deviceTypeName}: {deviceName}");
- return true;
- }
- }
- return false;
- }
- void BLEConnectByName(string name)
- {
- deviceName = name;
- bluetoothHelper.setDeviceName(deviceName);
- bluetoothHelper.Connect();
- }
- void HandleConnectException(string errorText)
- {
- scanLock = false;
- canConnect = true;
- // SetStatus(BluetoothStatusEnum.ConnectFail);
- status = BluetoothStatusEnum.Connect;
- userDoConnect = false;
- PopupMgr.ins.ShowTip(errorText);
- }
- // 协程来处理轮询
- // 目前仅手枪支持该指令。
- // 调用 AUTHOR_SendReq 方法,传递系统Tick值(在这里用一个示例值)
- private bool isPolling = false;
- private int PollingCoroutineCount = 4;
- private IEnumerator PollingCoroutine()
- {
- // 发送请求
- // SendEncrypt();
- // 设置轮询标志
- isPolling = true;
- PollingCoroutineCount = 4;
- uint systemTick = (uint)DateTime.Now.Ticks;
- while (isPolling)
- {
- // 等待一秒
- yield return new WaitForSeconds(1f);
- SendEncrypt(systemTick);
- PollingCoroutineCount--;
- }
- }
- /// <summary>
- /// 1、加密字节由系统生成的随机码加密而成;
- /// 2、蓝牙每次断开并重新连接后,会重新生成随机加密值;
- /// 3、当设备未发送正确的解密信息时,APP会每秒发送1次请求,直到解密成功。
- /// </summary>
- /// <param name="systemTick"></param>
- private void SendEncrypt(uint systemTick)
- {
- byte[] sendByte = BluetoothDecryptor.AUTHOR_SendReq(systemTick);
- Debug.Log("请求sendByte:" + BitConverter.ToString(sendByte));
- WriteByteData(sendByte);
- }
- // 模拟从硬件读取数据
- public void StopEncrypt()
- {
- isPolling = false;
- }
- void ConnectBleByUDP()
- {
- try
- {
- BleUDP.ins.OnConnected = () =>
- {
- Log("连接成功\n" + deviceName);
- SetStatus(BluetoothStatusEnum.ConnectSuccess);
- BowCamera.isTouchMode = false;
- InitWhenConenct();
- };
- BleUDP.ins.OnConnectionFailed = () =>
- {
- Log("连接失败\n" + deviceName);
- OnDisconnect();
- };
- BleUDP.ins.OnCharacteristicChanged = (byte[] value) =>
- {
- //if (!hasData) {
- // hasDataTime = JCUnityLib.TimeUtils.GetTimestamp();
- // UploadMacAddress(value);
- //}
- //hasData = true;
- if (status != BluetoothStatusEnum.ConnectSuccess) return;
- if (!hasData)
- {
- hasData = true;
- hasDataTime = JCUnityLib.TimeUtils.GetTimestamp();
- }
- dataCount++;
- if (curMac == null && dataCount < 500)
- {
- UploadMacAddress(value);
- }
- byte[] bytes = value;
- // Log(String.Join(",", bytes));
- BluetoothClient.UploadData(0, bytes);
- if (AimHandler.ins)
- {
- AimHandler.ins.OnDataReceived(bytes);
- }
- };
- BleUDP.ins.OnScanEnded = () =>
- {
- scanLock = false;
- deviceName = targetDeviceName;
- BleUDP.ins.Connect();
- Log("发现设备\n" + deviceName);
- };
- BleUDP.ins.ScanNearbyDevices();
- }
- catch (Exception e)
- {
- Debug.LogError(e.Message);
- Debug.LogError(e.StackTrace);
- scanLock = false;
- canConnect = true;
- SetStatus(BluetoothStatusEnum.ConnectFail);
- }
- }
- #region 自动进入/退出休眠状态, 这里做程指令发送队列,为了控制连续发送指令的间隔,避免硬件收不到或处理不过来
- class CmdToSend
- {
- public string[] cmds;
- public Action onComplete;
- public Func<bool> canDo;
- public CmdToSend(string[] cmds, Action onComplete, Func<bool> canDo)
- {
- this.cmds = cmds;
- this.onComplete = onComplete;
- this.canDo = canDo;
- }
- }
- Queue<CmdToSend> cmdWaitingList = new Queue<CmdToSend>();
- bool isSendCmdLocked = false;
- bool canAutoDormancy = false;
- bool isStartUp = false;
- JCUnityLib.CountLock needModularAwake = new JCUnityLib.CountLock();
- void CheckAndStartUp()
- {
- if (needModularAwake.IsLocked())
- {
- StartUp();
- }
- else
- {
- Dormancy();
- }
- }
- void InitAutoDormancy()
- {
- // GlobalEventCenter.ins.onGameSceneLoad += () => {
- // needModularAwake.Lock();
- // CheckAndStartUp();
- // };
- // GlobalEventCenter.ins.onGameSceneDestroy += () => {
- // needModularAwake.Unlock();
- // CheckAndStartUp();
- // };
- // GlobalEventCenter.ins.onSimulateMouseAwakeChanged += (waked) => {
- // if (waked) needModularAwake.Lock();
- // else needModularAwake.Unlock();;
- // CheckAndStartUp();
- // };
- // GlobalEventCenter.ins.onDeviceCalibrateViewAwakeChanged += (waked) => {
- // if (waked) needModularAwake.Lock();
- // else needModularAwake.Unlock();;
- // CheckAndStartUp();
- // };
- //暂时关闭自动休眠,默认是需要模块保持激活
- needModularAwake.Lock();
- }
- void InitWhenConenct()
- {
- canAutoDormancy = true;
- List<string> cmds = new List<string>();
- cmds.Add("M"); //获取Mac地址
- cmds.Add("I"); //获取设备信息
- cmds.Add("b"); //确保开启stm32
- cmds.Add("b"); //获取初始电量
- cmds.Add("1"); //开启发送逻辑
- Action onComplete = null;
- if (needModularAwake.IsLocked())
- {
- cmds.Add("w"); //红外灯开启
- cmds.Add("3"); //九轴开启
- onComplete = () =>
- {
- isStartUp = true;
- };
- }
- else
- {
- cmds.Add("s"); //红外灯关闭
- cmds.Add("S"); //Stm32关闭
- cmds.Add("4"); //九轴关闭
- onComplete = () =>
- {
- isStartUp = false;
- };
- }
- SendCDM(null, onComplete, cmds.ToArray());
- }
- void DestroyWhenDisconenct()
- {
- canAutoDormancy = false;
- sendCMD_CheckAndDoStop(null);
- }
- //启动
- void StartUp()
- {
- SendCDM(() =>
- {
- return !isStartUp;
- }, () =>
- {
- isStartUp = true;
- }, "b", "w", "3");
- }
- //休眠
- void Dormancy()
- {
- SendCDM(() =>
- {
- return isStartUp;
- }, () =>
- {
- isStartUp = false;
- }, "4", "s", "S");
- }
- void SendCDM(Func<bool> canDo, Action onComplete, params string[] cmds)
- {
- CmdToSend cmdToSend = new CmdToSend(cmds, onComplete, canDo);
- if (isSendCmdLocked)
- {
- cmdWaitingList.Enqueue(cmdToSend);
- return;
- }
- sendCMD_NotCheck(cmdToSend);
- }
- void sendCMD_NotCheck(CmdToSend cmdToSend)
- {
- if (cmdToSend.canDo != null && !cmdToSend.canDo.Invoke())
- {
- sendCMD_CheckNext();
- return;
- }
- isSendCmdLocked = true;
- Sequence sequence = DOTween.Sequence();
- sequence.PrependInterval(0.3f);
- foreach (var cmd in cmdToSend.cmds)
- {
- sequence.AppendCallback(() =>
- {
- bool stopped = sendCMD_CheckAndDoStop(sequence);
- if (!stopped) WriteData(cmd);
- });
- sequence.AppendInterval(0.5f);
- }
- sequence.AppendCallback(() =>
- {
- bool stopped = sendCMD_CheckAndDoStop(sequence);
- if (!stopped)
- {
- isSendCmdLocked = false;
- cmdToSend.onComplete?.Invoke();
- sendCMD_CheckNext();
- }
- });
- sequence.SetUpdate(true);
- }
- void sendCMD_CheckNext()
- {
- if (cmdWaitingList.Count <= 0) return;
- CmdToSend cmdToSend = cmdWaitingList.Dequeue();
- sendCMD_NotCheck(cmdToSend);
- }
- bool sendCMD_CheckAndDoStop(Sequence sequence)
- {
- if (canAutoDormancy) return false;
- isStartUp = false;
- isSendCmdLocked = false;
- cmdWaitingList.Clear();
- if (sequence != null) sequence.Kill();
- return true;
- }
- #endregion
- public void RequestBattery()
- {
- if (!isStartUp) return;
- if (isSendCmdLocked) return;
- WriteData("b");
- }
- /// <summary>
- /// 获取设备信息 手枪、HOUYI Pro 和 ARTEMIS Pro
- /// </summary>
- public void RequestDeviceInfo()
- {
- if (isSendCmdLocked) return;
- WriteData("I");
- }
- /// <summary>
- /// 旧的红外射箭指令
- /// </summary>
- public void ReplyInfraredShoot()
- {
- if (isSendCmdLocked) return;
- WriteData("I");
- }
- void CallDelay(float delayTime, TweenCallback callback)
- {
- Sequence sequence = DOTween.Sequence();
- sequence.PrependInterval(delayTime).AppendCallback(callback);
- sequence.SetUpdate(true);
- }
- public void WriteData(string data)
- {
- //Debug.Log("WriteData:" + data);
- #if UNITY_STANDALONE_WIN || UNITY_EDITOR
- //BleUDP.ins.SendMsg(data);
- firstBluetoothWindows.Write(data);
- #else
- if (DebugDeviceCMD.ins) DebugDeviceCMD.ins.ShowCMD(data);
- BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristicWrite.getName());
- ch.setService(bluetoothService.getName());
- bluetoothHelper.WriteCharacteristic(ch, data);
- #endif
- }
- public void WriteByteData(byte[] data)
- {
- #if UNITY_STANDALONE_WIN || UNITY_EDITOR
- firstBluetoothWindows.WriteByte(data);
- #else
- BluetoothHelperCharacteristic ch = new BluetoothHelperCharacteristic(characteristicWrite.getName());
- ch.setService(bluetoothService.getName());
- bluetoothHelper.WriteCharacteristic(ch, data);
- #endif
- }
- void Log(string text)
- {
- if (textUI)
- {
- textUI.text = text;
- }
- Debug.Log(string.Format("[{0}]{1}", typeof(BluetoothAim).Name, text));
- }
- [NonSerialized] public string curMac;
- void UploadMacAddress(byte[] bytes)
- {
- string mac = System.Text.Encoding.ASCII.GetString(bytes);
- if (mac != null) mac = mac.Trim();
- if (CheckIsMacValid(mac))
- {
- SideTipView.ShowTip("Mac获取成功:" + mac, Color.white);
- //需要增加一个判断,判断是否对应的mac设备。不是需要进行重新连接
- if (!AimHandler.ins.aimDeviceInfo.bInitMac)
- {
- Debug.Log("设置设备mac:" + mac);
- AimHandler.ins.SetAimDeviceMac(mac);
- }
- else if (AimHandler.ins.aimDeviceInfo.mac != mac)
- {
- Debug.Log("设备不一样,断开连接");
- DoConnect();
- //延迟一点时间后重新触发扫描
- CallDelay(4, () =>
- {
- Debug.Log("CallDelay 重新连接");
- DoConnect();
- });
- return;
- }
- curMac = mac;
- LoginMgr.myUserInfo.mac = mac;
- UserComp.Instance.saveMac();
- }
- //else {
- // SideTipView.ShowTip("Mac获取失败", Color.yellow);
- //}
-
- }
- bool CheckIsMacValid(string mac)
- {
- if (mac == null) return false;
- if (!mac.StartsWith("{")) return false;
- if (!mac.EndsWith("}")) return false;
- if (!mac.Contains(":")) return false;
- char[] validChars = { '{', '}', ':', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
- foreach (var c in mac.ToCharArray())
- {
- if (Array.IndexOf(validChars, c) == -1) return false;
- }
- if (mac.Length != 19) return false;
- string macNoneFrame = mac.Substring(1, mac.Length - 2);
- string[] macNoneFrameSplits = macNoneFrame.Split(':');
- if (macNoneFrameSplits.Length != 6) return false;
- foreach (var item in macNoneFrameSplits)
- {
- if (item.Length != 2) return false;
- foreach (var c in item.ToCharArray())
- if (Array.IndexOf(validChars, c) < 3) return false;
- }
- return true;
- }
- #region 2p蓝牙部分,使用了SmartBowSDK
- //2p蓝牙连接 使用 SmartBowSDK
- SmartBowHelper smartBowHelper2P;
- //陀螺仪校准进度
- public int smartBowHelper2_Progress { get => (int)(smartBowHelper2P.GetGyrProgress() * 100); }
- bool doConnect2P = false;
- bool userDoConnect2P = false;
- int _scanCanRetryCount2P = 4;
- bool canConnect2P = true;
- public bool bNoNeedToReconnect { get; set; } = true;//是否需要重连
- bool lerpForRotation2P = true;
- float lerpTimeRate2P = 7;
- private Quaternion newRotation2P = Quaternion.identity;
- //数据存储标识
- string userTags = "smartbow";
- int deviceId2 = 2;
- public void onCreateSmartBowHelper2P()
- {
- smartBowHelper2P = SmartBowHelper.NewInstance();
- smartBowHelper2P.SetFilters(targetDeviceName2P);
- smartBowHelper2P.OnBluetoothModuleInited += () =>
- {
- Debug.Log("OnBluetoothModuleInited");
- //判断是否是同一个mac
- //需要增加一个判断,判断是否对应的mac设备。不是需要进行重新连接
- string mac = smartBowHelper2P.GetMacAddress();
- if (!AimHandler.ins.aimDeviceInfo.bInitMac)
- {
- Debug.Log("smartBowHelper2P 设置设备mac:" + mac);
- AimHandler.ins.SetAimDeviceMac(mac);
- }
- else if (AimHandler.ins.aimDeviceInfo.mac != mac)
- {
- Debug.Log("设备不一样,断开连接");
- DoConnect2P();
- //延迟一点时间后重新触发扫描
- CallDelay(4, () =>
- {
- Debug.Log("CallDelay 重新连接");
- DoConnect2P();
- });
- return;
- }
- UpdateConnectText();
- smartBowHelper2P.StartRotationSensor();
- smartBowHelper2P.StartShootingSensor();
- //if (SB_EventSystem.ins)
- //{
- // //唤起/隐藏虚拟鼠标
- // SB_EventSystem.ins.AwakenSimulateMouse();
- //}
- };
- smartBowHelper2P.OnBluetoothError += (error, message) =>
- {
- Debug.Log("smartBowHelper2P error:" + error);
- if (error == BluetoothError.ScanNotFoundTargetDevice)
- {
- scanLock = false;
- PopupMgr.ins.ShowTip("连接失败,未发现目标设备!");
- if (_scanCanRetryCount2P > 0)
- {
- _scanCanRetryCount2P--;
- scanLock = true;
- ConnectSmartBowHelper2P();
- }
- else
- {
- userDoConnect2P = false;
- canConnect2P = true;
- Log("没有发现设备");
- TextAutoLanguage2.GetTextByKey("ble-dev-notfound");
- }
- return;
- }
- PopupMgr.ins.ShowTip(message);
- };
- smartBowHelper2P.OnBluetoothStatusChanged += (oldStatus, newStatus) =>
- {
- UpdateConnectText();
- };
- smartBowHelper2P.OnRotationUpdate += (r) =>
- {
- newRotation2P = r;
- //GameController.ins.aimCrossHairs[playerIndex].UpdatePositionByModuleRotation(r);
- //if (SB_EventSystem.ins && SB_EventSystem.ins.simulateMouseIsAwaked) SB_EventSystem.ins.MoveSimulateMouse(r);
- };
- smartBowHelper2P.OnShooting += OnShot2P;
- smartBowHelper2P.OnFunctionKeyPress += () =>
- {
- //如果是双人场景,触发提示
- if (SceneManager.GetActiveScene().name == "GameDouble")
- {
- if (GameObject.Find("AutoResetViewNewRight")) return;
- GameObject resetView = Instantiate(Resources.Load<GameObject>("AutoResetViewNew"));
- resetView.name = "AutoResetViewNewRight";
- AutoResetViewNew autoResetViewNewScript = resetView.GetComponent<AutoResetViewNew>();
- autoResetViewNewScript.setTextKey("new-user-guider_tip_视角归位-瞄准-infraredD");
- autoResetViewNewScript.setPosRight();
- autoResetViewNewScript.action_OnDestroy += () =>
- {
- smartBowHelper2P.ResetAim();
- };
- }
- else if (SceneManager.GetActiveScene().name == "InfraredGameDouble" || SceneManager.GetActiveScene().name == "WildAttackDouble")
- {
- if (GameObject.Find("AutoResetViewNewRight")) return;
- GameObject resetView = Instantiate(Resources.Load<GameObject>("AutoResetViewNew"));
- resetView.name = "AutoResetViewNewRight";
- AutoResetViewNew autoResetViewNewScript = resetView.GetComponent<AutoResetViewNew>();
- autoResetViewNewScript.setTextKey("new-user-guider_tip_视角归位-瞄准-infraredD");
- autoResetViewNewScript.setPosRight();
- autoResetViewNewScript.action_OnDestroy += () =>
- {
- if (SceneManager.GetActiveScene().name == "InfraredGameDouble")
- {
- InfraredDemo._ins?.SetAdjustPointsOffset(PlayerType.SecondPlayer);
- }
- else if (SceneManager.GetActiveScene().name == "WildAttackDouble")
- {
- WildAttack.GameMananger.GetInstance().ResetAim(WildAttack.PlayerTypeEnum.Second);
- }
- };
- }
- //else if (SceneManager.GetActiveScene().name.Equals("WildAttackDouble"))
- //{
- // //双人场景直接校准2P
- // WildAttack.GameMananger.GetInstance().ResetAim(WildAttack.PlayerTypeEnum.Second);
- //}
- else
- {
- smartBowHelper2P.ResetAim();
- }
- };
- //#if UNITY_STANDALONE_WIN || UNITY_EDITOR
- // //用户2window连接 BluetoothWindows.IsWindows() &&
- // if (currentBLEPlayer == BluetoothPlayer.SECONDE_PLAYER)
- // {
- // Debug.Log("SECONDE_PLAYER BleWinHelper.RegisterTo");
- // BleWinHelper com = BleWinHelper.RegisterTo(smartBowHelper2P.gameObject, smartBowHelper2P.CreateBluetoothWindows(), "2P");
- // }
- //#endif
- }
- void OnShot2P(float speed)
- {
- if (SceneManager.GetActiveScene().name.Equals("WildAttackDouble"))
- {
- WildAttack.SmartBowController.Instance.OnShooting2P(speed);
- }
- else
- {
- if (GameController.ins.GetArmBowDoublePlayer(PlayerType.SecondPlayer) != null)
- {
- //本地双人模式下处理2P ,1P在 ShootCheck 类处理
- GameController.ins.GetArmBowDoublePlayer(PlayerType.SecondPlayer).ADS_fire(true, speed);
- }
- }
- }
- void UpdateConnectText()
- {
- var newStatus = smartBowHelper2P.GetBluetoothStatus();
- if (newStatus == SmartBowSDK.BluetoothStatusEnum.None)
- {
- if (GameController.ins)
- {
- GameController.ins.GetBowCameraDoublePlayer(PlayerType.SecondPlayer).isTouchMode = true;
- }
- Debug.Log("<color=blue>未连接</color>(点击连接)");
- if (!bNoNeedToReconnect) return;
- scanLock = false;
- if (_scanCanRetryCount2P > 0)
- {
- _scanCanRetryCount2P--;
- scanLock = true;
- ConnectSmartBowHelper2P();
- }
- else
- {
- userDoConnect2P = false;
- canConnect2P = true;
- Log("没有发现设备");
- PopupMgr.ins.ShowTip("连接失败,未发现目标设备!");
- TextAutoLanguage2.GetTextByKey("ble-dev-notfound");
- }
- }
- else if (newStatus == SmartBowSDK.BluetoothStatusEnum.Connecting)
- {
- Debug.Log("<color=#FF670D>连接中</color>");
- if (GameController.ins)
- {
- GameController.ins.GetBowCameraDoublePlayer(PlayerType.SecondPlayer).isTouchMode = false;
- }
- }
- else if (newStatus == SmartBowSDK.BluetoothStatusEnum.Connected)
- {
- if (GameController.ins)
- {
- GameController.ins.GetBowCameraDoublePlayer(PlayerType.SecondPlayer).isTouchMode = false;
- }
- if (smartBowHelper2P.IsBluetoothModuleInited()) Debug.Log("<color=green>已连接</color>(点击断开)");
- else Debug.Log("<color=green>已连接</color><color=blue>(正在初始化)</color>");
- }
- }
- public void ConnectSmartBowHelper2P()
- {
- //#if UNITY_ANDROID
- // PopupMgr.ins.ClearAllTip();
- // if (BluetoothHelperAndroid.IsBluetoothEnabled() == false)
- // {
- // HandleConnectException(TextAutoLanguage2.GetTextByKey("ble-exception1"));
- // return;
- // }
- // if (BluetoothHelperAndroid.RequestBluetoothPermissions(ConnectSmartBowHelper2P, (permission) => {
- // if (permission.Contains("LOCATION"))
- // {
- // HandleConnectException(TextAutoLanguage2.GetTextByKey("ble-exception2"));
- // }
- // else if (permission.Contains("BLUETOOTH"))
- // {
- // HandleConnectException(TextAutoLanguage2.GetTextByKey("ble-exception3"));
- // }
- // })) return;
- //#endif
- if (smartBowHelper2P == null)
- {
- onCreateSmartBowHelper2P();
- CallDelay(1, () =>
- {
- smartBowHelper2P.Connect(userTags, deviceId2, true);//不在sdk 判断mac
- });
- }
- else
- {
- smartBowHelper2P.Connect(userTags, deviceId2, true);
- }
- }
- public void DoConnect2P()
- {
- Debug.Log("DoConnect2P");
- if (smartBowHelper2P == null || smartBowHelper2P.GetBluetoothStatus() == SmartBowSDK.BluetoothStatusEnum.None)
- {
- //connectCanceled = false;
- userDoConnect2P = true;
- doConnect2P = true;
- bNoNeedToReconnect = true;
- Connect2P();
- }
- else if (smartBowHelper2P.GetBluetoothStatus() == SmartBowSDK.BluetoothStatusEnum.Connected)
- {
- userDoConnect2P = false;
- doConnect2P = false;
- canConnect2P = true;
- DisconnectSmartBowHelper2P();
- }
- }
- void Connect2P()
- {
- //if (BluetoothShoot.scanLock)
- //{
- // return;
- //}
- if (!canConnect2P)
- {
- return;
- }
- doConnect = false;
- doConnect2P = false;
- scanLock = true;
- canConnect2P = false;
- _scanCanRetryCount2P = 4;
- //SetStatus2P(BluetoothStatusEnum.Connecting);
- ConnectSmartBowHelper2P();
- }
- //初始化陀螺仪
- public void OnCalibrateGyr2P()
- {
- if (smartBowHelper2P.IsGyrCalibrating()) smartBowHelper2P.StopGyrCalibration();
- else smartBowHelper2P.StartGyrCalibration();
- }
- //初始化地磁计
- public void OnCalibrateMag2P()
- {
- smartBowHelper2P.StartMagCalibration();
- }
- #endregion
- #region 当前选择操作的设备 如1p或者2p
- public SmartBowHelper getSmartBowHelper2P()
- {
- return smartBowHelper2P;
- }
- public void setBLEPlayer(BluetoothPlayer blePlayer)
- {
- //切换蓝牙用户时候,判断是否正在连接,如果正在匹配连接的话,取消连接状态
- if (blePlayer != currentBLEPlayer)
- {
- Debug.Log("Set BluetoothPlayer status:" + status);
- onCancelAllConnecting();
- }
- currentBLEPlayer = blePlayer;
- Debug.Log("Set BluetoothPlayer:" + currentBLEPlayer);
- }
- public BluetoothPlayer getBLEPlayer()
- {
- //Debug.Log("Get BluetoothPlayer:" + currentBLEPlayer);
- return currentBLEPlayer;
- }
- //更新跟随点位置
- public void UpdateCameraToLookNewPoint2P()
- {
- if (SceneManager.GetActiveScene().name != "InfraredGameDouble")
- {
- if (CameraToLookNew.ins != null)
- {
- Transform m_controlObj = CameraToLookNew.ins.transform;
- if (lerpForRotation2P)
- m_controlObj.localRotation = Quaternion.Lerp(m_controlObj.localRotation, newRotation2P, Time.deltaTime * lerpTimeRate2P);
- else
- m_controlObj.localRotation = newRotation2P;
- }
- }
- }
- public int get2PBattery()
- {
- return smartBowHelper2P == null ? 0 : smartBowHelper2P.GetBattery();
- }
- //主更新调用
- void updateSmartBowHelper2P()
- {
- UpdateCameraToLookNewPoint2P();
- }
- #endregion
- //取消正在连接的连接
- public void onCancelAllConnecting(BluetoothStatusEnum _bluetoothStatus = BluetoothStatusEnum.ConnectFail)
- {
- // status != BluetoothStatusEnum.ConnectSuccess
- Debug.LogWarning("onCancelAllConnecting 1:" + status);
- #if UNITY_STANDALONE_WIN || UNITY_EDITOR
- //BleUDP.ins != null
- //BluetoothWindows.IsWindows() &&
- if (status == BluetoothStatusEnum.Connecting)
- {
- //Debug.LogWarning("onCancelAllConnecting 2:" + status);
- userDoConnect = false;
- doConnect = false;
- OnDisconnect();
- // BleUDP.ins.Disconnect();
- firstBluetoothWindows.Disconnect();
- SetStatus(_bluetoothStatus);
- Debug.LogWarning("onCancelAllConnecting 3:" + status);
- }
- #else
- if (bluetoothHelper != null && status == BluetoothStatusEnum.Connecting)
- {
- Debug.LogWarning("onCancelAllConnecting 2:" + status);
- userDoConnect = false;
- doConnect = false;
- OnDisconnect();
- DisconnectBleHelper();
- SetStatus(_bluetoothStatus);
- }
- #endif
- //smartBowHelper2P.GetBluetoothStatus() != SmartBowSDK.BluetoothStatusEnum.Connected
- if (smartBowHelper2P != null && smartBowHelper2P.GetBluetoothStatus() == SmartBowSDK.BluetoothStatusEnum.Connecting)
- {
- userDoConnect2P = false;
- doConnect2P = false;
- canConnect2P = true;
- DisconnectSmartBowHelper2P();
- //smartBowHelper2P.Disconnect();
- Debug.Log("onCancelAllConnecting smartBowHelper2P 2:" + smartBowHelper2P.GetBluetoothStatus());
- }
- }
- #region 判断是否是1p设备连接的是HOUYIPRO信息
- public bool isMainConnectToHOUYIPRO()
- {
- bool _isHOUYIPRO = false;
- foreach (AimDeviceInfo p in AimHandler.ins.aimDeviceInfos.arry)
- {
- if ((int)BluetoothPlayer.FIRST_PLAYER == p.id && p.type == (int)AimDeviceType.HOUYIPRO)
- {
- _isHOUYIPRO = true;
- }
- }
- if (_isHOUYIPRO)
- {
- if (CommonConfig.bDisableBluetooth)
- {
- return true;
- }
- else
- {
- //如果是。判断是否连接
- return status == BluetoothStatusEnum.ConnectSuccess;
- }
- }
- else
- {
- return false;
- }
- }
- #endregion
- #region 判断是否是1p设备连接的是ARTEMISPRO信息
- public bool isMainConnectToARTEMISPRO()
- {
- bool _isARTEMISPRO = false;
- foreach (AimDeviceInfo p in AimHandler.ins.aimDeviceInfos.arry)
- {
- if ((int)BluetoothPlayer.FIRST_PLAYER == p.id && p.type == (int)AimDeviceType.ARTEMISPRO)
- {
- _isARTEMISPRO = true;
- }
- }
- if (_isARTEMISPRO)
- {
- if (CommonConfig.bDisableBluetooth)
- {
- return true;
- }
- else
- {
- //如果是。判断是否连接
- return status == BluetoothStatusEnum.ConnectSuccess;
- }
- }
- else
- {
- return false;
- }
- }
- #endregion
- #region 判断是否是1p设备连接的是红外信息,有多种红外设备
- public bool isMainConnectToInfraredDevice()
- {
- bool _isInfraredDevice = false;
- foreach (AimDeviceInfo p in AimHandler.ins.aimDeviceInfos.arry)
- {
- if ((int)BluetoothPlayer.FIRST_PLAYER == p.id && (p.type == (int)AimDeviceType.ARTEMISPRO || p.type == (int)AimDeviceType.HOUYIPRO))
- {
- _isInfraredDevice = true;
- }
- }
- if (_isInfraredDevice)
- {
- if (CommonConfig.bDisableBluetooth)
- {
- return true;
- }
- else
- {
- //如果是。判断是否连接
- return status == BluetoothStatusEnum.ConnectSuccess;
- }
- }
- else
- {
- return false;
- }
- }
- #endregion
- #region 判断是否是1p设备连接的是Gun信息
- public bool isMainConnectToGun()
- {
- bool _isGun = false;
- foreach (AimDeviceInfo p in AimHandler.ins.aimDeviceInfos.arry)
- {
- if ((int)BluetoothPlayer.FIRST_PLAYER == p.id && (p.type == (int)AimDeviceType.Gun || p.type == (int)AimDeviceType.PistolM17 || p.type == (int)AimDeviceType.RifleM416))
- {
- _isGun = true;
- }
- }
- if (_isGun)
- {
- if (CommonConfig.bDisableBluetooth)
- {
- return true;
- }
- else
- {
- //如果是。判断是否连接
- return status == BluetoothStatusEnum.ConnectSuccess;
- }
- }
- else
- {
- return false;
- }
- }
- /// <summary>
- /// 获取连接枪的类型
- /// </summary>
- /// <returns></returns>
- public (bool isGun, AimDeviceType gunType) isMainConnectToGunType()
- {
- bool _isGun = false;
- AimDeviceType aimDeviceType = AimDeviceType.NONE;
- foreach (AimDeviceInfo p in AimHandler.ins.aimDeviceInfos.arry)
- {
- if ((int)BluetoothPlayer.FIRST_PLAYER == p.id && (p.type == (int)AimDeviceType.Gun || p.type == (int)AimDeviceType.PistolM17 || p.type == (int)AimDeviceType.RifleM416))
- {
- _isGun = true;
- aimDeviceType = (AimDeviceType)p.type;
- }
- }
- if (_isGun)
- {
- if (CommonConfig.bDisableBluetooth)
- {
- return (true, aimDeviceType);
- }
- else
- {
- //如果是。判断是否连接
- return (status == BluetoothStatusEnum.ConnectSuccess, aimDeviceType);
- }
- }
- else
- {
- return (false, aimDeviceType);
- }
- }
- #endregion
- /// <summary>
- /// 设置设备类型
- /// </summary>
- public void SetMainConnectDeviceType()
- {
- //1号玩家连接蓝牙成功时候,设置一次 GlobalData.MyDeviceMode
- foreach (AimDeviceInfo p in AimHandler.ins.aimDeviceInfos.arry)
- {
- if ((int)BluetoothPlayer.FIRST_PLAYER == p.id)
- {
- if (p.type == (int)AimDeviceType.Gun || p.type == (int)AimDeviceType.PistolM17 || p.type == (int)AimDeviceType.RifleM416)
- {
- //设置枪
- HomeView.ins.MyTopBarView.onChangeType(1);
- }
- else
- {
- //其余默认是弓箭
- HomeView.ins.MyTopBarView.onChangeType(0);
- }
- }
- }
- }
- #region 用户1 window ble 连接和部分共用代码
- void OnConnected_windows1()
- {
- Log("[WinBle_1P]连接成功\n" + deviceName);
- SetStatus(BluetoothStatusEnum.ConnectSuccess);
- BowCamera.isTouchMode = false;
- if (CommonConfig.EnableDecryption && NeedDecryption)
- {
- // 这里验证指令,开始请求授权
- // 启动轮询协程
- StartCoroutine(PollingCoroutine());
- }
- else
- {
- //除了pc,Android 直接连接
- InitWhenConenct();
- }
- }
- void OnConnectionFailed_windows1()
- {
- Log("连接失败\n" + deviceName);
- OnDisconnect();
- }
- void OnCharacteristicChanged_windows1(string deviceId, byte[] value)
- {
- OnCharacteristicChanged(null, value, null);
- }
- void OnCharacteristicChanged(BluetoothHelper helper, byte[] value, BluetoothHelperCharacteristic characteristic)
- {
- if (status != BluetoothStatusEnum.ConnectSuccess) return;
- if (!hasData)
- {
- hasData = true;
- hasDataTime = JCUnityLib.TimeUtils.GetTimestamp();
- }
- if (CommonConfig.EnableDecryption && NeedDecryption)
- {
- //Pc 版本先走校验流程
- if (!BluetoothDecryptor.AUTHOR_IsDecrypt())
- {
- if (value[0] == 0x5a)
- {
- // 从硬件读取数据
- if (value != null && value.Length > 0)
- {
- Debug.Log("接收到数据:" + BitConverter.ToString(value));
- BluetoothDecryptor.AUTHOR_Decrypt(value);
- if (BluetoothDecryptor.AUTHOR_IsDecrypt())
- {
- Debug.Log("解密成功!");
- //解密成功后
- StopEncrypt();
- //开始连接其他信息
- InitWhenConenct();
- }
- else
- {
- Debug.Log("解密失败!");
- //SideTipView.ShowTip("设备通信失败,断开连接", Color.yellow);
- //断开连接等操作
- if (PollingCoroutineCount <= 0)
- {
- StopEncrypt();
- DoConnect();
- }
- }
- }
- }
- return;
- }
- }
- dataCount++;
- if (curMac == null && dataCount < 500)
- {
- UploadMacAddress(value);
- }
- byte[] bytes = value;
- // Log(String.Join(",", bytes));
- BluetoothClient.UploadData(0, bytes);
- if (AimHandler.ins)
- {
- AimHandler.ins.OnDataReceived(bytes);
- }
- }
- #endregion
- #region 管理部分监听通信
- /// <summary>
- /// 监听枪状态
- /// </summary>
- public BleDeviceEvent OnBleDeviceState;
- /// <summary>
- /// 硬件对应的事件
- /// </summary>
- public delegate void BleDeviceEvent(BluetoothDeviceType bleDeviceType, BluetoothDeviceStatus gunStatusEnum);
- internal void InvokeOnBleDevice(BluetoothDeviceType bleDeviceType, BluetoothDeviceStatus gunStatusEnum)
- {
- try
- {
- OnBleDeviceState?.Invoke(bleDeviceType, gunStatusEnum);
- }
- catch (Exception e)
- {
- Debug.LogError(e);
- }
- }
- /// <summary>
- /// 记录硬件反馈的设备状态和连接的设备平台信息
- /// </summary>
- public BluetoothDeviceType myBluetoothDeviceType = BluetoothDeviceType.NONE;
- public ConnectPlatform myConnectPlatform = ConnectPlatform.NONE;
- /// <summary>
- /// 监听设备状态和连接的设备平台信息
- /// </summary>
- public DeviceAndSystemInfoEvent OnDeviceAndSystemInfoEvent;
- /// <summary>
- /// 硬件对应的事件初始化回调
- /// </summary>
- public delegate void DeviceAndSystemInfoEvent(ConnectPlatform connectPlatform, BluetoothDeviceType bleDeviceType);
- internal void InvokeOnDeviceAndSystemInfoEvent(ConnectPlatform connectPlatform, BluetoothDeviceType bleDeviceType)
- {
- try
- {
- myConnectPlatform = connectPlatform;
- myBluetoothDeviceType = bleDeviceType;
- OnDeviceAndSystemInfoEvent?.Invoke(connectPlatform, bleDeviceType);
- }
- catch (Exception e)
- {
- Debug.LogError(e);
- }
- }
- /// <summary>
- /// 获取一次当前记录的信息
- /// </summary>
- public void GetDeviceAndSystemInfoEvent() {
- OnDeviceAndSystemInfoEvent?.Invoke(myConnectPlatform, myBluetoothDeviceType);
- }
- /// <summary>
- /// 返回一个存储用户的新手教程字符串
- /// </summary>
- /// <returns></returns>
- public string GetInfraredGuiderKey() {
- return $"hideInfraredGuider-{LoginMgr.myUserInfo.id}-{myBluetoothDeviceType}";
- }
- /// <summary>
- /// 清除当前红外记录的存储的所有key内容
- /// </summary>
- public void ClearAllInfraredGuider() {
- int userId = LoginMgr.myUserInfo.id;
- foreach (BluetoothDeviceType type in Enum.GetValues(typeof(BluetoothDeviceType)))
- {
- string key = $"hideInfraredGuider-{userId}-{type}";
- PlayerPrefs.DeleteKey(key);
- }
- PlayerPrefs.Save();
- }
- #endregion
- }
|