extmod/bluetooth: handling of disconnect in ble_simple_central.py example is misleading
The handling of the disconnect event in ble_simple_central.py is misleading. The condition if conn_handle == self._conn_handle:
(line 108) makes it look as if a different value for conn_handle would mean that there's nothing to do, but this is not the case. In particular, a disconnect can happen during the connection process, at least with nimble on the esp32, in which case self._conn_handle is still None and conn_handle != self._conn_handle but calling self._reset() is necessary.
https://github.com/micropython/micropython/blob/203e1d2a65273db3f6ff063ba1124a89c3482c0f/examples/bluetooth/ble_simple_central.py#L108
tempsensor.py example disconnects unexpectedly
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.
I think this kind of issue was solved already by the merged PRs of 835 and 497.
closing per the above comment.
Please do feel free to re-open if you think additional clarification is needed.