MacOS: scanning in new thread raises BleakError("Bluetooth device is turned off")
See original GitHub issue- bleak version: 0.6.4
- Python version: 3.8.2
- Operating System: MacOS 10.15.4
Trying to do scanning in a new thread raises BleakError("Bluetooth device is turned off")
. Run the program below with and without --thread
. In the latter case, the error is raised, but the program works fine with everything in the same thread.
Using BleakScanner
rather than discover
has the same problem.
This program runs fine on Linux with BlueZ, and on Windows 10 with Python 3.7.7 and pythonnet.
This sounds sort of like #93 and #125, but those were BlueZ problems. This stackoverflow Q&A may also be of interest, though I don’t know corebluetooth well enough to confirm: https://stackoverflow.com/questions/48958267/how-can-i-use-corebluetooth-for-python-without-giving-up-the-main-thread
The reason I’m using a second thread is that I’m re-implementing an existing non-async
BLE API using bleak. I was using a fresh thread for the bleak async
side of things, and a janus
queue to pass back scanning results.
import asyncio
from bleak import discover
from threading import Thread
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--thread', action='store_true')
args = parser.parse_args()
async def scan():
devices = await discover()
for d in devices:
print(d)
def run():
asyncio.run(scan(), debug=True)
if args.thread:
print("in separate thread")
t = Thread(target=run)
t.start()
t.join()
else:
print("in main thread")
loop = asyncio.get_event_loop()
loop.run_until_complete(scan())
Issue Analytics
- State:
- Created 3 years ago
- Comments:16 (8 by maintainers)
Top GitHub Comments
I had the same error as the title of this issue without using threads. The changes I made in https://github.com/pybricks/bleak/commit/26ab00f4d619f1db2618462a70b40e85bbcb3dd1 and https://github.com/pybricks/bleak/commit/0b37282af230c0b1161daaaa399a5bf328f28681 fixed the issue for me. But ideally it would be nice to get rid of the global
CBAPP
object. It causes other os-specific quirks like #111.(@dhalbert in case you haven’t seen, it looks like BlueZ is getting better advertisement support: https://github.com/bluez/bluez/blob/master/doc/advertisement-monitor-api.txt - might be good to make sure it does what is needed while it is still experimental)
@dhalbert I have looked at
_bleio
; very nice! It would be great if bleak could cater nicely to that kind of environment as well! Hitherto, it has been focused on desktop only, with some at least support for Raspberry Pi.The scanning issue that you are mentioning, could you please open a separate issue for that, because that is something I did not know about. I have been getting
PropertiesChanged
notifications in from BlueZ during scanning, but that might not yield new data, only updated RSSI values?