diff --git a/custom_components/trias/__init__.py b/custom_components/trias/__init__.py index 9830948..2e5a31a 100644 --- a/custom_components/trias/__init__.py +++ b/custom_components/trias/__init__.py @@ -31,15 +31,6 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: update_interval=DEFAULT_SCAN_INTERVAL, ) - try: - setup_ok = await hass.async_add_executor_job(coordinator.setup) - - except RequestException as err: - raise ConfigEntryNotReady from err - if not setup_ok: - _LOGGER.error("Could not setup integration") - return False - await coordinator.async_config_entry_first_refresh() entry.async_on_unload(entry.add_update_listener(_async_update_listener)) diff --git a/custom_components/trias/coordinator.py b/custom_components/trias/coordinator.py index 8b9e00c..7414f16 100644 --- a/custom_components/trias/coordinator.py +++ b/custom_components/trias/coordinator.py @@ -13,6 +13,10 @@ from .trias_client import client as trias from .trias_client.exceptions import ApiError, InvalidLocationName + +from homeassistant.exceptions import ConfigEntryNotReady +from requests.exceptions import RequestException + _LOGGER = logging.getLogger(__name__) @@ -40,6 +44,8 @@ def __init__( self._entry = entry self._config = entry.options + self._setup = False + self._url: str = entry.data["url"] self._api_key: str = entry.data.get("api_key", "") @@ -53,7 +59,7 @@ def __init__( self.trips = {} - def setup(self) -> bool: + async def setup(self) -> bool: """Set up the Trias API.""" stop_id_dict = {} @@ -69,7 +75,9 @@ def setup(self) -> bool: } try: - station_data = self.client.get_station_data(stop_id) + station_data = await self.hass.async_add_executor_job( + self.client.get_station_data, stop_id + ) except ApiError as error: _LOGGER.error("Could not request data for %s reason %s", stop_id, error) stop_dict["ok"] = False @@ -116,8 +124,12 @@ def setup(self) -> bool: from_location_name, to_location_name = list(locations.values()) try: - from_station_data = self.client.get_station_data(from_location_id) - to_station_data = self.client.get_station_data(to_location_id) + from_station_data = await self._hass.async_add_executor_job( + self.client.get_station_data, from_location_id + ) + to_station_data = await self._hass.async_add_executor_job( + self.client.get_station_data, to_location_id + ) except ApiError as error: _LOGGER.error( @@ -171,6 +183,17 @@ def setup(self) -> bool: async def _async_update_data(self) -> dict: """Get the latest data from the Trias API.""" + + if not self._setup: + try: + setup_ok = await self.setup() + except RequestException as err: + raise ConfigEntryNotReady from err + if not setup_ok: + _LOGGER.error("Could not setup integration") + return False + self._setup = True + _LOGGER.debug("Fetching new data from Trias API") for stop_id, data in self.stops.items():