| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112 |
- using ArduinoBluetoothAPI;
- using System;
- using UnityEngine;
- using System.Collections.Generic;
- using UnityEngine.UI;
- using DG.Tweening;
- using SmartBowSDK;
- /* 蓝牙瞄准模块 */
- /* 管理1p和2p蓝牙连接,脚本外调用逻辑如果同时连接1p和2p设备,以前的逻辑还是以1p为主,如果只连2p,则使用2p数据*/
- public class BluetoothAim : MonoBehaviour
- {
- #region 弓箭蓝牙模块基本信息
- readonly string targetDeviceName = "Bbow_20210501 | HOUYI Pro";
- readonly string targetDeviceNameHOUYIPro = "HOUYI Pro";
- 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;
- void Start()
- {
- ins = this;
- InitAutoDormancy();
- #if UNITY_STANDALONE_WIN || UNITY_EDITOR
- new GameObject("BleUDP").AddComponent<BleUDP>();
- #endif
- }
- void OnDestroy()
- {
- //删除ble。1p,2p 都删除
- DisconnectBleHelper();
- DisconnectSmartBowHelper2P();
- }
- 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();
- #if UNITY_STANDALONE_WIN || UNITY_EDITOR
- BleUDP.ins.Disconnect();
- #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 (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();
- #else
- ConnectBleHelper();
- #endif
- }
- int _scanCanRetryCount = 4;
- void ConnectBleHelper()
- {
- #if UNITY_ANDROID
- PopupMgr.ins.ClearAllTip();
- if (BluetoothHelperAndroid.IsBluetoothEnabled() == false)
- {
- HandleConnectException(TextAutoLanguage2.GetTextByKey("ble-exception1"));
- return;
- }
- if (BluetoothHelperAndroid.RequestBluetoothPermissions(ConnectBleHelper, (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);
- 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);
- 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) =>
- {
- if (status != BluetoothStatusEnum.ConnectSuccess) return;
- // logger.Log(String.Join(",", value));
- 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);
- }
- };
- 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 (device.DeviceName == targetDeviceName)
- if (targetDeviceName.Contains(device.DeviceName))
- {
- deviceName = device.DeviceName;
- bluetoothHelper.setDeviceName(deviceName);
- bluetoothHelper.Connect();
- Log("匹配设备 " + 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"));
- }
- }
- void HandleConnectException(string errorText)
- {
- scanLock = false;
- canConnect = true;
- // SetStatus(BluetoothStatusEnum.ConnectFail);
- status = BluetoothStatusEnum.Connect;
- userDoConnect = false;
- PopupMgr.ins.ShowTip(errorText);
- }
- 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("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");
- }
- 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);
- #else
- if (DebugDeviceCMD.ins) DebugDeviceCMD.ins.ShowCMD(data);
- 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;
- bool lerpForRotation2P = true;
- float lerpTimeRate2P = 7;
- private Quaternion newRotation2P = Quaternion.identity;
- //数据存储标识
- string userTags = "smartbow";
- int deviceId2 = 2;
- public void onCreateSmartBowHelper2P() {
- smartBowHelper2P = SmartBowHelper.NewInstance();
-
- 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 (UnityEngine.SceneManagement.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.setPosRight();
- autoResetViewNewScript.action_OnDestroy += () =>
- {
- smartBowHelper2P.ResetAim();
- };
- }
- else {
- smartBowHelper2P.ResetAim();
- }
-
- };
- //window蓝牙连接
- if (currentBLEPlayer == BluetoothPlayer.SECONDE_PLAYER && BluetoothWindows.IsWindows()) {
- Debug.Log(" BleWinHelper.RegisterTo");
- BleWinHelper.RegisterTo(smartBowHelper2P.gameObject);
- }
-
- }
- void OnShot2P(float speed)
- {
- 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>(点击连接)");
- 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, () =>
- {
- Debug.Log("Connect*********");
- 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;;
- 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 (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
- if (BleUDP.ins != null && status == BluetoothStatusEnum.Connecting)
- {
- //Debug.LogWarning("onCancelAllConnecting 2:" + status);
- userDoConnect = false;
- doConnect = false;
- OnDisconnect();
- BleUDP.ins.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)
- {
- //如果是。判断是否连接
- 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)
- {
- _isGun = true;
- }
- }
- if (_isGun)
- {
- //如果是。判断是否连接
- return status == BluetoothStatusEnum.ConnectSuccess;
- }
- else
- {
- return false;
- }
- }
- #endregion
- }
|