mirror of
https://dev.azure.com/TeilRad/sharee.bike%20App/_git/Code
synced 2024-11-16 07:06:33 +01:00
42 lines
1.5 KiB
C#
42 lines
1.5 KiB
C#
|
using Plugin.BLE.Abstractions.Contracts;
|
|||
|
using System;
|
|||
|
using System.Threading.Tasks;
|
|||
|
|
|||
|
namespace TINK.Services.BluetoothLock
|
|||
|
{
|
|||
|
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>();
|
|||
|
|
|||
|
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;
|
|||
|
}
|
|||
|
|
|||
|
return tcs.Task;
|
|||
|
}
|
|||
|
}
|
|||
|
}
|