client.set_disconnected_callback - callback does not appear to fire on disconnect
See original GitHub issue- bleak version: 0.8.0
- Python version: 3.8.5
- Operating System: Windows 10 2004, build 19041.508
Description
After connecting to a device, I am trying to set up a callback so that I am alerted if/when the device disappears (for instance if it wanders out of range, or waiting for confirmation of disconnect after await client.disconnect()
.
However, while the device definitely disconnects (be it through range, or being turned off, or await client.disconnect()
) the callback never runs and no errors are produced either.
I’m not entirely sure if I’m doing this right!
What I Did
For the purpose of testing, I put these two methods together in the class I’m implementing for BLE stuff; __callback_test()
is fed the target MAC address and then connects to the device, sets a disconnected_callback, pokes the GATT, then disconnects.
def __disconnect_callback(self):
# fires when a device is disconnected
print("Disconnect callback...")
async def __callback_test(self, mac):
print("Connecting to mac: {0}".format(mac), flush=True)
client = BleakClient(mac)
await client.connect()
# try to set a callback
client.set_disconnected_callback(self.__disconnect_callback)
# do something with the connection, blah blah
print("Poking services...".format(mac), flush=True)
await client.get_services()
# now disconnect
print("Trying disconnect...".format(mac), flush=True)
await client.disconnect()
Elsewhere in the class is the code to initiate the test:
mac = "[MAC address here]"
loop = asyncio.get_event_loop()
loop.run_until_complete(self.__callback_test(mac))
The console output is as below; the device shows a connection formed, then a few seconds later, disconnected, but the callback doesn’t appear to run from the console output. As stated before there is no error and the program is still running after this:
Connecting to mac: [MAC address here]
Poking services...
Trying disconnect...
Issue Analytics
- State:
- Created 3 years ago
- Comments:6 (3 by maintainers)
Top GitHub Comments
Thanks for all the advice, I really appreciate it!
I’ve found a way around the need for
await asyncio.sleep()
; in short I just don’t understand asyncio enough yet; the loop in my BLE handler that was listening for stdin was blocking…I’ve changed things around such that the class has a singular event loop:
This makes the message handler (which is now async) much cleaner:
And as for getting input from stdin:
With these tweaks I don’t need
asyncio.sleep()
and the disconnect callback fires as expected.Very good!
No, unbinding is not possible in Windows right now, due to several reasons. You should discard the client between uses and set up a new one each time to avoid it.