Skip to content

Suggestion to work around failed updates #138

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
27 changes: 24 additions & 3 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,9 +44,29 @@ 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)
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:
# return the 'old' data on a failed update
_LOGGER.debug("Update failed, returning existing data")
return self.data

# Data update failed too many times, raise an error
_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
Loading