micropython-lib icon indicating copy to clipboard operation
micropython-lib copied to clipboard

aioble: Use DeviceDisconnectedError for disconnected guards.

Open andrewleech opened this issue 4 years ago • 0 comments

Summary

When a BLE peer disconnects during L2CAP operations, callers get a mix of ValueError("Not connected"), bare L2CAPDisconnectedError(Exception), and OSError: [Errno 22] EINVAL depending on exactly which code path detects the disconnection first. Application code that catches DeviceDisconnectedError for clean disconnect handling (as the l2cap_file_server example does) misses all three.

This PR unifies the disconnect signalling:

  • L2CAPDisconnectedError becomes a subclass of DeviceDisconnectedError, so except DeviceDisconnectedError catches mid-operation L2CAP disconnections.
  • ValueError("Not connected") guards in L2CAPChannel.__init__, DeviceConnection.exchange_mtu, and Characteristic.indicate are replaced with the appropriate DeviceDisconnectedError (or subclass).
  • OSError(EINVAL) from the low-level ble.l2cap_send(), ble.l2cap_recvinto(), and ble.l2cap_disconnect() calls is caught and converted to L2CAPDisconnectedError. The BLE stack returns EINVAL when the connection handle or CID is no longer valid — semantically identical to a disconnection but previously not converted. disconnect() additionally sets _cid = None and returns cleanly since the channel is already gone.

Testing

Tested on STM32WB55 with an OTS (Object Transfer Service) file transfer interrupted by client disconnect. Before: three OSError: [Errno 22] EINVAL ERROR tracebacks per disconnect cycle. After: single INFO log "Transfer incomplete due to client disconnect".

Trade-offs and Alternatives

Could catch all OSError rather than checking errno == EINVAL specifically, but EINVAL is the only errno observed for this failure mode and catching broadly could mask real errors (e.g. ENOMEM).

andrewleech avatar Dec 07 '21 00:12 andrewleech