sharee.bike-App/LockIt.BLE/Services/BluetoothLock/StateChecker.cs

42 lines
1.2 KiB
C#
Raw Normal View History

2022-08-30 15:42:25 +02:00
using System;
2021-05-13 20:03:07 +02:00
using System.Threading.Tasks;
2022-08-30 15:42:25 +02:00
using Plugin.BLE.Abstractions.Contracts;
2021-05-13 20:03:07 +02:00
2024-04-09 12:53:23 +02:00
namespace ShareeBike.Services.BluetoothLock
2021-05-13 20:03:07 +02:00
{
2022-09-06 16:08:19 +02:00
public static class StateChecker
{
/// <summary>
/// Get current bluetooth state
/// </summary>
/// <remarks>See https://github.com/xabre/xamarin-bluetooth-le/issues/112#issuecomment-380994887.</remarks>
/// <param name="ble">Crossplatform bluetooth implementation object</param>
/// <returns>BluetoothState</returns>
public static Task<BluetoothState> GetBluetoothState(this IBluetoothLE ble)
{
var tcs = new TaskCompletionSource<BluetoothState>();
2021-05-13 20:03:07 +02:00
2022-09-06 16:08:19 +02:00
if (ble.State != BluetoothState.Unknown)
{
// If we can detect state out of box just returning in
tcs.SetResult(ble.State);
}
else
{
// Otherwise let's setup dynamic event handler and wait for first state update
EventHandler<Plugin.BLE.Abstractions.EventArgs.BluetoothStateChangedArgs> handler = null;
handler = (o, e) =>
{
ble.StateChanged -= handler;
// and return it as our state
// we can have an 'Unknown' check here, but in normal situation it should never occur
tcs.SetResult(e.NewState);
};
ble.StateChanged += handler;
}
2021-05-13 20:03:07 +02:00
2022-09-06 16:08:19 +02:00
return tcs.Task;
}
}
2021-05-13 20:03:07 +02:00
}