The BLE Device Disconnection not working on UWP C#
Hello folks,
I'm developing a UWP Application using a C# for establishing the connection between BLE devices like Connect, Read, Write, and Disconnect for that we using a "Windows.Devices.Bluetooth".
I'd successfully completed a few operations like connect, Read, and Write. But when I'm trying to disconnect that connected BLE Device, It does not disconnect the device properly, It takes more than 1.5 - 2 mins. Yeah, I had unsubscribed the notification so the data that we are receiving from the BLE Device was stopped. So, that is not a problem.
The only issue should be that the device not disconnecting from the system.
For Example:
connected_device.Dispose();
If anyone has a solution for this issue, please help me.
Thanks in advance!
Universal Windows Platform (UWP)
C#
Windows 11
-
Junjie Zhu - MSFT 17,226 Reputation points • Microsoft Vendor
2023-09-04T02:39:24.01+00:00 Hi @Manickavasagam C ,
Welcome to Microsoft Q&A!
Have you checked the GattSessionStatus? According to this document Bluetooth GATT Client , you should make sure that there is no other app on the system has a reference to the device.
Thank you.
-
Manickavasagam C 0 Reputation points
2023-09-04T07:22:10.35+00:00 Hello @Junjie Zhu - MSFT
Thanks for your time and response
Let me share, How I'm done a connection and disconnecting the device
Connect To Device
public static async Task<bool> ConnectToDevice(string lastSixId) { try { BluetoothLEDevice previous_connected_device = LocalStorage.GetData_BLE_Device(Constants.DEFAULT_CONNECTED_BLE_DEVICE_SESSION_KEY_NAME); //await Logger.AddLog(LogLevel.Info, $"Previous Connected device Address: {previous_connected_device.BluetoothAddress.ToString()}"); if (previous_connected_device != null && previous_connected_device.ConnectionStatus == BluetoothConnectionStatus.Connected) { if (characteristic != null) { characteristic.ValueChanged -= Characteristic_ValueChanged; previous_connected_device.ConnectionStatusChanged -= ConnectedDevice_ConnectionStatusChanged; bool UnSubcribed = await UnsubscribeFromNotificationsAsync(previous_connected_device, serviceUuid, characteristicUuid); if (UnSubcribed) { await Logger.AddLog(LogLevel.Info, $"Attempting to disconnect from Device: {previous_connected_device.Name} ----- Current Connection Status: {previous_connected_device.ConnectionStatus}"); DisconnectDeviceAsync(previous_connected_device); // Assuming the Dispose method should handle the disconnection //previous_connected_device.Dispose(); //bool isDisconnected = await DisconnectBLEDevice(previous_connected_device); //await Logger.AddLog(LogLevel.Info, "BLE Device Disconnected: " + isDisconnected); // Increase the delay to ensure the device has enough time to update its status await Task.Delay(5000); await Logger.AddLog(LogLevel.Info, $"Status after attempting disconnection, Device Name: {previous_connected_device.Name} ----- Connection Status: {previous_connected_device.ConnectionStatus}"); Constants.DEVICE_SETTING_PREVIOUS_CONNECTED_DEVICE_NAME = previous_connected_device.Name; StatusManagement(Constants.STATE_PREVIOUS_DEVICE_DISCONNECTED); // If the device is still connected after Disconnect, log an error or handle accordingly //if (previous_connected_device.ConnectionStatus == BluetoothConnectionStatus.Connected) //{ // Constants.DEVICE_SETTING_PREVIOUS_CONNECTED_DEVICE_NAME = previous_connected_device.Name; // previous_connected_device.Dispose(); // StatusManagement(Constants.STATE_PREVIOUS_DEVICE_DISCONNECTED); //} previous_connected_device = null; LocalStorage.Store_BluetoothLEDevice(Constants.DEFAULT_CONNECTED_BLE_DEVICE_SESSION_KEY_NAME, null); LocalStorage.Store_String(Constants.SAVED_DEVICE_SESSION_KEY_NAME, ""); characteristic = null; } else { await Logger.AddLog(LogLevel.Error, "Unsubscribed to notifications was failed"); } } else { await Logger.AddLog(LogLevel.Error, "characteristic is null for the previous connected device"); } } var bluetoothAddress = ulong.Parse(lastSixId.Replace(":", ""), System.Globalization.NumberStyles.HexNumber); await Logger.AddLog(LogLevel.Info, $"Bluetooth Address: {bluetoothAddress.ToString()}"); BluetoothLEDevice connectedDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(bluetoothAddress); if (connectedDevice != null) { bool IsSubscribed = await SubscribeToNotificationsAsync(connectedDevice, serviceUuid, characteristicUuid); if (IsSubscribed) { bool IsStarted = await StartDataReceiveTask(connectedDevice); if (IsStarted) { LocalStorage.Store_String(Constants.SAVED_DEVICE_SESSION_KEY_NAME, lastSixId); LocalStorage.Store_BluetoothLEDevice(Constants.DEFAULT_CONNECTED_BLE_DEVICE_SESSION_KEY_NAME, connectedDevice); Constants.CURRENT_CONNECTED_DEVICE = connectedDevice; StatusManagement(Constants.STATE_CONNECTED); return true; } else { await Logger.AddLog(LogLevel.Info, $"NOT STARTED!"); } } else { await Logger.AddLog(LogLevel.Info, $"NOT SUBCRIBED"); } } else { await Logger.AddLog(LogLevel.Info, "BluetoothLEDevice is null"); } } catch (Exception ex) { await Logger.AddLog(LogLevel.Info, $"Error on Connect_To_Devices: {ex.ToString()}"); } return false; }
Yes, From the above method which I'm sharing, I have checked if Is there any previously connected device, If yes, I'm trying to disconnect and connect to a new BLE Device by using a below line
BluetoothLEDevice connectedDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(bluetoothAddress);
Here is the method for disconnection
private static async Task<bool> DisconnectDeviceAsync(BluetoothLEDevice device) { bool success = true; try { var servicesResult = await device.GetGattServicesAsync(); if (servicesResult.Status == GattCommunicationStatus.Success) { foreach (var service in servicesResult.Services) { service.Dispose(); } } //device = null; } catch (Exception ex) { await Logger.AddLog(LogLevel.Error, $"Expection while disconnect the device: {ex}"); success = false; }
These are code which I have used before.
-
Junjie Zhu - MSFT 17,226 Reputation points • Microsoft Vendor
2023-09-04T08:06:37.9266667+00:00 Can this official sample help you? It uses
GattClientCharacteristicConfigurationDescriptorValue.None
to clear the CCCD. -
Manickavasagam C 0 Reputation points
2023-09-04T09:30:30.41+00:00 I will try that
GattClientCharacteristicConfigurationDescriptorValue.None
private async Task<bool> DisconnectDevice(BluetoothLEDevice device) { if (characteristic != null) { var result = await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.None); if (result != GattCommunicationStatus.Success) { return false; } else { characteristic.ValueChanged -= Characteristic_ValueChanged; } } device?.Dispose(); int n = 0; while (device.ConnectionStatus != BluetoothConnectionStatus.Disconnected) { await Task.Delay(1000); // Wait for the device to disconnect Debug.WriteLine($"Checking Disconnection Status!, Delay Seconds: {n}"); n++; } device = null; return true; }
It more than a 4min, Still the device not disconnecting from the system.
-
Junjie Zhu - MSFT 17,226 Reputation points • Microsoft Vendor
2023-09-04T09:58:49.5966667+00:00 Can this behavior be reproduced on other devices?
-
Manickavasagam C 0 Reputation points
2023-09-04T10:16:49.75+00:00 Yes, I'm Developing a UWP Application. When I'm trying to new device, I want to disconnect the previous connected device. At times, When I use the device.Dispose(); The device is not disconnected from the system( When I check with my windows Bluetooth, it shows Connected(1));
-
Junjie Zhu - MSFT 17,226 Reputation points • Microsoft Vendor
2023-09-05T08:50:18.5933333+00:00 How about setting
bluetoothLeDevice = null
directly afterDispose()
like the official sample? -
Deleted
This comment has been deleted due to a violation of our Code of Conduct. The comment was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.
-
Roy Li - MSFT 32,921 Reputation points • Microsoft Vendor
2023-09-15T01:39:21.7266667+00:00 Any updates about this issue? Have checked Junjie Zhu's suggestion?
Sign in to comment