移动端蓝牙优化

This commit is contained in:
lishuo 2022-06-09 14:51:03 +08:00 committed by CaiYanPeng
parent 72f254af2a
commit 2f64aa494f
10 changed files with 84 additions and 16 deletions

View File

@ -39,6 +39,10 @@ namespace Assets.Scripts.Devices
/// </summary> /// </summary>
public int SignalStrength { get; internal set; } public int SignalStrength { get; internal set; }
public DateTime LastActiveTime { get; internal set; }
public string ErrorMsg { get; internal set; }
protected AbstractDevice(string id, NetworkType networkType) protected AbstractDevice(string id, NetworkType networkType)
{ {
this.Id = id; this.Id = id;
@ -46,7 +50,7 @@ namespace Assets.Scripts.Devices
} }
public abstract void Connect(); public abstract void Connect(Action<string> callback = null);
public abstract void Disconnect(bool save = true); public abstract void Disconnect(bool save = true);
} }

View File

@ -166,12 +166,12 @@ namespace Assets.Scripts.Devices.Ant
// base.reset(); // base.reset();
//} //}
public override void Connect() public override void Connect(Action<string> callback = null)
{ {
if (State == DeviceState.Connected || State == DeviceState.Connecting) if (State == DeviceState.Connected || State == DeviceState.Connecting)
return; return;
Debug.Log("连接" + this.DeviceNumber); Debug.Log("连接" + this.DeviceNumber);
AntConnector.Instance().ConnectDevice(this); AntConnector.Instance().ConnectDevice(this, callback);
} }
public override void Disconnect(bool save = true) public override void Disconnect(bool save = true)

View File

