Skip to content

Windows 11 - BLE device stays connected even after calling disconnect from bleak #1949

@EyalboiP

Description

@EyalboiP

OS: Windows 11
bleak version info:
Name: bleak
Version: 3.0.0
Summary: Bluetooth Low Energy platform Agnostic Klient
Home-page: https://github.com/hbldh/bleak
Author: Henrik Blidh
Author-email: henrik.blidh@nedomkull.com
License-Expression: MIT
Location: C:\Users\automation\AppData\Roaming\Python\Python312\site-packages
Requires: winrt-runtime, winrt-Windows.Devices.Bluetooth, winrt-Windows.Devices.Bluetooth.Advertisement, winrt-Windows.Devices.Bluetooth.GenericAttributeProfile, winrt-Windows.Devices.Enumeration, winrt-Windows.Devices.Radios, winrt-Windows.Foundation, winrt-Windows.Foundation.Collections, winrt-Windows.Storage.Streams

79:74:E0:F4:DE:2A
starting connection
connected
Negotiated MTU: 256
disconnected
not connected

Image

code ran:

import time
import bleak
import asyncio
import platform
import traceback
from bleak import BleakClient

if platform.system().lower() == "windows":
    try:
        from bleak.backends.winrt.util import uninitialize_sta
    except ImportError:
        uninitialize_sta = None
else:
    uninitialize_sta = None


TARGET_NAME = "M6971WZZ"
def _mac_to_int(address: str) -> int:
    return int(address.replace(":", "").replace("-", ""), 16)

async def allow_sta() -> None:
    # Only call the WinRT helper when it is available.
    if uninitialize_sta is not None:
        uninitialize_sta()

asyncio.run(allow_sta())
time.sleep(1)
async def force_windows_disconnect(address: str) -> None:
    if platform.system().lower() != "windows":
        return
    try:
        print("Trying to force disconnect")
        from winrt.windows.devices.bluetooth import BluetoothLEDevice
        ble_device = await BluetoothLEDevice.from_bluetooth_address_async(
            _mac_to_int(address)
        )
        print("ble_device: ", ble_device)
        if ble_device is not None:
            print("Closing winrt device handle")
            ble_device.close()
            print("winrt device handle closed")
    except ImportError:
        print("winrt not installed, skipping forced disconnect")
    except Exception as exc:
        print(f"winrt forced disconnect failed: {exc}")

async def main():
    devices = await bleak.BleakScanner.discover()
    for device in devices:
        if device.name == TARGET_NAME:
            print(f"{device.address}\nstarting connection")
            client = BleakClient(device.address)
            await client.connect()
            print("connected")
            await asyncio.sleep(2)
            mtu = client.mtu_size
            print("Negotiated MTU:", mtu)
            # await client.pair()
            # print("paired")
            await asyncio.sleep(2)
            # await client.unpair()
            # print("unpaired")
            await asyncio.sleep(2)
            disconnect_timeout = 10
            try:
                await asyncio.wait_for(client.disconnect(), timeout=disconnect_timeout)
                print("disconnected")
            except Exception as exc:
                print(f"disconnect failed: {exc}")
                print(f"Traceback errors: {traceback.format_exc()}")
            await asyncio.sleep(1)
            if client.is_connected:
                print("connected")
            else:
                print("not connected")
            return

    print(f"{TARGET_NAME} not found")

if __name__ == "__main__":
    asyncio.run(main())

Metadata

Metadata

Assignees

No one assigned

    Labels

    3rd party issueThe issue is with the Bluetooth stack, the BLE device, or other 3rd party code not with Bleak itselfBackend: WinRTIssues or PRs relating to the WinRT backend

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions