Skip to content

Commit 89bd38f

Browse files
committed
chore: extract caching logic to one place
1 parent 0aebe13 commit 89bd38f

File tree

1 file changed

+18
-11
lines changed

1 file changed

+18
-11
lines changed

roborock/devices/v1_channel.py

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -220,17 +220,7 @@ async def _background_reconnect(self) -> None:
220220
await asyncio.sleep(reconnect_backoff.total_seconds())
221221
reconnect_backoff = min(reconnect_backoff * RECONNECT_MULTIPLIER, MAX_RECONNECT_INTERVAL)
222222

223-
# First failure refreshes cache. Subsequent failures use the cache
224-
# until the refresh interval expires.
225-
use_cache = True
226-
if local_connect_failures == 1:
227-
use_cache = False
228-
elif self._last_network_info_refresh and (
229-
datetime.datetime.now(datetime.timezone.utc) - self._last_network_info_refresh
230-
> NETWORK_INFO_REFRESH_INTERVAL
231-
):
232-
use_cache = False
233-
223+
use_cache = self._should_use_cache(local_connect_failures)
234224
await self._local_connect(use_cache=use_cache)
235225
# Reset backoff and failures on success
236226
reconnect_backoff = MIN_RECONNECT_INTERVAL
@@ -246,6 +236,23 @@ async def _background_reconnect(self) -> None:
246236
except Exception:
247237
_LOGGER.exception("Unhandled exception in background reconnect task")
248238

239+
def _should_use_cache(self, local_connect_failures: int) -> bool:
240+
"""Determine whether to use cached network info on retries.
241+
242+
On the first retry we'll avoid the cache to handle the case where
243+
the network ip may have recently changed. Otherwise, use the cache
244+
if available then expire at some point.
245+
"""
246+
if local_connect_failures == 1:
247+
return False
248+
elif self._last_network_info_refresh and (
249+
datetime.datetime.now(datetime.timezone.utc) - self._last_network_info_refresh
250+
> NETWORK_INFO_REFRESH_INTERVAL
251+
):
252+
return False
253+
return True
254+
255+
249256
def _on_mqtt_message(self, message: RoborockMessage) -> None:
250257
"""Handle incoming MQTT messages."""
251258
_LOGGER.debug("V1Channel received MQTT message from device %s: %s", self._device_uid, message)

0 commit comments

Comments
 (0)