Skip to content

Commit

Permalink
feat: add service to refresh data (#28)
Browse files Browse the repository at this point in the history
NOTE: This is partially implemented.
  • Loading branch information
duhow authored Oct 26, 2024
1 parent 0dbccc4 commit 5c06e2b
Show file tree
Hide file tree
Showing 5 changed files with 73 additions and 0 deletions.
3 changes: 3 additions & 0 deletions custom_components/aigues_barcelona/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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


Expand Down
2 changes: 2 additions & 0 deletions custom_components/aigues_barcelona/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
23 changes: 23 additions & 0 deletions custom_components/aigues_barcelona/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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."""
Expand Down
39 changes: 39 additions & 0 deletions custom_components/aigues_barcelona/service.py
Original file line number Diff line number Diff line change
@@ -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)
6 changes: 6 additions & 0 deletions custom_components/aigues_barcelona/services.yaml
Original file line number Diff line number Diff line change
@@ -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.

0 comments on commit 5c06e2b

Please sign in to comment.