using System;
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;
using DG.Tweening;
using SmartBowSDK;
using System.Collections;
using UnityEngine.SceneManagement;
using SmartBowSDK.CMD;
using AppUI.Manager.View;
using AppUI.View.Home.Main;
using UHomeView = AppUI.View.Home.Main.HomeView;
using SdkAimDeviceInfo = SmartBowSDK.AimDeviceInfo;
namespace AppUI.Bluetooth
{
/* 蓝牙瞄准模块(AppUI) */
/* 1P/2P 连接与 CompanionDeviceManager(CMD)统一经 SmartBowHelper → SDK,AppUI 不维护 CMDManager */
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 targetDeviceNameARTEMISPro = "ARTEMIS Pro | Bbow_20210501";
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";
#endregion
//当前选择的设备
BluetoothPlayer currentBLEPlayer = BluetoothPlayer.FIRST_PLAYER;
#region 1p蓝牙使用的是sdk
//1p蓝牙连接 使用 SmartBowSDK
SmartBowHelper smartBowHelper1P;
string userTags1P = "smartbow";
int deviceId1P = 1;
int _scanCanRetryCount1P = 4;
#endregion
string deviceName = "";
bool canConnect = true;
[SerializeField] Text textUI;
public BluetoothStatusEnum status = BluetoothStatusEnum.Connect;
public bool hasData = false;
public long hasDataTime;
public static bool scanLock = false; //防止同时扫描冲突
//根据设备情况来看是否需要解密,目前就是枪需要进行解密操作
public bool NeedDecryption = false;
AimHandler DeviceAim => SmartBowDeviceHub.ins?.Aim;
//首页初始化时候调用一次连接
public bool bStartConnect = false;
bool _suppressHomeAutoConnect;
/// DeviceView 手动选型/侧滑连接期间为 true,跳过 HomeView 延迟自动连接。
public void SetSuppressHomeAutoConnect(bool suppress) => _suppressHomeAutoConnect = suppress;
public bool IsHomeAutoConnectSuppressed => _suppressHomeAutoConnect;
public static void Init() => SmartBowDeviceHub.EnsureReady();
private void Awake()
{
#if UNITY_ANDROID
if (CommonConfig.bUseCMD)
SmartBowLogger.isDebug = true;
#endif
}
void OnDestroy()
{
//删除ble。1p,2p 都删除
DisconnectSmartBowHelper1P();
DisconnectSmartBowHelper2P();
}
///
/// 首页初始化的时候,如果是第一次。尝试连接蓝牙。只进行一次
///
public void HomeViewConnectBLE()
{
if (!UserPlayer.IsLoginReadyForHomeBle())
{
Debug.Log("[初始化自动连接蓝牙] 登录未完成或 AuthLoginMask 显示中,跳过 Home 自动连接");
return;
}
if (_suppressHomeAutoConnect)
{
Debug.Log("[初始化自动连接蓝牙] DeviceView 手动连接中,跳过 Home 自动连接");
return;
}
if (bStartConnect) return;
if (DeviceAim == null) return;
bStartConnect = true;
//当已经连接过一把弓(1P)时,下一次打开 APP,1P 就自动处于连接的状态;用户只要打1.开 APP 和打开模块就可以自动连接,减少连接设备的操作。
Debug.Log("[初始化自动连接蓝牙] 自动开始连接上一次连接的设备 1P?");
DeviceAim.OnGetAimDeviceInfos();
if (DeviceAim.GetAimDeviceInfo(BluetoothPlayer.FIRST_PLAYER) != null)
{
//如果需要连接
if (status != BluetoothStatusEnum.ConnectSuccess)
{
//setBLEPlayer(BluetoothPlayer.FIRST_PLAYER);
Debug.Log("[初始化自动连接蓝牙] 当前选择的操作用户:" + getBLEPlayer());
//DeviceAim.SetAimDeviceSelectIndex(0);
//第一次进入从存储的资料获取 aimDeviceInfo
DeviceAim.onCreateAimDeviceInfoById();
DoConnect();
}
}
}
private bool userDoConnect = false;
private bool doConnect = false;
public Func 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();
DisconnectSmartBowHelper1P();
//#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;
hasData = false;
canConnect = true;
SetStatus(BluetoothStatusEnum.ConnectFail);
BowCamera.isTouchMode = true;
if (DeviceAim != null) DeviceAim.SetMsOldDefault();
DisconnectSmartBowHelper1P();
}
void Update()
{
updateSmartBowHelper2P();
if (userDoConnect && status == BluetoothStatusEnum.Connect)
{
DoConnect();
}
if (doConnect) Connect();
}
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);
}
SmartBowDeviceHub.ins?.NotifyStateChanged();
}
void DisconnectSmartBowHelper1P()
{
DeviceAim?.UnbindSdk1P();
if (smartBowHelper1P != null) smartBowHelper1P.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;
_scanCanRetryCount1P = 4;
SetStatus(BluetoothStatusEnum.Connecting);
ConnectSmartBowHelper1P();
}
#region 1p蓝牙部分,使用了SmartBowSDK
string Get1PDeviceFilterNames()
{
int firstPlayerType = DeviceAim.GetDeviceType(BluetoothPlayer.FIRST_PLAYER);
if (firstPlayerType == (int)AimDeviceType.HOUYIPRO)
return targetDeviceNameHOUYIPro;
if (firstPlayerType == (int)AimDeviceType.ARTEMISPRO)
return targetDeviceNameARTEMISPro;
if (firstPlayerType == (int)AimDeviceType.Gun)
return targetDeviceNameGun;
if (firstPlayerType == (int)AimDeviceType.PistolM17)
return targetDeviceNameGun_M17;
if (firstPlayerType == (int)AimDeviceType.RifleM416)
return targetDeviceNameGun_M416;
return targetDeviceNameAxis;
}
/// CompanionDeviceManager 扫描用:把 "A | B" 转为 (A|B) 正则。
string ToRegex(string names)
{
if (string.IsNullOrEmpty(names))
return "";
var parts = names.Split('|');
for (int i = 0; i < parts.Length; i++)
parts[i] = parts[i].Trim();
return "(" + string.Join("|", parts) + ")";
}
void Apply1PDeviceFilters()
{
string filterNames = Get1PDeviceFilterNames();
SdkAimDeviceInfo firstPlayer = DeviceAim.GetAimDeviceInfo(BluetoothPlayer.FIRST_PLAYER);
if (firstPlayer == null)
{
smartBowHelper1P.SetIsConnectName(true);
smartBowHelper1P.SetConnectMacStr("");
if (smartBowHelper1P.GetUseCompanionDeviceManagerStatus())
smartBowHelper1P.SetFilters(ToRegex(filterNames));
else
smartBowHelper1P.SetFilters(filterNames);
return;
}
if (firstPlayer.bInitMac)
{
smartBowHelper1P.SetIsConnectName(false);
smartBowHelper1P.SetConnectMacStr(firstPlayer.mac);
smartBowHelper1P.SetFilters("");
}
else
{
smartBowHelper1P.SetIsConnectName(true);
smartBowHelper1P.SetConnectMacStr("");
if (smartBowHelper1P.GetUseCompanionDeviceManagerStatus())
smartBowHelper1P.SetFilters(ToRegex(filterNames));
else
smartBowHelper1P.SetFilters(filterNames);
}
}
public void onCreateSmartBowHelper1P()
{
smartBowHelper1P = SmartBowHelper.NewInstance();
#if UNITY_ANDROID
if (CommonConfig.bUseCMD)
{
smartBowHelper1P.UseCompanionDeviceManager(true);
}
#endif
Apply1PDeviceFilters();
smartBowHelper1P.OnBluetoothModuleInited += () =>
{
scanLock = false;
canConnect = true;
userDoConnect = false;
doConnect = false;
if (connectCanceled)
{
Debug.Log("ble connectCanceled");
DoConnect();
return;
}
string mac = smartBowHelper1P.GetMacAddress();
SdkAimDeviceInfo firstPlayer = DeviceAim.GetAimDeviceInfo(BluetoothPlayer.FIRST_PLAYER);
if (firstPlayer != null && !firstPlayer.bInitMac)
{
Debug.Log("smartBowHelper1P 设置设备mac:" + mac);
DeviceAim.SetAimDeviceMac(mac);
}
else if (firstPlayer != null && !string.IsNullOrEmpty(mac) && firstPlayer.mac != mac)
{
Debug.Log("设备不一样,断开连接");
DoConnect();
CallDelay(4, () =>
{
Debug.Log("CallDelay 重新连接");
DoConnect();
});
return;
}
//if (!string.IsNullOrEmpty(mac))
//{
// curMac = mac;
// LoginMgr.myUserInfo.mac = mac;
// UserComp.Instance.saveMac();
//}
BowCamera.isTouchMode = false;
hasData = true;
hasDataTime = JCUnityLib.TimeUtils.GetTimestamp();
smartBowHelper1P.StartRotationSensor();
smartBowHelper1P.StartShootingSensor();
SetMainConnectDeviceType();
};
smartBowHelper1P.OnCMDState += (state, message) =>
{
userDoConnect = false;
doConnect = false;
canConnect = true;
scanLock = false;
DisconnectSmartBowHelper1P();
PopupMgr.ins.ShowTip(message);
SetStatus(BluetoothStatusEnum.ConnectFail);
};
smartBowHelper1P.OnBluetoothError += (error, message) =>
{
Debug.Log("smartBowHelper1P error:" + error+ ",message:"+ message);
if (error == BluetoothError.ScanNotFoundTargetDevice)
{
scanLock = false;
//PopupMgr.ins.ShowTip("连接失败,未发现目标设备!");
if (_scanCanRetryCount1P > 0)
{
_scanCanRetryCount1P--;
scanLock = true;
ConnectSmartBowHelper1P();
}
else
{
userDoConnect = false;
canConnect = true;
Log("没有发现设备");
SetStatus(BluetoothStatusEnum.ConnectFail);
}
return;
}
//PopupMgr.ins.ShowTip(message);
};
smartBowHelper1P.OnBluetoothStatusChanged += (oldStatus, newStatus) =>
{
Sync1PStatusFromSDK(newStatus);
SmartBowDeviceHub.ins?.NotifyStateChanged();
};
smartBowHelper1P.OnDeviceAndSystemInfoEvent += (connectPlatform, bleDeviceType) =>
InvokeOnDeviceAndSystemInfoEvent(connectPlatform, bleDeviceType);
DeviceAim?.BindSdk1P(smartBowHelper1P);
SmartBowDeviceHub.ins?.RegisterHelper1P(smartBowHelper1P);
}
void Sync1PStatusFromSDK(SmartBowSDK.BluetoothStatusEnum newStatus)
{
if (newStatus == SmartBowSDK.BluetoothStatusEnum.None)
{
if (status == BluetoothStatusEnum.Connecting || status == BluetoothStatusEnum.ConnectSuccess)
SetStatus(BluetoothStatusEnum.Connect);
}
else if (newStatus == SmartBowSDK.BluetoothStatusEnum.Connecting)
{
SetStatus(BluetoothStatusEnum.Connecting);
}
else if (newStatus == SmartBowSDK.BluetoothStatusEnum.Connected)
{
SetStatus(BluetoothStatusEnum.ConnectSuccess);
}
}
public void ConnectSmartBowHelper1P()
{
if (smartBowHelper1P == null)
{
onCreateSmartBowHelper1P();
CallDelay(0.2f, () =>
{
Apply1PDeviceFilters();
smartBowHelper1P.Connect(userTags1P, deviceId1P, false);
});
}
else
{
// 断开时 UnbindSdk1P,复用 helper 重连须重新订阅 rotation/shoot 等事件
DeviceAim?.BindSdk1P(smartBowHelper1P);
SmartBowDeviceHub.ins?.RegisterHelper1P(smartBowHelper1P);
Apply1PDeviceFilters();
smartBowHelper1P.Connect(userTags1P, deviceId1P, false);
}
}
public SmartBowHelper getSmartBowHelper1P()
{
return smartBowHelper1P;
}
#endregion
void HandleConnectException(string errorText)
{
scanLock = false;
canConnect = true;
// SetStatus(BluetoothStatusEnum.ConnectFail);
status = BluetoothStatusEnum.Connect;
userDoConnect = false;
PopupMgr.ins.ShowTip(errorText);
}
void CallDelay(float delayTime, TweenCallback callback)
{
Sequence sequence = DOTween.Sequence();
sequence.PrependInterval(delayTime).AppendCallback(callback);
sequence.SetUpdate(true);
}
void Log(string text)
{
if (textUI)
{
textUI.text = text;
}
Debug.Log(string.Format("[{0}]{1}", typeof(BluetoothAim).Name, text));
}
[NonSerialized] public string curMac;
#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();
#if UNITY_ANDROID
if (CommonConfig.bUseCMD)
{
//使用CMD API连接,这个只支持Android
smartBowHelper2P.UseCompanionDeviceManager(true);
}
#endif
if (smartBowHelper2P.GetUseCompanionDeviceManagerStatus())
smartBowHelper2P.SetFilters(ToRegex(targetDeviceName2P));
else
smartBowHelper2P.SetFilters(targetDeviceName2P);
smartBowHelper2P.OnBluetoothModuleInited += () =>
{
Debug.Log("OnBluetoothModuleInited");
//判断是否是同一个mac
//需要增加一个判断,判断是否对应的mac设备。不是需要进行重新连接
string mac = smartBowHelper2P.GetMacAddress();
SdkAimDeviceInfo secondPlayer = DeviceAim.GetAimDeviceInfo(BluetoothPlayer.SECOND_PLAYER);
if (secondPlayer != null && !secondPlayer.bInitMac)
{
Debug.Log("smartBowHelper2P 设置设备mac:" + mac);
DeviceAim.SetAimDeviceMac(mac);
}
else if (secondPlayer != null && secondPlayer.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.OnCMDState += (state, message) =>
{
userDoConnect2P = false;
doConnect2P = false;
canConnect2P = true;
DisconnectSmartBowHelper2P();
PopupMgr.ins.ShowTip(message);
};
smartBowHelper2P.OnBluetoothError += (error, message) =>
{
Debug.Log("smartBowHelper2P error:" + error + ",message:" + message);
if (error == BluetoothError.ScanNotFoundTargetDevice)
{
scanLock = false;
//PopupMgr.ins.ShowTip("连接失败,未发现目标设备!");
if (_scanCanRetryCount2P > 0)
{
_scanCanRetryCount2P--;
scanLock = true;
ConnectSmartBowHelper2P();
}
else
{
userDoConnect2P = false;
canConnect2P = true;
Log("没有发现设备");
}
return;
}
//PopupMgr.ins.ShowTip(message);
};
smartBowHelper2P.OnBluetoothStatusChanged += (oldStatus, newStatus) =>
{
UpdateConnectText();
SmartBowDeviceHub.ins?.NotifyStateChanged();
};
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 += DeviceAim.OnShot2P;
smartBowHelper2P.OnFunctionKeyPress += () =>
{
//如果是双人场景,触发提示
if (SceneManager.GetActiveScene().name == "GameDouble")
{
if (GameObject.Find("AutoResetViewNewRight")) return;
GameObject resetView = Instantiate(Resources.Load("AutoResetViewNew"));
resetView.name = "AutoResetViewNewRight";
AutoResetViewNew autoResetViewNewScript = resetView.GetComponent();
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("AutoResetViewNew"));
resetView.name = "AutoResetViewNewRight";
AutoResetViewNew autoResetViewNewScript = resetView.GetComponent();
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
SmartBowDeviceHub.ins?.RegisterHelper2P(smartBowHelper2P);
}
void UpdateConnectText()
{
var newStatus = smartBowHelper2P.GetBluetoothStatus();
if (newStatus == SmartBowSDK.BluetoothStatusEnum.None)
{
if (GameController.ins)
{
GameController.ins.GetBowCameraDoublePlayer(PlayerType.SecondPlayer).isTouchMode = true;
}
Debug.Log("未连接(点击连接)");
if (!bNoNeedToReconnect) return;
scanLock = false;
if (_scanCanRetryCount2P > 0)
{
_scanCanRetryCount2P--;
scanLock = true;
ConnectSmartBowHelper2P();
}
else
{
userDoConnect2P = false;
canConnect2P = true;
Log("没有发现设备");
//PopupMgr.ins.ShowTip("连接失败,未发现目标设备!");
}
}
else if (newStatus == SmartBowSDK.BluetoothStatusEnum.Connecting)
{
Debug.Log("连接中");
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("已连接(点击断开)");
else Debug.Log("已连接(正在初始化)");
}
}
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 (status == BluetoothStatusEnum.Connecting)
{
userDoConnect = false;
doConnect = false;
OnDisconnect();
DisconnectSmartBowHelper1P();
SetStatus(_bluetoothStatus);
}
if (smartBowHelper1P != null && smartBowHelper1P.GetBluetoothStatus() == SmartBowSDK.BluetoothStatusEnum.Connecting)
{
userDoConnect = false;
doConnect = false;
canConnect = true;
DisconnectSmartBowHelper1P();
}
//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 = DeviceAim != null
&& DeviceAim.GetDeviceType(BluetoothPlayer.FIRST_PLAYER) == (int)AimDeviceType.HOUYIPRO;
if (_isHOUYIPRO)
{
if (CommonConfig.bDisableBluetooth)
{
return true;
}
else
{
//如果是。判断是否连接
return status == BluetoothStatusEnum.ConnectSuccess;
}
}
else
{
return false;
}
}
#endregion
#region 判断是否是1p设备连接的是ARTEMISPRO信息
public bool isMainConnectToARTEMISPRO()
{
bool _isARTEMISPRO = DeviceAim != null
&& DeviceAim.GetDeviceType(BluetoothPlayer.FIRST_PLAYER) == (int)AimDeviceType.ARTEMISPRO;
if (_isARTEMISPRO)
{
if (CommonConfig.bDisableBluetooth)
{
return true;
}
else
{
//如果是。判断是否连接
return status == BluetoothStatusEnum.ConnectSuccess;
}
}
else
{
return false;
}
}
#endregion
#region 判断是否是1p设备连接的是红外信息,有多种红外设备
public bool isMainConnectToInfraredDevice()
{
if (DeviceAim == null)
return false;
int type = DeviceAim.GetDeviceType(BluetoothPlayer.FIRST_PLAYER);
bool _isInfraredDevice = type == (int)AimDeviceType.ARTEMISPRO
|| type == (int)AimDeviceType.HOUYIPRO;
if (_isInfraredDevice)
{
if (CommonConfig.bDisableBluetooth)
{
return true;
}
else
{
//如果是。判断是否连接
return status == BluetoothStatusEnum.ConnectSuccess;
}
}
else
{
return false;
}
}
#endregion
#region 判断是否是1p设备连接的是Gun信息
public bool isMainConnectToGun()
{
if (DeviceAim == null)
return false;
int type = DeviceAim.GetDeviceType(BluetoothPlayer.FIRST_PLAYER);
bool _isGun = type == (int)AimDeviceType.Gun
|| type == (int)AimDeviceType.PistolM17
|| type == (int)AimDeviceType.RifleM416;
if (_isGun)
{
if (CommonConfig.bDisableBluetooth)
{
return true;
}
else
{
//如果是。判断是否连接
return status == BluetoothStatusEnum.ConnectSuccess;
}
}
else
{
return false;
}
}
///
/// 获取连接枪的类型
///
///
public (bool isGun, AimDeviceType gunType) isMainConnectToGunType()
{
AimDeviceType aimDeviceType = AimDeviceType.NONE;
if (DeviceAim == null)
return (false, aimDeviceType);
int type = DeviceAim.GetDeviceType(BluetoothPlayer.FIRST_PLAYER);
bool _isGun = type == (int)AimDeviceType.Gun
|| type == (int)AimDeviceType.PistolM17
|| type == (int)AimDeviceType.RifleM416;
if (_isGun)
aimDeviceType = (AimDeviceType)type;
if (_isGun)
{
if (CommonConfig.bDisableBluetooth)
{
return (true, aimDeviceType);
}
else
{
//如果是。判断是否连接
return (status == BluetoothStatusEnum.ConnectSuccess, aimDeviceType);
}
}
else
{
return (false, aimDeviceType);
}
}
#endregion
///
/// 设置设备类型(1P 连接成功后同步顶部栏 / GlobalData;HomeView 未就绪时仍写入 PlayerPrefs)。
///
public void SetMainConnectDeviceType()
{
AimHandler aim = DeviceAim;
if (aim == null) return;
int type = aim.GetDeviceType(BluetoothPlayer.FIRST_PLAYER);
int topBarIndex = 0;
if (type == (int)AimDeviceType.Gun
|| type == (int)AimDeviceType.PistolM17
|| type == (int)AimDeviceType.RifleM416)
topBarIndex = 1;
HomeViewTopBar topBar = UHomeView.ins?.MyTopBarView;
if (topBar != null)
{
topBar.onChangeType(topBarIndex);
return;
}
GlobalData.MyDeviceMode = (DeviceMode)topBarIndex;
PlayerPrefs.SetInt("DeviceModeKey", topBarIndex);
PlayerPrefs.Save();
}
#region 管理部分监听通信
///
/// 监听枪状态
///
public BleDeviceEvent OnBleDeviceState;
///
/// 硬件对应的事件
///
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);
}
}
///
/// 记录硬件反馈的设备状态和连接的设备平台信息
///
public BluetoothDeviceType myBluetoothDeviceType = BluetoothDeviceType.NONE;
public ConnectPlatform myConnectPlatform = ConnectPlatform.NONE;
///
/// 监听设备状态和连接的设备平台信息
///
public DeviceAndSystemInfoEvent OnDeviceAndSystemInfoEvent;
///
/// 硬件对应的事件初始化回调
///
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);
}
}
///
/// 获取一次当前记录的信息
///
public void GetDeviceAndSystemInfoEvent()
{
OnDeviceAndSystemInfoEvent?.Invoke(myConnectPlatform, myBluetoothDeviceType);
}
///
/// 返回一个存储用户的新手教程字符串
///
///
public string GetInfraredGuiderKey()
{
return $"hideInfraredGuider-{LoginMgr.myUserInfo.id}-{myBluetoothDeviceType}";
}
///
/// 清除当前红外记录的存储的所有key内容
///
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
}
}