Skip to content

Commit

Permalink
use code directly from coordinator
Browse files Browse the repository at this point in the history
  • Loading branch information
duhow committed Oct 26, 2024
1 parent 0fc0e7b commit ac9e92d
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 23 deletions.
16 changes: 10 additions & 6 deletions custom_components/aigues_barcelona/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,17 +258,21 @@ async def _async_import_statistics(self, consumptions) -> None:
async def clear_all_stored_data(self) -> None:
await self._clear_statistics()

async def fetch_metrics_from_one_year_ago(self) -> None:
async def import_old_consumptions(self, days: int = 365) -> None:
today = datetime.now()
one_year_ago = today - timedelta(days=365)
one_year_ago = today - timedelta(days=days)

current_date = one_year_ago
while current_date < today:
await self._async_import_statistics(
await self.hass.async_add_executor_job(
self._api.consumptions_week, current_date, self.contract
)
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)


Expand Down
20 changes: 3 additions & 17 deletions custom_components/aigues_barcelona/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,27 +26,13 @@ async def handle_reset_and_refresh_data(call: ServiceCall) -> None:

# TODO: Not working - Detected unsafe call not in recorder thread
#await clear_stored_data(hass, coordinator)
await fetch_historic_data(hass, coordinator, contract)
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, contract: str = None) -> None:
today = datetime.now()
one_year_ago = today - timedelta(days=365)

current_date = one_year_ago
while current_date < today:
consumptions = await hass.async_add_executor_job(
coordinator._api.consumptions_week, current_date, contract
)

if not consumptions:
_LOGGER.warning(f"No data available for {current_date}")
else:
await coordinator._async_import_statistics(consumptions)

current_date += timedelta(weeks=1)
async def fetch_historic_data(hass: HomeAssistant, coordinator) -> None:
await coordinator.import_old_consumptions(days=365)

0 comments on commit ac9e92d

Please sign in to comment.