Skip to content

Commit

Permalink
Move state metadata check into async_write_ha_historical_states
Browse files Browse the repository at this point in the history
  • Loading branch information
ldotlopez committed Feb 6, 2024
1 parent c8c59b5 commit b5ca6c2
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 17 deletions.
5 changes: 5 additions & 0 deletions homeassistant_historical_sensor/consts.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,10 @@
# USA.


from math import ceil

MIN_REQ_MAJOR_VERSION = 2023
MIN_REQ_MINOR_VERSION = 6

HOMEASSISTANT_INTERNAL_UPDATE_SECONDS = 30
DELAY_ON_MISSING_STATES_METADATA = ceil(HOMEASSISTANT_INTERNAL_UPDATE_SECONDS * 1.1)
44 changes: 28 additions & 16 deletions homeassistant_historical_sensor/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
from homeassistant.helpers.event import async_call_later, async_track_time_interval
from homeassistant.util import dt as dtutil

from .consts import DELAY_ON_MISSING_STATES_METADATA
from .patches import _build_attributes, _stringify_state
from .recorderutil import (
delete_entity_invalid_states,
Expand Down Expand Up @@ -130,12 +131,32 @@ async def async_update_historical(self):
"""
raise NotImplementedError()

async def async_write_ha_historical_states(self):
async def _schedule_on_missing_states_metadata(self, fn) -> bool:
metadata_id = await hass_get_entity_states_metadata_id(self.hass, self)
if metadata_id is not None:
return False

_LOGGER.debug(
f"{self.entity_id} not yet fully ready, StatesMeta object is not ready."
+ f"Retry in {DELAY_ON_MISSING_STATES_METADATA} seconds"
)

async_call_later(self.hass, DELAY_ON_MISSING_STATES_METADATA, fn)
return True

async def async_write_ha_historical_states(self, _=None):
"""async_write_ha_historical_states()
This method writes `self.historical_states` into database
"""

if await self._schedule_on_missing_states_metadata(
self.async_write_ha_historical_states
):
return

_LOGGER.debug(f"{self.entity_id} states medata ready")

hist_states = self.historical_states
if any([True for x in hist_states if x.dt.tzinfo is None]):
_LOGGER.error("historical_states MUST include tzinfo")
Expand All @@ -151,21 +172,21 @@ async def async_write_ha_historical_states(self):
return

# Write states
n = len(await self._async_write_recorder_states(hist_states))
n = len(await self._async_write_states(hist_states))
_LOGGER.debug(f"{self.entity_id}: {n} states written into the database")

# Write statistics
n = len(await self._async_write_statistic_data(hist_states))
n = len(await self._async_write_statistics(hist_states))
_LOGGER.debug(f"{self.entity_id}: {n} statistics points written into database")

async def _async_write_recorder_states(
async def _async_write_states(
self, hist_states: list[HistoricalState]
) -> list[HistoricalState]:
return await recorder.get_instance(self.hass).async_add_executor_job(
self._write_recorder_states, hist_states
self._recorder_write_states, hist_states
)

def _write_recorder_states(
def _recorder_write_states(
self, hist_states: list[HistoricalState]
) -> list[HistoricalState]:
with hass_recorder_session(self.hass) as session:
Expand Down Expand Up @@ -275,7 +296,7 @@ def _write_recorder_states(

return hist_states

async def _async_write_statistic_data(
async def _async_write_statistics(
self, hist_states: list[HistoricalState]
) -> list[HistoricalState]:
if self.statistic_id is None:
Expand Down Expand Up @@ -411,14 +432,5 @@ async def async_will_remove_from_hass(self) -> None:
self._remove_time_tracker_fn()

async def _async_historical_handle_update(self, _: datetime | None = None) -> None:
metadata_id = await hass_get_entity_states_metadata_id(self.hass, self)
if metadata_id is None:
retry_in = timedelta(seconds=30 * 1.05)
_LOGGER.debug(
f"{self.entity_id} not yet fully ready, StatesMeta object is not ready. Retry in {retry_in}"
)
async_call_later(self.hass, retry_in, self._async_historical_handle_update)
return

await self.async_update_historical()
await self.async_write_ha_historical_states()
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

[project]
name = "homeassistant-historical-sensor"
version = "2.0.0rc5"
version = "2.0.0rc6"
dependencies = [
"importlib-metadata; python_version >= '3.11'",
]
Expand Down

0 comments on commit b5ca6c2

Please sign in to comment.