118 lines
4.2 KiB
C#

using Assets.Scripts.Ble;
using System.Timers;
using UnityEngine;
namespace Assets.Scripts.Devices.Ble
{
internal class BleMobileThread
{
public delegate void WclInitializedDelegate(BleMobileThread sender);
private BleMobileThread.WclInitializedDelegate managerInitialized;
public event BleMobileThread.WclInitializedDelegate ManagerInitialized
{
add
{
this.managerInitialized += value;
}
remove
{
this.managerInitialized -= value;
}
}
public delegate void WclAdvertisementPacketDelegate(BleMobileThread sender, string address, string name, int rssi, string[] uuids);
public BleMobileThread.WclAdvertisementPacketDelegate ScanInfoReceived;
internal delegate void ManagerStatusChangedCallback(BleMobileThread thread, WclBleManagerStatus status);
private BleMobileThread.ManagerStatusChangedCallback managerStatusChanged;
public event BleMobileThread.ManagerStatusChangedCallback ManagerStatusChanged
{
add
{
this.managerStatusChanged += value;
}
remove
{
this.managerStatusChanged -= value;
}
}
WclBleManagerStatus statusEnum = WclBleManagerStatus.RadioOn;
internal BleMobileThread() {
Initialize();//初始蓝牙
}
public void StartWatcher() {
var self = this;
if (statusEnum == WclBleManagerStatus.RadioOff)
{
//Initialize();
BluetoothLEHardwareInterface.BluetoothEnable(true);
}
else
{
BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(ServiceUuids.GetServiceUuidList().ToArray(), null, (address, name, rssi, bytes) =>
{
ScanInfoReceived?.Invoke(self, address, name, rssi, bytes);
}, true);
}
}
public void Initialize()
{
Debug.Log("Initialize");
var self = this;
BluetoothLEHardwareInterface.BluetoothEnable(true);
BluetoothLEHardwareInterface.Initialize(true, false, () =>
{
statusEnum = WclBleManagerStatus.RadioOn;
managerInitialized?.Invoke(self);
BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(ServiceUuids.GetServiceUuidList().ToArray(), null, (address, name, rssi, bytes) =>
{
ScanInfoReceived?.Invoke(self, address, name, rssi, bytes);
}, true);
},
(error) =>
{
statusEnum = WclBleManagerStatus.RadioOff;
BluetoothLEHardwareInterface.Log("Error: " + error);
if (error.Contains("Bluetooth LE Not Enabled"))
BluetoothLEHardwareInterface.BluetoothEnable(true);
}, (status) =>
{
statusEnum = WclBleManagerStatus.RadioOn;
switch (status)
{
case 10:
statusEnum = WclBleManagerStatus.RadioOff;
break;
case 13:
statusEnum = WclBleManagerStatus.RadioOff;
break;
case 11:
statusEnum = WclBleManagerStatus.RadioOff;
break;
case 12:
statusEnum = WclBleManagerStatus.RadioOn;
break;
default:
statusEnum = WclBleManagerStatus.RadioOff;
break;
}
if (managerStatusChanged != null)
{
managerStatusChanged.Invoke(self, statusEnum);
}
});
}
public void Stop()
{
BluetoothLEHardwareInterface.StopScan();
}
public void Dispose()
{
BluetoothLEHardwareInterface.StopScan();
BluetoothLEHardwareInterface.DisconnectAll();
}
}
}