diff --git a/custom_components/aigues_barcelona/__init__.py b/custom_components/aigues_barcelona/__init__.py index 28b1589..6a0d62d 100644 --- a/custom_components/aigues_barcelona/__init__.py +++ b/custom_components/aigues_barcelona/__init__.py @@ -13,6 +13,7 @@ from .api import AiguesApiClient from .const import DOMAIN +from .service import async_setup as setup_service # from homeassistant.exceptions import ConfigEntryNotReady @@ -41,6 +42,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) + await setup_service(hass, entry) + return True diff --git a/custom_components/aigues_barcelona/api.py b/custom_components/aigues_barcelona/api.py index f49b405..a8f1567 100644 --- a/custom_components/aigues_barcelona/api.py +++ b/custom_components/aigues_barcelona/api.py @@ -82,6 +82,8 @@ def _query(self, path, query=None, json=None, headers=None, method="GET"): raise Exception(f"Denied: {msg}") if resp.status_code == 400: raise Exception(f"Bad response: {msg}") + if resp.status_code == 429: + raise Exception(f"Rate-Limited: {msg}") return resp diff --git a/custom_components/aigues_barcelona/sensor.py b/custom_components/aigues_barcelona/sensor.py index 85a0dd2..0a4b240 100644 --- a/custom_components/aigues_barcelona/sensor.py +++ b/custom_components/aigues_barcelona/sensor.py @@ -113,6 +113,9 @@ def __init__( # create alias self._data = hass.data[DOMAIN][self.contract] + # WARN define a pointer to this object + hass.data[DOMAIN][self.contract]["coordinator"] = self + # the api object self._api = AiguesApiClient(username, password, contract) if token: @@ -252,6 +255,26 @@ async def _async_import_statistics(self, consumptions) -> None: # _LOGGER.debug(f"Adding metric: {metadata} {stats}") async_import_statistics(self.hass, metadata, stats) + async def clear_all_stored_data(self) -> None: + await self._clear_statistics() + + async def import_old_consumptions(self, days: int = 365) -> None: + today = datetime.now() + one_year_ago = today - timedelta(days=days) + + current_date = one_year_ago + while current_date < today: + consumptions = await self.hass.async_add_executor_job( + self._api.consumptions_week, current_date, self.contract + ) + + if consumptions: + await self._async_import_statistics(consumptions) + else: + _LOGGER.warning(f"No data available for {current_date}") + + current_date += timedelta(weeks=1) + class ContadorAgua(CoordinatorEntity, SensorEntity): """Representation of a sensor.""" diff --git a/custom_components/aigues_barcelona/service.py b/custom_components/aigues_barcelona/service.py new file mode 100644 index 0000000..c248267 --- /dev/null +++ b/custom_components/aigues_barcelona/service.py @@ -0,0 +1,39 @@ +import logging +from .const import DOMAIN + +from homeassistant.core import HomeAssistant, ServiceCall +from homeassistant.helpers.typing import ConfigType + +_LOGGER = logging.getLogger(__name__) + + +async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: + async def handle_reset_and_refresh_data(call: ServiceCall) -> None: + contract = next(iter(hass.data[DOMAIN]), None) + if not contract: + _LOGGER.error("No contracts available") + return + + coordinator = hass.data[DOMAIN].get(contract).get("coordinator") + if not coordinator: + _LOGGER.error(f"Contract coordinator for {contract} not found") + return + + _LOGGER.warning(f"Performing reset and refresh for {contract}") + + # TODO: Not working - Detected unsafe call not in recorder thread + # await clear_stored_data(hass, coordinator) + await fetch_historic_data(hass, coordinator) + + hass.services.async_register( + DOMAIN, "reset_and_refresh_data", handle_reset_and_refresh_data + ) + return True + + +async def clear_stored_data(hass: HomeAssistant, coordinator) -> None: + await coordinator._clear_statistics() + + +async def fetch_historic_data(hass: HomeAssistant, coordinator) -> None: + await coordinator.import_old_consumptions(days=365) diff --git a/custom_components/aigues_barcelona/services.yaml b/custom_components/aigues_barcelona/services.yaml new file mode 100644 index 0000000..6789238 --- /dev/null +++ b/custom_components/aigues_barcelona/services.yaml @@ -0,0 +1,6 @@ +--- +# Service call documentation for Aigues de Barcelona integration + +reset_and_refresh_data: + name: Reset and Refresh Data + description: WARNING! Reset all stored historic/metrics data and start getting metrics from 1 year ago, querying data weekly.