hbldh / bleak

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

[WinError -2140864509] Error Writing Attribute with Bleak Library on Windows #1635

Open TancredeJean opened 2 months ago

TancredeJean commented 2 months ago

Description

What I Was Trying to Achieve:

I was attempting to use the Bleak library to establish a connection with a Bluetooth Low Energy (BLE) device and enable notifications for a specific characteristic. My goal was to receive real-time data from the device via BLE notifications.

What Happened:

When trying to start notifications for the BLE characteristic, I encountered the following error:

OSError: [WinError -2140864509] The attribute cannot be written

What Went Wrong:

The specific error [WinError -2140864509] The attribute cannot be written suggests that the system encountered an issue while trying to write to the characteristic attribute. This prevents the Bleak client from successfully enabling notifications.

What I Expected to Happen:

I expected the Bleak client to successfully enable notifications for the specified characteristic and start receiving real-time data. The notification handler should be called whenever new data is available from the BLE device.

What I Did

import asyncio
from bleak import BleakScanner, BleakClient

# Define the target device name and characteristic UUIDs
target_name = "***"
target_address = None
CHAR_ACC_UUID = "5266237b-0a94-45f6-b9d6-9a8f2482bac3"

async def notification_handler(sender, data):
    # This function will be called whenever a notification is received.
    print("Notification from {}: {}".format(sender, data.decode('utf-8')))

async def main():
    global target_address
    # Discover BLE devices
    devices = await BleakScanner.discover()
    for d in devices:
        print(d)
        if target_name == d.name:
            target_address = d.address
            print(f"Found target {target_name} Bluetooth device with address {target_address}")
            break

    if target_address is not None:
        async with BleakClient(target_address) as client:
            print(f"Connected: {client.is_connected}")

            # Start notifications
            await client.start_notify(CHAR_ACC_UUID, notification_handler)
            print("Started notifications...")

            # Keep the program running to receive notifications
            try:
                while True:
                    await asyncio.sleep(1)
            except KeyboardInterrupt:
                print("Program interrupted by user.")
                await client.stop_notify(CHAR_ACC_UUID)
    else:
        print("Could not find target Bluetooth device nearby")

asyncio.run(main())

Logs

Device: 03:E0:DF:64:48:A9, Name: None
Device: 2D:BE:65:5C:25:4C, Name: None
Device: 46:FD:14:21:86:EE, Name: None
Device: 7E:57:58:2B:E2:99, Name: None
Device: F0:F5:BD:51:A8:91, Name: ***
Found target *** Bluetooth device with address F0:F5:BD:51:A8:91
Connected: True
Traceback (most recent call last):
  File "your_script_name.py", line 41, in <module>
    asyncio.run(main())
  File "C:\Python\Lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main())
  File "C:\Python\Lib\asyncio\base_events.py", line 647, in run_until_complete
    return future.result()
  File "your_script_name.py", line 28, in main
    await client.start_notify(CHAR_ACC_UUID, notification_handler)
  File "C:\Python\Lib\site-packages\bleak\__init__.py", line 844, in start_notify
    await self._backend.start_notify(characteristic, wrapped_callback, **kwargs)
  File "C:\Python\Lib\site-packages\bleak\backends\winrt\client.py", line 981, in start_notify
    await winrt_char.write_client_characteristic_configuration_descriptor_async(
OSError: [WinError -2140864509] Impossible d’écrire l’attribut

Additional Attempts

I have also tried using the following during the initialization of the Bleak client to disable cached services:

BleakClient(..., winrt=dict(use_cached_services=False))

Unfortunately, this did not solve the issue.

dlech commented 2 months ago

Does this charcateristic actually support notifications? You can tell by running the service explorer example.

And I would suggest logging Bluetooth packets (see troubleshooting page in the docs) to see what the device is actually doing.