Skip to content

Commit

Permalink
suggestion to work around failed updates
Browse files Browse the repository at this point in the history
  • Loading branch information
jcjveraa committed Apr 16, 2024
1 parent 02be2fd commit 301405e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
2 changes: 2 additions & 0 deletions custom_components/knmi/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,5 @@
# Defaults
DEFAULT_NAME: Final = NAME
DEFAULT_SCAN_INTERVAL: Final = 300
# TODO by someone that understands HASS plugins better: make this user configurable, preferably in seconds rather than 'times'
FAILED_UPDATES_ALLOWANCE: Final = 6
24 changes: 20 additions & 4 deletions custom_components/knmi/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import pytz

from .api import KnmiApiClient
from .const import API_TIMEZONE, DOMAIN
from .const import API_TIMEZONE, DOMAIN, FAILED_UPDATES_ALLOWANCE

_LOGGER: logging.Logger = logging.getLogger(__package__)

Expand All @@ -21,6 +21,7 @@ class KnmiDataUpdateCoordinator(DataUpdateCoordinator):
"""Class to manage fetching data from the API."""

config_entry: ConfigEntry
failed_update_count = 0

def __init__(
self,
Expand All @@ -43,10 +44,25 @@ def __init__(
async def _async_update_data(self) -> dict[str, Any]:
"""Update data via library."""
try:
return await self.api.async_get_data()
data = await self.api.async_get_data()
# No exception from api.async_get_data() -> reset the failed update counter
self.failed_update_count = 0
return data
except Exception as exception:
_LOGGER.error("Update failed! - %s", exception)
raise UpdateFailed() from exception
self.failed_update_count += 1
_LOGGER.warning(
"Update failed %s times! - %s", self.failed_update_count, exception
)
# Do not throw an exception unless it's failed a few times to avoid excessive "unavailable" data
# in HASS
if self.failed_update_count > FAILED_UPDATES_ALLOWANCE:
_LOGGER.error(
"Update failed %s times, above limit of %s! - %s",
self.failed_update_count,
FAILED_UPDATES_ALLOWANCE,
exception,
)
raise UpdateFailed() from exception

def get_value(self, path: list[int | str], default=None) -> Any:
"""
Expand Down

0 comments on commit 301405e

Please sign in to comment.