Skip to content

Commit

Permalink
Implement basic debouncer for fetching from REST API
Browse files Browse the repository at this point in the history
  • Loading branch information
WebSpider authored and Prior99 committed Sep 21, 2024
1 parent 60871ed commit eb3d69e
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion custom_components/myskoda/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.debounce import Debouncer
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from homeassistant.util.ssl import get_default_context
from myskoda import MySkoda, Vehicle
Expand All @@ -16,6 +17,24 @@
_LOGGER = logging.getLogger(__name__)


class MySkodaDebouncer(Debouncer):
"""Class to rate limit calls to MySkoda REST APIs."""

def __init__(self, hass: HomeAssistant) -> None:
"""Initialize debounce."""
super.__init__(hass, _LOGGER, cooldown=60.0, immediate=False)

async def async_call(self) -> None:
"""Call the intended function."""
# Restart timer when calling
self.async_cancel()
await super().async_call()

def has_pending_call(self) -> bool:
"""Is there a call pending already?"""
return self._execute_at_end_of_timer


class State:
vehicles: dict[str, Vehicle]
user: User
Expand All @@ -41,7 +60,11 @@ def __init__(self, hass: HomeAssistant, config: ConfigEntry) -> None:
"""Create a new coordinator."""

super().__init__(
hass, _LOGGER, name=DOMAIN, update_interval=timedelta(minutes=30)
hass,
_LOGGER,
name=DOMAIN,
update_interval=timedelta(minutes=30),
request_refresh_debouncer=MySkodaDebouncer(hass),
)
self.myskoda = MySkoda(async_get_clientsession(hass))
self.config = config
Expand Down

0 comments on commit eb3d69e

Please sign in to comment.