diff --git a/homeassistant/components/sensor/history_stats.py b/homeassistant/components/sensor/history_stats.py index c76d2cefca0..a8d9276edc8 100644 --- a/homeassistant/components/sensor/history_stats.py +++ b/homeassistant/components/sensor/history_stats.py @@ -10,6 +10,7 @@ import math import voluptuous as vol +from homeassistant.core import callback from homeassistant.components import history import homeassistant.helpers.config_validation as cv import homeassistant.util.dt as dt_util @@ -19,7 +20,7 @@ from homeassistant.const import ( EVENT_HOMEASSISTANT_START) from homeassistant.exceptions import TemplateError from homeassistant.helpers.entity import Entity -from homeassistant.helpers.event import track_state_change +from homeassistant.helpers.event import async_track_state_change _LOGGER = logging.getLogger(__name__) @@ -94,8 +95,6 @@ class HistoryStatsSensor(Entity): self, hass, entity_id, entity_state, start, end, duration, sensor_type, name): """Initialize the HistoryStats sensor.""" - self._hass = hass - self._entity_id = entity_id self._entity_state = entity_state self._duration = duration @@ -109,15 +108,19 @@ class HistoryStatsSensor(Entity): self.value = None self.count = None - def force_refresh(*args): - """Force the component to refresh.""" - self.schedule_update_ha_state(True) + @callback + def start_refresh(*args): + """Register state tracking.""" + @callback + def force_refresh(*args): + """Force the component to refresh.""" + self.async_schedule_update_ha_state(True) - # Update value when home assistant starts - hass.bus.listen_once(EVENT_HOMEASSISTANT_START, force_refresh) + force_refresh() + async_track_state_change(self.hass, self._entity_id, force_refresh) - # Update value when tracked entity changes its state - track_state_change(hass, entity_id, force_refresh) + # Delay first refresh to keep startup fast + hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_refresh) @property def name(self):