hbldh / bleak

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

read_gatt_char() doesn't wait for new data #1543

Closed j-w-jones closed 2 weeks ago

j-w-jones commented 3 weeks ago

Description

I have a BLE server running on an ESP32 using Micropython. This sends two integers each second with each one being incremented by 1 each time.

I have successfully connected to the device using my laptop and when I call read_gatt_char() in a loop I was expecting the function to block until the next two integers were sent. Instead, the function returns immediately with the values last sent from the device.

What I Did

The code below runs and reads the data sent by the device correctly. However I was expecting it to print the two numbers once per second, e.g.

1 1 2 2 3 3

but, instead, it repeats the loop many times a second displaying a list like:

1 1 1 1 1 1 ... 1 1 2 2 2 2 2 2 .... 2 2 3 3 3 3 3 3 .... 3 3

async def main(address):
    client = bleak.BleakClient(address)
    try:
        await client.connect()

        while True:
            sensor_data = await client.read_gatt_char(ENV_SENSE_TEMP_UUID)
            (temp1, temp2) = struct.unpack(">hh", sensor_data)
            print(temp1, temp2)
    except Exception as e:
        print(e)
    finally:
        await client.disconnect()
dlech commented 3 weeks ago

BLE is a stateless protocol. Reading a characteristic always returns the current value. If you want to know when a value changes, have a look at notifications instead - if this characteristics support it.