@ -294,6 +294,14 @@ namespace Assets.Scripts.Devices.Ant
void antChannel_channelResponse_FeSearch(ANT_Response response) void antChannel_channelResponse_FeSearch(ANT_Response response)
{ {
//删除扫描不到的设备
var now = DateTime.Now;
var needRemoveList = discoveredDevices.Where(c => (now - c.LastActiveTime).TotalSeconds > 5 && c.State == DeviceState.Disconnected).ToList();
foreach (var item in needRemoveList)
{
discoveredDevices.Remove(item);
}
if (IsBackgroundScanning == false) if (IsBackgroundScanning == false)
{ {
searchChannel.closeChannel(); searchChannel.closeChannel();
@ -318,6 +326,7 @@ namespace Assets.Scripts.Devices.Ant
var device2 = discoveredDevices.FirstOrDefault(d => d.searchProfile.deviceNumber == deviceNumber && d.searchProfile.deviceType == deviceTypeId); var device2 = discoveredDevices.FirstOrDefault(d => d.searchProfile.deviceNumber == deviceNumber && d.searchProfile.deviceType == deviceTypeId);
if (device2 != null) if (device2 != null)
{ {
device2.LastActiveTime = DateTime.Now;
//ReSearch(); //ReSearch();
_action?.Invoke(device2); _action?.Invoke(device2);
if (device2.State == DeviceState.Connected) if (device2.State == DeviceState.Connected)
@ -371,6 +380,7 @@ namespace Assets.Scripts.Devices.Ant
if (device != null) if (device != null)
{ {
//device.searchProfile.deviceNumber = (ushort)deviceNumber; //device.searchProfile.deviceNumber = (ushort)deviceNumber;
device.LastActiveTime = DateTime.Now;
device.DeviceNumber = (ushort)deviceNumber; device.DeviceNumber = (ushort)deviceNumber;
discoveredDevices.Add(device); discoveredDevices.Add(device);
@ -412,9 +422,10 @@ namespace Assets.Scripts.Devices.Ant
searchChannel.setChannelSearchTimeout(0); searchChannel.setChannelSearchTimeout(0);
searchChannel.openChannel(500); searchChannel.openChannel(500);
} }
Action<string> connectCallBack;
public void ConnectDevice(AbstractAntDevice device) public void ConnectDevice(AbstractAntDevice device,Action<string> callBack = null)
{ {
this.connectCallBack = callBack;
if (usedChannels.Any(u => u.DeviceNumber == device.searchProfile.deviceNumber.ToString() && if (usedChannels.Any(u => u.DeviceNumber == device.searchProfile.deviceNumber.ToString() &&
u.DeviceTypeId == device.searchProfile.deviceType.ToString())) u.DeviceTypeId == device.searchProfile.deviceType.ToString()))
return; return;

View File

@ -19,6 +19,7 @@ namespace Assets.Scripts.Devices.Ble
{ {
protected IBleWinHwInterface hwInterface; protected IBleWinHwInterface hwInterface;
protected BlePeripheralInfo peripheralInfo; protected BlePeripheralInfo peripheralInfo;
protected Action<string> connectCallBack;
private readonly HashSet<BleService> services = new HashSet<BleService>(); private readonly HashSet<BleService> services = new HashSet<BleService>();
private readonly HashSet<BleServiceInfo> pendingServices = new HashSet<BleServiceInfo>(); private readonly HashSet<BleServiceInfo> pendingServices = new HashSet<BleServiceInfo>();
@ -98,6 +99,7 @@ namespace Assets.Scripts.Devices.Ble
Debug.Log($"连接{ this.Name }"+response.IsSuccess); Debug.Log($"连接{ this.Name }"+response.IsSuccess);
if (response.IsSuccess) if (response.IsSuccess)
{ {
ErrorMsg = string.Empty;
State = DeviceState.Connected; State = DeviceState.Connected;
//Debug.Log("连接成功"+this.Name); //Debug.Log("连接成功"+this.Name);
hwInterface.DiscoverServices(this.peripheralInfo, ServicesDiscoveredAction);//, this.ServicesDiscoveredAction); hwInterface.DiscoverServices(this.peripheralInfo, ServicesDiscoveredAction);//, this.ServicesDiscoveredAction);
@ -106,6 +108,7 @@ namespace Assets.Scripts.Devices.Ble
if (response.Error != null) if (response.Error != null)
{ {
ErrorMsg = App.GetLocalString("connect failed");
this.State = DeviceState.Disconnected; this.State = DeviceState.Disconnected;
if (response.Error.Code == WclBleErrors.WCL_E_BLUETOOTH_LE_DEVICE_NOT_FOUND) if (response.Error.Code == WclBleErrors.WCL_E_BLUETOOTH_LE_DEVICE_NOT_FOUND)
{ {
@ -113,7 +116,9 @@ namespace Assets.Scripts.Devices.Ble
App.MainDeviceAdapter.ClearDevice(this.peripheralInfo.Address); App.MainDeviceAdapter.ClearDevice(this.peripheralInfo.Address);
} }
} }
//无法与xx连接请检查后重拾
var errorMsg = App.GetLocalLanguage() == "zh" ? $"无法与设备{Name}-{DeviceNumber}连接,请检查后重试。": $"failed to connect {Name}-{DeviceNumber},please check and retry.";
connectCallBack?.Invoke(response.IsSuccess ? string.Empty : errorMsg);
} }
private void Disconnect() private void Disconnect()
@ -234,8 +239,9 @@ namespace Assets.Scripts.Devices.Ble
} }
} }
public override void Connect() public override void Connect(Action<string> callback = null)
{ {
this.connectCallBack = callback;
this.ConnectToPeripheralIfPossible(); this.ConnectToPeripheralIfPossible();
} }

View File

@ -34,6 +34,7 @@ namespace Assets.Scripts.Devices.Ble
if(bleState == BleState.Off) if(bleState == BleState.Off)
{ {
discoveredDevices.Clear(); discoveredDevices.Clear();
this.StopScan();
} }
else else
{ {
@ -158,8 +159,16 @@ namespace Assets.Scripts.Devices.Ble
if (discoveredDevices.ContainsKey(device.Peripheral.Address)) if (discoveredDevices.ContainsKey(device.Peripheral.Address))
{ {
discoveredDevices[device.Peripheral.Address].SignalStrength = device.Rssi; discoveredDevices[device.Peripheral.Address].SignalStrength = device.Rssi;
discoveredDevices[device.Peripheral.Address].LastActiveTime = DateTime.Now;
//Debug.Log($"设备{ device.Peripheral.Name }信号量:{ device.Rssi }"); //Debug.Log($"设备{ device.Peripheral.Name }信号量:{ device.Rssi }");
} }
//移除到5s没有扫描到的设备
var now = DateTime.Now;
var needRemove = discoveredDevices.Where(c => (now - c.Value.LastActiveTime).TotalSeconds > 5 && c.Value.State == Ant.DeviceState.Disconnected).ToList();
foreach (var item in needRemove)
{
discoveredDevices.Remove(item.Key);
}
}); });
} }

View File

@ -35,7 +35,7 @@ namespace Assets.Scripts.Devices.Ble
this.managerStatusChanged -= value; this.managerStatusChanged -= value;
} }
} }
WclBleManagerStatus statusEnum = WclBleManagerStatus.RadioOn; WclBleManagerStatus statusEnum = WclBleManagerStatus.RadioOff;
internal BleMobileThread() { internal BleMobileThread() {
var self = this; var self = this;
//初始蓝牙 //初始蓝牙
@ -69,12 +69,12 @@ namespace Assets.Scripts.Devices.Ble
public void StartWatcher() { public void StartWatcher() {
var self = this; var self = this;
statusEnum = WclBleManagerStatus.RadioOn;
if (statusEnum == WclBleManagerStatus.RadioOff) if (statusEnum == WclBleManagerStatus.RadioOff)
{ {
BluetoothLEHardwareInterface.BluetoothEnable(true); BluetoothLEHardwareInterface.BluetoothEnable(true);
BluetoothLEHardwareInterface.Initialize(true, false, () => BluetoothLEHardwareInterface.Initialize(true, false, () =>
{ {
statusEnum = WclBleManagerStatus.RadioOn;
managerInitialized?.Invoke(self); managerInitialized?.Invoke(self);
BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(ServiceUuids.GetServiceUuidList().ToArray(), null, (address, name, rssi, bytes) => BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(ServiceUuids.GetServiceUuidList().ToArray(), null, (address, name, rssi, bytes) =>
{ {

View File

@ -107,7 +107,10 @@ public class ConnectDeviceModal : PFUIPanel
var dd = deviceList.Select(d => d.Value).Where(d => d.GetStatus()).FirstOrDefault(); var dd = deviceList.Select(d => d.Value).Where(d => d.GetStatus()).FirstOrDefault();
if (dd != null) if (dd != null)
{ {
dd.DeviceInfo.Connect(); var modal = this.gameObject;
dd.DeviceInfo.Connect((error)=> {
Utils.showToast(modal, error);
});
DeviceCache.Add(dd.DeviceInfo); DeviceCache.Add(dd.DeviceInfo);
} }
} }
@ -215,6 +218,21 @@ public class ConnectDeviceModal : PFUIPanel
deviceList.Add(device.Id, deviceItemObj); deviceList.Add(device.Id, deviceItemObj);
} }
//删除扫描不到的设备
var needRemove = deviceList.Where(q => !devices.Select(n => n.Id).Contains(q.Key)).ToList();
if (needRemove.Count > 0)
{
var currentlist = FindObjectsOfType<DeviceItem>();
foreach (var item in needRemove)
{
deviceList.Remove(item.Key);
var current = currentlist.Where(e => e.Id == item.Key).FirstOrDefault();
if (current != null)
{
current.gameObject.Destroy(true);
}
}
}
if(deviceList.All(d=>d.Value.GetStatus() == false)) if(deviceList.All(d=>d.Value.GetStatus() == false))
{ {

View File

@ -13,6 +13,7 @@ public class DeviceItem : Selectable, IEventSystemHandler, IPointerClickHandler
private Image network; private Image network;
private Image signal; private Image signal;
private float timer = 0f; private float timer = 0f;
public string Id { get; set; }
public AbstractDevice DeviceInfo public AbstractDevice DeviceInfo
{ {
get;set; get;set;
@ -31,6 +32,7 @@ public class DeviceItem : Selectable, IEventSystemHandler, IPointerClickHandler
//this.currentSelectionState = SelectionState.Selected //this.currentSelectionState = SelectionState.Selected
if (DeviceInfo == null) if (DeviceInfo == null)
return; return;
Id = DeviceInfo.Id;
mText.text = DeviceInfo.Name;// + "-" + DeviceInfo.DeviceNumber; mText.text = DeviceInfo.Name;// + "-" + DeviceInfo.DeviceNumber;
if(DeviceInfo.Network == NetworkType.ANT) if(DeviceInfo.Network == NetworkType.ANT)
{ {
@ -49,9 +51,14 @@ public class DeviceItem : Selectable, IEventSystemHandler, IPointerClickHandler
{ {
signal.enabled = false; signal.enabled = false;
} }
Signal_1 = Resources.Load<Sprite>("Images/Signal_1");
Signal_2 = Resources.Load<Sprite>("Images/Signal_2");
Signal_3 = Resources.Load<Sprite>("Images/Signal_3");
SetSignal(); SetSignal();
} }
Sprite Signal_1;
Sprite Signal_2;
Sprite Signal_3;
private void SetSignal() private void SetSignal()
{ {
@ -66,15 +73,15 @@ public class DeviceItem : Selectable, IEventSystemHandler, IPointerClickHandler
var signalValue = DeviceInfo.SignalStrength * -1; var signalValue = DeviceInfo.SignalStrength * -1;
if (signalValue >= 0 && signalValue <= 30) if (signalValue >= 0 && signalValue <= 30)
{ {
signal.sprite = Resources.Load<Sprite>("Images/Signal_1"); signal.sprite = Signal_1;
} }
else if (signalValue > 30 && signalValue <= 60) else if (signalValue > 30 && signalValue <= 60)
{ {
signal.sprite = Resources.Load<Sprite>("Images/Signal_2"); signal.sprite = Signal_2;
} }
else if (signalValue > 60)//&& signalValue <= 97 else if (signalValue > 60)//&& signalValue <= 97
{ {
signal.sprite = Resources.Load<Sprite>("Images/Signal_3"); signal.sprite = Signal_3;
} }
} }

View File

@ -5,6 +5,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using UnityEngine; using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI; using UnityEngine.UI;
public class MailReceiver : MonoBehaviour public class MailReceiver : MonoBehaviour
@ -47,7 +48,10 @@ public class MailReceiver : MonoBehaviour
timer -= Time.deltaTime; timer -= Time.deltaTime;
if (timer < 0) if (timer < 0)
{ {
GetMessage(); if (!SceneManager.GetActiveScene().name.Contains("Login"))
{
GetMessage();
}
timer += 10; timer += 10;
} }
} }

View File

@ -24,10 +24,10 @@ public class RowerDevicePanel : PFUIPanel
base.Show(); base.Show();
print("开启扫描"); print("开启扫描");
#if UNITY_ANDROID || UNITY_IOS #if UNITY_ANDROID || UNITY_IOS
App.MainDeviceAdapter.StartScan();
#if UNITY_ANDROID #if UNITY_ANDROID
Utils.CallAndroidMethod("OpenLocationService"); Utils.CallAndroidMethod("OpenLocationService");
#endif #endif
App.MainDeviceAdapter.StartScan();
#endif #endif
} }
float timer = 1f; float timer = 1f;
@ -48,4 +48,13 @@ public class RowerDevicePanel : PFUIPanel
timer += 1f; timer += 1f;
} }
} }
protected override void OnDisable()
{
App.MainDeviceAdapter.StopScan();
}
protected override void OnDestroy()
{
App.MainDeviceAdapter.StopScan();
}
} }