micropython / micropython-lib

Core Python libraries ported to MicroPython
Other
2.3k stars 981 forks source link

tempsensor.py example disconnects unexpectedly #807

Open Remco-Schoeman opened 4 months ago

Remco-Schoeman commented 4 months ago

at the line below the example waits for the connected client to disconnect. What is not obvious is that awaiting this disconnected() call causes an disconnect after 60 seconds!

https://github.com/micropython/micropython-lib/blob/8058b2935bad15f930a45a5f5f640c8da8aaf1f2/micropython/bluetooth/aioble/examples/temp_sensor.py#L58

It took me a long time reading code before I found the reason why: The timeout_ms parameter for the disconnected() call specifies a default timeout of 60 seconds for the wait, after which a CancelledError is raised, and the peripheral_task() exits, disconnecting the connection.

https://github.com/micropython/micropython-lib/blob/8058b2935bad15f930a45a5f5f640c8da8aaf1f2/micropython/bluetooth/aioble/aioble/device.py#L218

regrettably neither the CancelledError or the stacktrace give any clear indication of what happened.

As this is example code it might be nice to change the example to this instead:

    print("Connection from", connection.device)
    while connection.is_connected():
        temp_characteristic.notify(connection)
        await asyncio.sleep_ms(5_000)

which will push change notifications to the connected client every 5 sec or so, and not disconnect mysteriously (for micropython noobs like me in any case) after 60 seconds.

I can make a PR for this if desired.