bleak icon indicating copy to clipboard operation
bleak copied to clipboard

I'd like to ask how to solve the error "OSError: [WinError -2140864509] Unable to write to the property".

Open songjie1121 opened this issue 9 months ago • 1 comments

Dear author, during the process of extracting the heart - rate detection data from the Xiaomi Mi Band 6 using the bleak package, I've consistently faced errors, and I haven't been able to find a definite solution. I'm reaching out to kindly request your guidance on how to resolve this problem. Below are the source code and the corresponding error details.

import_ asyncio
from bleak import BleakScanner, BleakClient
from Crypto.Cipher import AES
import time

AuthKey = "a9999986cba7f4c2a3bd59fb5d18f70d"
Truekey = bytes.fromhex(AuthKey)
Mac = "C4:95:CA:95:1F:D0"
CHARACTERISTIC_AUTH = "00000009-0000-3512-2118-0009af100700"
CHARACTERISTIC_HEART_RATE_MEASURE = "00002a37-0000-1000-8000-00805f9b34fb"
CHARACTERISTIC_HEART_RATE_CONTROL = "00002a39-0000-1000-8000-00805f9b34fb"
_send_enc_key = b'\x03\x00'
global cmd


def notification_handler(sender, data):
    if len(data) == 2:
        a = data.hex()[2:4]
        b = int(a, 16)
        print(b)
    elif data[:3] == b'\x10\x02\x01':
        random_nr = data[3:]
        print(f"接收到的 random_nr 长度22222: {len(random_nr)}")  # 添加这一行
        if len(random_nr) % 16 != 0:
            print("random_nr 长度不是 16 的倍数,可能存在问题")
        aes = AES.new(Truekey, AES.MODE_ECB)
        try:
            truedata = aes.encrypt(random_nr)
            global cmd
            cmd = _send_enc_key + truedata
            print("认证密钥生成成功")
        except Exception as e:
            print(f"加密过程中出现错误: {e}")


async def main():
    global cmd
    # 扫描设备
    devices = await BleakScanner.discover()
    print("可用的蓝牙设备:")
    for device in devices:
        print(f"地址: {device.address}, 名称: {device.name}")

    target_device = next((device for device in devices if device.address == Mac), None)
    if target_device is None:
        print(f"未找到地址为 {Mac} 的设备。")
        return

    client = BleakClient(target_device,winrt=dict(use_cached_services=False))
    print("连接中")
    client._timeout = 100
    await client.connect()
    await client.start_notify(CHARACTERISTIC_AUTH, notification_handler)
    print("验证中")
    await client.write_gatt_char(CHARACTERISTIC_AUTH, b'\x02\x00')
    await asyncio.sleep(3.0)
    await client.write_gatt_char(CHARACTERISTIC_AUTH, cmd)
    await asyncio.sleep(1.5)
    # 启用心率通知(关键修改)
    print("配置心率监测...")

    await client.start_notify(CHARACTERISTIC_HEART_RATE_MEASURE, notification_handler)
    print("连接完成,请稍等十秒左右完成首次测量")
    await client.write_gatt_char(CHARACTERISTIC_HEART_RATE_CONTROL, b'\x15\x01\x00', True)
    await asyncio.sleep(1.0)
    await client.write_gatt_char(CHARACTERISTIC_HEART_RATE_CONTROL, b'\x15\x02\x00', True)
    await asyncio.sleep(1.0)
    await client.write_gatt_char(CHARACTERISTIC_HEART_RATE_CONTROL, b'\x15\x02\x01', True)
    t = time.time()
    while True:
        time.sleep(1)
        if (time.time() - t) >= 12:
            await client.write_gatt_char(CHARACTERISTIC_HEART_RATE_CONTROL, b'\x16', True)
            t = time.time()


asyncio.run(main())
Traceback (most recent call last):
  File "D:\kf\kf\Mi_band6_NFC\mi_xinglv.py", line 77, in <module>
    asyncio.run(main())
  File "D:\Anaconda\envs\kf\Lib\asyncio\runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "D:\Anaconda\envs\kf\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Anaconda\envs\kf\Lib\asyncio\base_events.py", line 654, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "D:\kf\kf\Mi_band6_NFC\mi_xinglv.py", line 64, in main
    await client.write_gatt_char(CHARACTERISTIC_HEART_RATE_CONTROL, b'\x15\x01\x00', True)
  File "D:\Anaconda\envs\kf\Lib\site-packages\bleak\__init__.py", line 786, in write_gatt_char
    await self._backend.write_gatt_char(characteristic, data, response)
  File "D:\Anaconda\envs\kf\Lib\site-packages\bleak\backends\winrt\client.py", line 905, in write_gatt_char
    _ensure_success(
  File "D:\Anaconda\envs\kf\Lib\site-packages\bleak\backends\winrt\client.py", line 160, in _ensure_success
    raise BleakError(
bleak.exc.BleakError: Could not write value b'\x15\x01\x00' to characteristic 002B: Protocol Error 0x03: Write Not Permitted

songjie1121 avatar Mar 31 '25 10:03 songjie1121

Protocol Error 0x03: Write Not Permitted

The error explains the problem. This characteristic is not writable.

You can use the service explorer example in Bleak to enumerate the properties of each characteristic. Maybe write without response works on that characteristic?

dlech avatar Mar 31 '25 13:03 dlech