Skip to content

Commit 73ea1cf

Browse files
committed
Connection timeout and stability
1 parent 6e03981 commit 73ea1cf

1 file changed

Lines changed: 13 additions & 3 deletions

File tree

custom_components/skykettle/kettle_connection.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ class KettleConnection(SkyKettle):
1414
UUID_SERVICE = "6e400001-b5a3-f393e-0a9e-50e24dcca9e"
1515
UUID_TX = "6e400002-b5a3-f393-e0a9-e50e24dcca9e"
1616
UUID_RX = "6e400003-b5a3-f393-e0a9-e50e24dcca9e"
17+
CONNECTION_TIMEOUT = 10
1718
BLE_RECV_TIMEOUT = 1.5
1819
MAX_TRIES = 3
1920
TRIES_INTERVAL = 0.5
@@ -90,7 +91,11 @@ async def _connect(self):
9091
self._device = bluetooth.async_ble_device_from_address(self.hass, self._mac)
9192
self._client = BleakClient(self._device)
9293
_LOGGER.debug("Connecting to the Kettle...")
93-
await self._client.connect()
94+
await asyncio.wait_for(
95+
# Bluez connection timeout is not working actually
96+
self._client.connect(timeout=KettleConnection.CONNECTION_TIMEOUT),
97+
timeout=KettleConnection.CONNECTION_TIMEOUT
98+
)
9499
_LOGGER.debug("Connected to the Kettle")
95100
await self._client.start_notify(KettleConnection.UUID_RX, self._rx_callback)
96101
_LOGGER.debug("Subscribed to RX")
@@ -99,9 +104,10 @@ async def _connect(self):
99104

100105
async def _disconnect(self):
101106
try:
102-
if self._client and self._client.is_connected:
107+
if self._client:
108+
was_connected = self._client.is_connected
103109
self._client.disconnect()
104-
_LOGGER.debug("Disconnected")
110+
if was_connected: _LOGGER.debug("Disconnected")
105111
finally:
106112
self._auth_ok = False
107113
self._device = None
@@ -114,11 +120,15 @@ async def disconnect(self):
114120
pass
115121

116122
async def _connect_if_need(self):
123+
if self._client and not self._client.is_connected:
124+
_LOGGER.debug("Connection lost")
125+
await self.disconnect()
117126
if not self._client or not self._client.is_connected:
118127
try:
119128
await self._connect()
120129
self._last_connect_ok = True
121130
except Exception as ex:
131+
await self.disconnect()
122132
self._last_connect_ok = False
123133
raise ex
124134
if not self._auth_ok:

0 commit comments

Comments
 (0)