p4a: disconnect on connection failure
If there is a failure after connecting but before the connect method returns, we need to disconnect, otherwise we end up in a bad state.
@@ -71,6 +71,8 @@ class BleakClientP4Android(BaseBleakClient):
self.__callbacks = _PythonBluetoothGattCallback(self, loop)
+ self._subscriptions = {}
+
logger.debug("Connecting to BLE device @ {0}".format(self.address))
(self.__gatt,) = await self.__callbacks.perform_and_wait(
@@ -86,10 +88,9 @@ class BleakClientP4Android(BaseBleakClient):
return_indicates_status=False,
)
+ try:
logger.debug("Connection successful.")
- self._subscriptions = {}
-
# unlike other backends, Android doesn't automatically negotiate
# the MTU, so we request the largest size possible like BlueZ
logger.debug("requesting mtu...")
@@ -107,6 +108,15 @@ class BleakClientP4Android(BaseBleakClient):
)
await self.get_services()
+ except BaseException:
+ # if connecting is canceled or one of the above fails, we need to
+ # disconnect
+ try:
+ await self.disconnect()
+ except Exception:
+ pass
+ raise
+
return True
async def disconnect(self) -> bool:
