Skip to content

Commit

Permalink
Merge pull request #849 from AskBojesen/demo_connection_lost_reconnect
Browse files Browse the repository at this point in the history
Windows: Connect -> ConnectionLost -> Reconnect
  • Loading branch information
janusw committed May 15, 2024
2 parents 18d5e3f + ee64c6c commit c894e46
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 41 deletions.
96 changes: 60 additions & 36 deletions Source/BLE.Client/BLE.Client.WinConsole/PluginDemos.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ internal class PluginDemos
private readonly Action<string, object[]>? writer;
private readonly List<IDevice> discoveredDevices;
private bool scanningDone = false;
private ConsoleKey consoleKey = ConsoleKey.None;
private IDevice? reconnectDevice;
private CancellationTokenSource escKeyCancellationTokenSource = new CancellationTokenSource();

public PluginDemos(Action<string, object[]>? writer = null)
{
Expand All @@ -41,11 +44,6 @@ private void Adapter_DeviceConnectionError(object? sender, Plugin.BLE.Abstractio
Write($"Adapter_DeviceConnectionError {e.Device.Id.ToHexBleAddress()} with name: {e.Device.Name}");
}

private void Adapter_DeviceConnectionLost(object? sender, Plugin.BLE.Abstractions.EventArgs.DeviceErrorEventArgs e)
{
Write($"Adapter_DeviceConnectionLost {e.Device.Id.ToHexBleAddress()} with name: {e.Device.Name}");
}

private void Adapter_DeviceDisconnected(object? sender, Plugin.BLE.Abstractions.EventArgs.DeviceEventArgs e)
{
Write($"Adapter_DeviceDisconnected {e.Device.Id.ToHexBleAddress()} with name: {e.Device.Name}");
Expand Down Expand Up @@ -163,41 +161,71 @@ public async Task Connect_Read_Services_Dispose_5X()
}
}

public async Task Connect_ConnectionLost_Connect()
private void ConsoleKeyReader()
{
string bleaddress = BleAddressSelector.GetBleAddress();
var id = bleaddress.ToBleDeviceGuid();
var connectParameters = new ConnectParameters(connectionParameterSet: ConnectionParameterSet.Balanced);
ConsoleKey consoleKey = ConsoleKey.None;
using (IDevice dev = await Adapter.ConnectToKnownDeviceAsync(id, connectParameters))
while (consoleKey != ConsoleKey.Escape)
{
while (consoleKey != ConsoleKey.Escape)
consoleKey = Console.ReadKey().Key;
}
Write("Escape key pressed - stopping...");
escKeyCancellationTokenSource.Cancel();
}

private async Task ConnectWorker(Guid id)
{
while (consoleKey != ConsoleKey.Escape)
{
try
{
Write("Reading services");
var services = await dev.GetServicesAsync();
List<ICharacteristic> charlist = new List<ICharacteristic>();
Write("Trying to connect to device (Escape key to abort)");
reconnectDevice = await Adapter.ConnectToKnownDeviceAsync(id, cancellationToken: escKeyCancellationTokenSource.Token);
Write("Reading all services and characteristics");
var services = await reconnectDevice.GetServicesAsync();
List<ICharacteristic> characteristics = new List<ICharacteristic>();
foreach (var service in services)
{
var characteristics = await service.GetCharacteristicsAsync();
charlist.AddRange(characteristics);
var newcharacteristics = await service.GetCharacteristicsAsync();
characteristics.AddRange(newcharacteristics);
}
await Task.Delay(1000);
Console.WriteLine(new string('-', 80));
Console.WriteLine("Now powercycle the device... Hit any key when the device is booted up again (Escape to quit)");
Console.WriteLine(new string('-', 80));
consoleKey = Console.ReadKey().Key;
await Adapter.ConnectToDeviceAsync(dev, connectParameters);
Write("Waiting 3 secs");
await Task.Delay(3000);
foreach (var service in services)
{
service.Dispose();
}
charlist.Clear();
Write(new string('-', 80));
Write("Connected successfully!");
Write("To test connection lost: Move the device out of range / power off the device");
Write(new string('-', 80));
break;
}
catch
{
}
}
}

public async Task Connect_ConnectionLost_Reconnect()
{
string bleaddress = BleAddressSelector.GetBleAddress();
var id = bleaddress.ToBleDeviceGuid();
var consoleReaderTask = new Task(ConsoleKeyReader);
consoleReaderTask.Start();
await ConnectWorker(id);
consoleReaderTask.Wait();
}

