Bleak not disconnecting automatically when run and stopped/interrupted with PyCharm
See original GitHub issue- bleak version: 0.12.1
- Python version: 3.9
- Operating System: PopOS 21.04 (based on Ubuntu)
- BlueZ version (
bluetoothctl -v
) in case of Linux: 5.56
Description
I connect to my BLE hardware device using python3 and Bleak and I send a LED command every 5 seconds indefinitely. The device blinks its LEDs and answers back. It works perfectly. However, when I stop the code (I use Pycharm and I press the red stop button), the snippet never works again unless I reset the Bluetooth subsystem (systemctl restart bluetooth). It seems I am suffering from the issue in line #348 of client.py in master branch, which states something like " Otherwise BlueZ will keep the device connected even after Python exits". I think I can confirm this since, when I run the code again it comes up with the error “bleak.exc.BleakError: Device with address <my_mac_below> was not found.” It cannot be found because it is not advertising since it is still connected in the background 😦
Also, in my hardware device logging subsystem, I see Bleak never tells it to disconnect. My other apps with other frameworks automatically disconnect if code is no longer working. I have seen this issue around the forum but tested some of the suggestions (some of the branches are not existing anymore) and it does not seem to be solved. Maybe I am missing some parameters on BleakClient()? Gonna check issue #377 again meanwhile.
This seems a great project. Let me know if I can do some testing around all this.
What I Did
Please see my code example 😃 I simply activate notifications on UUID_C. Then I write commands on UUID_W.
import logging
import asyncio
import bleak.exc
from bleak import BleakClient, discover
logging.basicConfig(level=logging.INFO)
UUID_C = 'f0001132-0451-4000-b000-000000000000'
UUID_W = 'f0001131-0451-4000-b000-000000000000'
addr = '04:EE:03:6C:EF:30'
def notification_handler(_, data):
print(data)
async def main(mac):
try:
disconnected_event = asyncio.Event()
def disconnected_callback(client):
print("Disconnected callback called!")
disconnected_event.set()
async with BleakClient(mac, disconnected_callback=disconnected_callback) as client:
await client.start_notify(UUID_C, notification_handler)
# this blinks some LEDs in my hardware device :)
v = b'LED \r'
while 1:
await client.write_gatt_char(UUID_W, v)
await asyncio.sleep(5)
except bleak.exc.BleakError as ex:
print('-- {}'.format(ex))
if __name__ == "__main__":
asyncio.run(main(addr))
Issue Analytics
- State:
- Created 2 years ago
- Comments:11 (2 by maintainers)
Top GitHub Comments
In order to make disconnecting work correctly after an unhandled exception, replace:
with
I just tried to reproduce the issue using a fresh install of:
and
examples/disconnect_callback.py
.The device disconnected as expected when pressing the stop button in PyCharm. So I’m not sure why your PyCharm would be different.