0

I am using the C# Windows.Devices.Bluetooth APIs to communicate with a device via BLE.

The BluetoothLEDevice class does not expose connect or disconnect methods but at least the connect can be forced by settings MaintainConnection to true, or by retrieving any GATT service (see here).

For disconnecting, however, there is no direct option. The only option seems to be to

[dispose] of all references to a BluetoothLEDevice object for a device (and if no other app on the system has a reference to the device) [Windows] will trigger an automatic disconnect after a small timeout period. (see here slightly further down)

Unfortunately, this behavior is not sufficient in my case. My connected BLE device requires receiving an explicit disconnect signal from my program when I close the connection.

My question is: does anyone know a reliable workaround, or perhaps a P/Invoke method, to explicitly trigger a disconnect?

From what I’ve read, the Bluetooth stack is managed directly by Windows, so this may not be possible. On the other hand, since Windows can detect when no object is holding a reference to a device and then initiate a disconnect, it seems like there should be a way to request this explicitly.

6
  • Yes, there is a workaround. First, you must close the session and the device (explicit call to Close() method for Device and session. Both implements IClosable interface). Unfortunately it does not work always as expected. Bluetooth Framework additionally forces disconnection by calling soma undocumented functions. Commented Sep 23 at 7:51
  • From the docu here it says that this method is not implemented in C#. I'll give it a try nonetheless. Commented Sep 23 at 9:14
  • I guess you should call Dispose() instead. I use direct call to WinRT interfaces so I can get access to IClosable. Try to cast the BluetoothLEDevice object to IClosable interface. Commented Sep 23 at 9:18
  • Yeah I checked here (see Notes to implementers). I cannot cast to IClosable as that does not exist in .net. Only IDisposable. The BluetoothLEDevice is already implements IDisposable. Calling dispose and setting the reference to null, however, is not enough. This just leads to the timeout disconnect handled by windows directly as described in the question. Are you using .net? Commented Sep 23 at 10:42
  • Yes, of course, .NET as well. However, as I wrote, in my products I prefer to have full control on what I'm doing so I use WinRT interfaces instead of .NET classes. So I have access to iClosable as well. Any way, there is other way (that is used by Bluetooth Framework internally) instead of using iClosable. Commented Sep 23 at 13:59

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.