hbldh / bleak

A cross platform Bluetooth Low Energy Client for Python using asyncio
MIT License
1.6k stars 280 forks source link

bleak.exc.BleakError: Could not get GATT services: Unreachable #839

Closed snowuyl closed 1 year ago

snowuyl commented 2 years ago

Description

PythonNUS> python .\main.py
E8:20:9F:75:90:08
<class 'str'>
Traceback (most recent call last):
File "D:\workspace_Python3_Win10\PythonNUS\main.py", line 74, in
loop.run_until_complete(run(address, loop))
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 646, in run_until_complete
return future.result()
File "D:\workspace_Python3_Win10\PythonNUS\main.py", line 39, in run
async with BleakClient(address, loop=loop) as client:
File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\bleak\backends\client.py", line 61, in aenter
await self.connect()
File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\bleak\backends\winrt\client.py", line 276, in connect
await self.get_services()
File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\bleak\backends\winrt\client.py", line 451, in get_services
services: Sequence[GattDeviceService] = _ensure_success(
File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\bleak\backends\winrt\client.py", line 105, in _ensure_success
raise BleakError(f"{fail_msg}: Unreachable")
bleak.exc.BleakError: Could not get GATT services: Unreachable

main.zip

dlech commented 2 years ago

Contents of main.zip:

"""
Coyt Barringer - 2020

Test program demonstrating data transmission between Adafruit Bluefruit BLE libraries running 
on nrf52840 and Python

This uses the Nordic Uart Service (NUS) and should work concurrently with other BLE services such as HID

On the python side, the Bluetooth Low Energy platform Agnostic Klient for Python (Bleak) project
is used for Cross Platform Support and has been tested with windows 10

"""

import platform
import logging
import asyncio
from bleak import BleakClient
from bleak import BleakClient
from bleak import _logger as logger
from bleak.uuids import uuid16_dict

UART_TX_UUID = "6e400002-b5a3-f393-e0a9-e50e24dcca9e" #Nordic NUS characteristic for TX
UART_RX_UUID = "6e400003-b5a3-f393-e0a9-e50e24dcca9e" #Nordic NUS characteristic for RX

dataFlag = False #global flag to check for new data

def notification_handler(sender, data):
    """Simple notification handler which prints the data received."""
    print("{0}: {1}".format(sender, data))
    global dataFlag
    dataFlag = True

async def run(address, loop):
    print(address)
    print(type(address))
    async with BleakClient(address, loop=loop) as client:

        #wait for BLE client to be connected
        x = await client.is_connected()
        print("Connected: {0}".format(x))

        #wait for data to be sent from client
        await client.start_notify(UART_RX_UUID, notification_handler)

        while True : 

            #give some time to do other tasks
            await asyncio.sleep(0.01)

            #check if we received data
            global dataFlag
            if dataFlag :
                dataFlag = False

                #echo our received data back to the BLE device
                data = await client.read_gatt_char(UART_RX_UUID)
                await client.write_gatt_char(UART_TX_UUID,data)

if __name__ == "__main__":

    #this is MAC of our BLE device
    address = (
        "E8:20:9F:75:90:08"
    )

    #loop = asyncio.get_event_loop()
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(run(address, loop))
dlech commented 2 years ago

This seems to be a common error on Windows (I've seen it quite a bit in Web Bluetooth too, so it is possibly not just a Bleak problem).

Have you tried any of the suggested troubleshooting in the Bleak docs like enabling logging or capturing Bluetooth packets?

snowuyl commented 2 years ago
set BLEAK_LOGGING=1
python3 .\main.py
BleDeviceStruct(name='ANCS1', address='E8:20:9F:75:90:08', rssi=-36)
D:\ble.py:104: FutureWarning: is_connected has been changed to a property. Calling it as an async method will be removed in a future version
  x = await client.is_connected()
Connected: True
Connected: False
BleDeviceStruct(name='ANCS1', address='E8:20:9F:75:90:08', rssi=-36)
Connected: True
Connected: False
BleDeviceStruct(name='ANCS1', address='E8:20:9F:75:90:08', rssi=-36)
BleDeviceStruct(name='ANCS1', address='E8:20:9F:75:90:08', rssi=-36)
Traceback (most recent call last):
  File "D:\worker.py", line 37, in run
    result = self.fn(*self.args, **self.kwargs)
  File "D:\main_window.py", line 114, in _connect_device
    self.ble_obj.ble_uart_thread_function(ble_device)
  File "D:\ble.py", line 178, in ble_uart_thread_function
    loop.run_until_complete(self._run_uart(ble_device, loop))
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 646, in run_until_complete
    return future.result()
  File "D:\ble.py", line 101, in _run_uart
    async with BleakClient(ble_device.address, loop=loop) as client:
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\bleak\backends\client.py", line 61, in __aenter__
    await self.connect()
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\bleak\backends\winrt\client.py", line 276, in connect
    await self.get_services()
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\bleak\backends\winrt\client.py", line 451, in get_services
    services: Sequence[GattDeviceService] = _ensure_success(
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\bleak\backends\winrt\client.py", line 105, in _ensure_success
    raise BleakError(f"{fail_msg}: Unreachable")
bleak.exc.BleakError: Could not get GATT services: Unreachable
Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\locks.py", line 214, in wait
    await fut
asyncio.exceptions.CancelledError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\tasks.py", line 456, in wait_for
    return fut.result()
asyncio.exceptions.CancelledError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "D:\worker.py", line 37, in run
    result = self.fn(*self.args, **self.kwargs)
  File "D:\main_window.py", line 114, in _connect_device
    self.ble_obj.ble_uart_thread_function(ble_device)
  File "D:\ble.py", line 178, in ble_uart_thread_function
    loop.run_until_complete(self._run_uart(ble_device, loop))
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 646, in run_until_complete
    return future.result()
  File "D:\ble.py", line 101, in _run_uart
    async with BleakClient(ble_device.address, loop=loop) as client:
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\bleak\backends\client.py", line 61, in __aenter__
    await self.connect()
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\bleak\backends\winrt\client.py", line 268, in connect
    await asyncio.wait_for(event.wait(), timeout=timeout)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\tasks.py", line 458, in wait_for
    raise exceptions.TimeoutError() from exc
asyncio.exceptions.TimeoutError
snowuyl commented 2 years ago

ble.zip

snowuyl commented 2 years ago

Which tool do you suggest to capture Bluetooth packets on Windows?

dlech commented 2 years ago

Please see https://bleak.readthedocs.io/en/latest/troubleshooting.html#capture-bluetooth-traffic

snowuyl commented 2 years ago

connect_to_nRF52832_failed.zip The attached file is Wireshark log for connecting to nRF52832 device failed.

snowuyl commented 2 years ago

The following is another bleak log messages occurred at same time when capture Wireshark log.

python3 .\main.py
Waiting connecting to ANCS1
E8:20:9F:75:90:08
Exception in thread Thread-1 (thread_function):
Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\locks.py", line 214, in wait
    await fut
asyncio.exceptions.CancelledError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\tasks.py", line 456, in wait_for
    return fut.result()
asyncio.exceptions.CancelledError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\threading.py", line 1016, in _bootstrap_inner
    self.run()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\threading.py", line 953, in run
    self._target(*self._args, **self._kwargs)
  File "D:\andy\workspace_Python3_Win10\HrvPy\main.py", line 174, in thread_function
    loop.run_until_complete(run_uart(bt_mac_address, loop))
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 646, in run_until_complete
    return future.result()
  File "D:\andy\workspace_Python3_Win10\HrvPy\main.py", line 99, in run_uart
    async with BleakClient(address, loop=loop) as client:
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\bleak\backends\client.py", line 61, in __aenter__
    await self.connect()
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\bleak\backends\winrt\client.py", line 268, in connect
    await asyncio.wait_for(event.wait(), timeout=timeout)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\tasks.py", line 458, in wait_for
    raise exceptions.TimeoutError() from exc
asyncio.exceptions.TimeoutError
snowuyl commented 2 years ago
LE_Remove_device_from_white_list

From Wireshark log, I found one HCI command is strange, that is "LE Remove Device from White List".

dlech commented 2 years ago

Thanks for the logs. In the wireshark capture, we can see that Windows never connected to the device. Maybe you could try getting a different Bluetooth dongle and see if it makes a difference?

Also the most recent Bleak logs you have posted don't seem to match the example program that you have given, so are likely a different problem.

snowuyl commented 2 years ago
Intel_wireless_Bluetooth

Thanks for your reply! My labtop already has Intel Bluetooth device. How can I request bleak to use Nordic Bluetooth dongle?

snowuyl commented 2 years ago

The the most recent Bleak log messages is generated by the attached file main_2022_06_15.zip .

snowuyl commented 1 year ago

Which Bluetooth dongle do you suggest to use for bleak?

xudeyang commented 1 year ago

This error was solved by deleting the Bluetooth connected device, which may have been caused by multiple bluetooth connections

snowuyl commented 1 year ago

Which version solve this issue?

xudeyang commented 1 year ago

I just delete bluetooth-connected devices in the settings,my version is Bluetooth 5.0 Adapter

dlech commented 1 year ago

We have just added a new option to control the use of cached gatt services (#695) that could help with this.

Closing as duplicate of #740, so if there are any further updates, please post in that issue.