82 lines
2.7 KiB
C#

using Assets.Scripts.Ble;
using System.Timers;
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;
}
}
internal BleMobileThread() {
var self = this;
//初始蓝牙
BluetoothLEHardwareInterface.Initialize(true, false, () => {
managerInitialized?.Invoke(self);
},
(error) => {
BluetoothLEHardwareInterface.Log("Error: " + error);
if (error.Contains("Bluetooth LE Not Enabled"))
BluetoothLEHardwareInterface.BluetoothEnable(true);
}, (status) => {
var statusEnum = WclBleManagerStatus.RadioOn;
switch (status)
{
case 13:
statusEnum = WclBleManagerStatus.RadioOff;
break;
case 11:
statusEnum = WclBleManagerStatus.RadioOn;
break;
}
if (managerStatusChanged != null)
{
managerStatusChanged.Invoke(self, statusEnum);
}
});
}
public void StartWatcher() {
BluetoothLEHardwareInterface.ScanForPeripheralsWithServices(ServiceUuids.GetServiceUuidList().ToArray(), null, (address, name, rssi, bytes) =>
{
ScanInfoReceived?.Invoke(this, address, name, rssi, bytes);
}, true);
}
public void Stop()
{
BluetoothLEHardwareInterface.StopScan();
}
}
}