Skip to content

Commit

Permalink
Introduce exponential backoff for MQTT reconnect (skodaconnect#263)
Browse files Browse the repository at this point in the history
* Make MQTT reconnect backoff exponential so we do not hammer MQTT server if it is in an error state
* Add self._reconnect_delay to init. Reset only upon succesfull complete subscribe
  • Loading branch information
WebSpider authored and zaptm committed Dec 8, 2024
1 parent 0c07237 commit 4623157
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
12 changes: 10 additions & 2 deletions myskoda/mqtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import ssl
from collections.abc import Awaitable, Callable
from datetime import UTC, datetime
from random import uniform
from typing import Any, cast

import aiomqtt
Expand Down Expand Up @@ -99,6 +100,7 @@ def __init__( # noqa: D107
self._listener_task = None
self._running = False
self._subscribed = asyncio.Event()
self._reconnect_delay = MQTT_RECONNECT_DELAY

async def connect(self, user_id: str, vehicle_vins: list[str]) -> None:
"""Connect to the MQTT broker and listen for messages for the given user_id and VINs."""
Expand Down Expand Up @@ -165,11 +167,17 @@ async def _connect_and_listen(self) -> None:
await client.subscribe(f"{self.user_id}/{vin}/account-event/{topic}")

self._subscribed.set()
self._reconnect_delay = MQTT_RECONNECT_DELAY
async for message in client.messages:
self._on_message(message)
except aiomqtt.MqttError as exc:
_LOGGER.info("Connection lost (%s); reconnecting in %ss", exc, MQTT_RECONNECT_DELAY)
await asyncio.sleep(MQTT_RECONNECT_DELAY)
_LOGGER.info(
"Connection lost (%s); reconnecting in %ss", exc, self._reconnect_delay
)
await asyncio.sleep(self._reconnect_delay)
self._reconnect_delay *= 2
self._reconnect_delay += uniform(0, 1) # noqa: S311
_LOGGER.debug("Increased reconnect backoff to %s", self._reconnect_delay)

def _on_message(self, msg: aiomqtt.Message) -> None:
"""Deserialize received MQTT message and emit Event to subscribed callbacks."""
Expand Down
2 changes: 1 addition & 1 deletion myskoda/myskoda.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ async def connect(self, email: str, password: str) -> None:
user = await self.get_user()
vehicles = await self.list_vehicle_vins()
await self.mqtt.connect(user.id, vehicles)
_LOGGER.debug("Myskoda ready.")
_LOGGER.debug("MySkoda ready.")

def subscribe(self, callback: Callable[[Event], None | Awaitable[None]]) -> None:
"""Listen for events emitted by MySkoda's MQTT broker."""
Expand Down

0 comments on commit 4623157

Please sign in to comment.