private async void Adapter_DeviceConnectionLost(object? sender, Plugin.BLE.Abstractions.EventArgs.DeviceErrorEventArgs e)
{
Write($"Adapter_DeviceConnectionLost {e.Device.Id.ToHexBleAddress()} with name: {e.Device.Name}");
if (reconnectDevice is not null && reconnectDevice.Id == e.Device.Id)
{
reconnectDevice.Dispose();
reconnectDevice = null;
await Task.Delay(1000);
Write(new string('-', 80));
Write("Lost connection!");
Write("To test reconnect: Move the device back in range / power on the device");
Write(new string('-', 80));
_ = ConnectWorker(e.Device.Id);
}
}

public async Task Connect_Change_Parameters_Disconnect()
{
string bleaddress = BleAddressSelector.GetBleAddress();
Expand Down Expand Up @@ -231,7 +259,7 @@ public async Task BondAsync()
public Task GetBondedDevices()
{
int idx = 0;
foreach(var dev in Adapter.BondedDevices)
foreach (var dev in Adapter.BondedDevices)
{
Write($"{idx++} Bonded device: {dev.Name} : {dev.Id}");
}
Expand All @@ -255,7 +283,8 @@ public async Task Pair_Connect_Disconnect()
deviceInformation.Pairing.Custom.PairingRequested += Custom_PairingRequested;
DevicePairingResult result = await deviceInformation.Pairing.Custom.PairAsync(DevicePairingKinds.ConfirmOnly, DevicePairingProtectionLevel.Encryption);
Write("Pairing result: " + result.Status);
} else
}
else
{
Write("Already paired");
}
Expand All @@ -272,11 +301,6 @@ public async Task Pair_Connect_Disconnect()
Write("Custom_Pair_Connect_Disconnect done");
}

private void NativeDevice_ConnectionStatusChanged(BluetoothLEDevice sender, object args)
{
Write($"NativeDevice_ConnectionStatusChanged({sender.ConnectionStatus})");
}

private void Custom_PairingRequested(DeviceInformationCustomPairing sender, DevicePairingRequestedEventArgs args)
{
Write("Custom_PairingRequested -> Accept");
Expand Down
2 changes: 1 addition & 1 deletion Source/BLE.Client/BLE.Client.WinConsole/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
{ConsoleKey.D6, new Demo("Run GetSystemConnectedOrPairedDevices", ppemos.RunGetSystemConnectedOrPairedDevices) },
{ConsoleKey.D7, new Demo("5X: Connect -> Read services -> Disconnect", ppemos.Connect_Read_Services_Disconnect_5X) },
{ConsoleKey.D8, new Demo("5X: Connect -> Read services -> Dispose", ppemos.Connect_Read_Services_Dispose_5X) },
{ConsoleKey.D9, new Demo("Connect -> Loop: ConnectionLost -> Connect", ppemos.Connect_ConnectionLost_Connect) },
{ConsoleKey.D9, new Demo("Connect -> Loop: ConnectionLost -> Connect", ppemos.Connect_ConnectionLost_Reconnect) },
{ConsoleKey.Q, new Demo("Adapter.BondAsync", ppemos.BondAsync) },
{ConsoleKey.W, new Demo("Adapter.BondedDevices", ppemos.GetBondedDevices) },
{ConsoleKey.E, new Demo("Device.BondState", ppemos.ShowBondState) },
Expand Down
3 changes: 1 addition & 2 deletions Source/BLE.Client/BLE.Client.WinConsole/WindowsDemos.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,12 @@ public async Task Connect_Disconnect()

public async Task UnPairAllBleDevices()
{
var bleaddress = BleAddressSelector.GetBleAddress();
string aqsFilter = BluetoothLEDevice.GetDeviceSelector();
var collection = await DeviceInformation.FindAllAsync(aqsFilter);
foreach (DeviceInformation di in collection)
{
try
{
{
DeviceUnpairingResult res = await di.Pairing.UnpairAsync();
Write($"Unpairing {di.Name}: {res.Status}");
}
Expand Down
4 changes: 2 additions & 2 deletions Source/Plugin.BLE/Windows/Adapter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -153,9 +153,9 @@ private void Device_ConnectionStatusChanged(BluetoothLEDevice nativeDevice, obje
bool disconnectRequested = disconnectingRegistry.Remove(id);
if (!disconnectRequested)
{
// device was powered off or went out of range. Call DisconnectDeviceNative to cleanup
// Device was powered off or went out of range. Call DisconnectInternal to cleanup
// resources otherwise windows will not disconnect on a subsequent connect-disconnect.
DisconnectDeviceNative(disconnectedDevice);
((Device)disconnectedDevice).DisconnectInternal();
}
ConnectedDeviceRegistry.Remove(id, out _);
nativeDevice.ConnectionStatusChanged -= Device_ConnectionStatusChanged;
Expand Down

0 comments on commit c894e46

Please sign in to comment.