From e7ebdbf10fecc579a78c0ec76a19360044f27241 Mon Sep 17 00:00:00 2001 From: Ask Bojesen Date: Wed, 8 May 2024 17:01:41 +0200 Subject: [PATCH 1/3] Improved demo for Connect_ConnectionLost_Reconnect --- .../BLE.Client.WinConsole/PluginDemos.cs | 96 ++++++++++++------- .../BLE.Client.WinConsole/Program.cs | 2 +- .../BLE.Client.WinConsole/WindowsDemos.cs | 3 +- 3 files changed, 62 insertions(+), 39 deletions(-) diff --git a/Source/BLE.Client/BLE.Client.WinConsole/PluginDemos.cs b/Source/BLE.Client/BLE.Client.WinConsole/PluginDemos.cs index fb32c61b..22998461 100644 --- a/Source/BLE.Client/BLE.Client.WinConsole/PluginDemos.cs +++ b/Source/BLE.Client/BLE.Client.WinConsole/PluginDemos.cs @@ -23,6 +23,9 @@ internal class PluginDemos private readonly Action? writer; private readonly List discoveredDevices; private bool scanningDone = false; + private ConsoleKey consoleKey = ConsoleKey.None; + private IDevice? reconnectDevice; + private CancellationTokenSource escKeyCancellationTokenSource = new CancellationTokenSource(); public PluginDemos(Action? writer = null) { @@ -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}"); @@ -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 charlist = new List(); + 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 characteristics = new List(); 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(); @@ -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}"); } @@ -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"); } @@ -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"); diff --git a/Source/BLE.Client/BLE.Client.WinConsole/Program.cs b/Source/BLE.Client/BLE.Client.WinConsole/Program.cs index 6fc66477..073edb14 100644 --- a/Source/BLE.Client/BLE.Client.WinConsole/Program.cs +++ b/Source/BLE.Client/BLE.Client.WinConsole/Program.cs @@ -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) }, diff --git a/Source/BLE.Client/BLE.Client.WinConsole/WindowsDemos.cs b/Source/BLE.Client/BLE.Client.WinConsole/WindowsDemos.cs index bf405ba6..a3ee3365 100644 --- a/Source/BLE.Client/BLE.Client.WinConsole/WindowsDemos.cs +++ b/Source/BLE.Client/BLE.Client.WinConsole/WindowsDemos.cs @@ -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}"); } From a54b5364d9108fb467d392f841eb5015fe473aba Mon Sep 17 00:00:00 2001 From: Ask Bojesen Date: Wed, 8 May 2024 17:59:49 +0200 Subject: [PATCH 2/3] Fixed connection lost --- Source/Plugin.BLE/Windows/Adapter.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Source/Plugin.BLE/Windows/Adapter.cs b/Source/Plugin.BLE/Windows/Adapter.cs index 232a4569..77ea6070 100644 --- a/Source/Plugin.BLE/Windows/Adapter.cs +++ b/Source/Plugin.BLE/Windows/Adapter.cs @@ -153,7 +153,7 @@ private void Device_ConnectionStatusChanged(BluetoothLEDevice nativeDevice, obje { // device was powered off or went out of range. Call DisconnectDeviceNative 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; @@ -199,7 +199,7 @@ protected override IReadOnlyList GetBondedDevices() this, bluetoothLeDevice, 0, id); - devlist.Add(device); + devlist.Add(device); Trace.Message("GetBondedDevices: {0}: {1}", dev.Id, dev.Name); } else From a9efc5a8fc873b10aeba6d9b62ccbb8e34deea27 Mon Sep 17 00:00:00 2001 From: Ask Bojesen Date: Wed, 8 May 2024 18:01:56 +0200 Subject: [PATCH 3/3] Fixed comment in code --- Source/Plugin.BLE/Windows/Adapter.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/Plugin.BLE/Windows/Adapter.cs b/Source/Plugin.BLE/Windows/Adapter.cs index 77ea6070..b14418ef 100644 --- a/Source/Plugin.BLE/Windows/Adapter.cs +++ b/Source/Plugin.BLE/Windows/Adapter.cs @@ -151,7 +151,7 @@ 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. ((Device)disconnectedDevice).DisconnectInternal(); }