From 3036d80ef9fce5aa7fe17b1c568ce6369c758d24 Mon Sep 17 00:00:00 2001 From: Olivier Mehani Date: Thu, 27 Jul 2023 20:16:03 +1000 Subject: [PATCH] fixup! fixup! [WIP] Historical sensor #6 --- custom_components/auroraplus/sensor.py | 53 ++++++++++++++------------ 1 file changed, 28 insertions(+), 25 deletions(-) diff --git a/custom_components/auroraplus/sensor.py b/custom_components/auroraplus/sensor.py index b8a8057..e3f9073 100644 --- a/custom_components/auroraplus/sensor.py +++ b/custom_components/auroraplus/sensor.py @@ -177,17 +177,39 @@ def extra_state_attributes(self): attributes['Bill Overdue Amount'] = self._session.BillOverDueAmount return attributes - def async_update_historical(self): - # XXX - self.update() + async def async_update_historical(self): + await self._session.getday() + if self._sensor.startswith(SENSOR_KILOWATTHOURUSAGETARIFF): + tariff = self._sensor.removeprefix(SENSOR_KILOWATTHOURUSAGETARIFF) + + try: + _LOGGER.debug("Getting historical states for: %s", self._sensor) + await self._session.getday() + except OSError as err: + _LOGGER.error("Updating Aurora+ failed: %s", err) + metered_records = self._session.day.get( + 'MeteredUsageRecords' + ) + if not metered_records: + _LOGGER.warning(f"No daily records for {self._sensor}") + return + + self._historical_state = [ + HistoricalState( + state=r.get('KilowattHourUsage').get(tariff), + dt=datetime.datetime.fromisoformat(r['EndTime']) + ) + for r in metered_records + if r.get('KilowattHourUsage') + ] + _LOGGER.debug("Done with historical states for: %s", self._sensor) def update(self): """Collect updated data from Aurora+ API.""" try: - _LOGGER.debug("Updating sensor: %s", self._sensor) + # _LOGGER.debug("Updating sensor: %s", self._sensor) self._session.getcurrent() self._session.getsummary() - self._data = self._session except OSError as err: _LOGGER.error("Updating Aurora+ failed: %s", err) self._old_state = self._state @@ -201,26 +223,7 @@ def update(self): self._state = round( self._session.KilowattHourUsage['Total'], self._rounding) elif self._sensor.startswith(SENSOR_KILOWATTHOURUSAGETARIFF): - tariff = self._sensor.removeprefix(SENSOR_KILOWATTHOURUSAGETARIFF) - self._state = self._session.KilowattHourUsage.get(tariff) - if self._state: - self._state = round(self._state, self._rounding) - - self._session.getday() - metered_records = self._session.day.get( - 'MeteredUsageRecords' - ) - if not metered_records: - _LOGGER.warning(f"No daily records for {self._sensor}") - return - - self._historical_state = [ - HistoricalState( - state=(r.get('KilowattHourUsageAEST') or {}).get(tariff), - dt=datetime.datetime.fromisoformat(r['EndTime']) - ) - for r in metered_records - ] + pass else: _LOGGER.error("Unknown sensor type found")