Skip to content

Commit

Permalink
Optimize coordinator data update
Browse files Browse the repository at this point in the history
  • Loading branch information
andarotajo committed Apr 19, 2024
1 parent f7f1ce3 commit 848cfc5
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 16 deletions.
33 changes: 27 additions & 6 deletions homeassistant/components/dwd_weather_warnings/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from homeassistant.util import location

from .const import (
CONF_REGION_DEVICE_TRACKER,
Expand All @@ -23,7 +24,7 @@ class DwdWeatherWarningsCoordinator(DataUpdateCoordinator[None]):
"""Custom coordinator for the dwd_weather_warnings integration."""

config_entry: ConfigEntry
_api: DwdWeatherWarningsAPI
api: DwdWeatherWarningsAPI

def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Initialize the dwd_weather_warnings coordinator."""
Expand All @@ -32,11 +33,12 @@ def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
)

self._device_tracker = None
self._previous_position = None

async def async_config_entry_first_refresh(self) -> None:
"""Perform first refresh."""
if region_identifier := self.config_entry.data.get(CONF_REGION_IDENTIFIER):
self._api = await self.hass.async_add_executor_job(
self.api = await self.hass.async_add_executor_job(
DwdWeatherWarningsAPI, region_identifier
)
else:
Expand All @@ -54,8 +56,27 @@ async def _async_update_data(self) -> None:
except (EntityNotFoundError, AttributeError) as err:
raise UpdateFailed(f"Error fetching position: {repr(err)}") from err

self._api = await self.hass.async_add_executor_job(
DwdWeatherWarningsAPI, position
)
distance = None
if self._previous_position is not None:
distance = location.distance(
self._previous_position[0],
self._previous_position[1],
position[0],
position[1],
)

if distance is None or distance > 50:
# Only create a new object on the first update
# or when the distance to the previous position
# changes by more than 50 meters (to take GPS
# inaccuracy into account).
self.api = await self.hass.async_add_executor_job(
DwdWeatherWarningsAPI, position
)
else:
# Otherwise update the API to check for new warnings.
await self.hass.async_add_executor_job(self.api.update)

self._previous_position = position
else:
await self.hass.async_add_executor_job(self._api.update)
await self.hass.async_add_executor_job(self.api.update)
18 changes: 8 additions & 10 deletions homeassistant/components/dwd_weather_warnings/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,29 +95,27 @@ def __init__(
entry_type=DeviceEntryType.SERVICE,
)

self.api = coordinator._api

@property
def native_value(self) -> int | None:
"""Return the state of the sensor."""
if self.entity_description.key == CURRENT_WARNING_SENSOR:
return self.api.current_warning_level
return self.coordinator.api.current_warning_level

return self.api.expected_warning_level
return self.coordinator.api.expected_warning_level

@property
def extra_state_attributes(self) -> dict[str, Any]:
"""Return the state attributes of the sensor."""
data = {
ATTR_REGION_NAME: self.api.warncell_name,
ATTR_REGION_ID: self.api.warncell_id,
ATTR_LAST_UPDATE: self.api.last_update,
ATTR_REGION_NAME: self.coordinator.api.warncell_name,
ATTR_REGION_ID: self.coordinator.api.warncell_id,
ATTR_LAST_UPDATE: self.coordinator.api.last_update,
}

if self.entity_description.key == CURRENT_WARNING_SENSOR:
searched_warnings = self.api.current_warnings
searched_warnings = self.coordinator.api.current_warnings
else:
searched_warnings = self.api.expected_warnings
searched_warnings = self.coordinator.api.expected_warnings

data[ATTR_WARNING_COUNT] = len(searched_warnings)

Expand All @@ -144,4 +142,4 @@ def extra_state_attributes(self) -> dict[str, Any]:
@property
def available(self) -> bool:
"""Could the device be accessed during the last update call."""
return self.api.data_valid
return self.coordinator.api.data_valid

0 comments on commit 848cfc5

Please sign in to comment.