This commit is contained in:
Paulus Schoutsen committed 2019-07-31 12:25:30 -07:00
1 parent da05dfe708
commit 4de97abc3a
2676 files changed
+163166 -140084

No files matched your search

+89 -75
View File
@@ -8,8 +8,12 @@ import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_NAME, CONF_ENTITY_ID, EVENT_HOMEASSISTANT_START, STATE_UNKNOWN,
ATTR_UNIT_OF_MEASUREMENT)
CONF_NAME,
CONF_ENTITY_ID,
EVENT_HOMEASSISTANT_START,
STATE_UNKNOWN,
ATTR_UNIT_OF_MEASUREMENT,
)
from homeassistant.core import callback
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import async_track_state_change
@@ -18,43 +22,44 @@ from homeassistant.components.recorder.util import session_scope, execute
_LOGGER = logging.getLogger(__name__)
ATTR_AVERAGE_CHANGE = 'average_change'
ATTR_CHANGE = 'change'
ATTR_CHANGE_RATE = 'change_rate'
ATTR_COUNT = 'count'
ATTR_MAX_AGE = 'max_age'
ATTR_MAX_VALUE = 'max_value'
ATTR_MEAN = 'mean'
ATTR_MEDIAN = 'median'
ATTR_MIN_AGE = 'min_age'
ATTR_MIN_VALUE = 'min_value'
ATTR_SAMPLING_SIZE = 'sampling_size'
ATTR_STANDARD_DEVIATION = 'standard_deviation'
ATTR_TOTAL = 'total'
ATTR_VARIANCE = 'variance'
ATTR_AVERAGE_CHANGE = "average_change"
ATTR_CHANGE = "change"
ATTR_CHANGE_RATE = "change_rate"
ATTR_COUNT = "count"
ATTR_MAX_AGE = "max_age"
ATTR_MAX_VALUE = "max_value"
ATTR_MEAN = "mean"
ATTR_MEDIAN = "median"
ATTR_MIN_AGE = "min_age"
ATTR_MIN_VALUE = "min_value"
ATTR_SAMPLING_SIZE = "sampling_size"
ATTR_STANDARD_DEVIATION = "standard_deviation"
ATTR_TOTAL = "total"
ATTR_VARIANCE = "variance"
CONF_SAMPLING_SIZE = 'sampling_size'
CONF_MAX_AGE = 'max_age'
CONF_PRECISION = 'precision'
CONF_SAMPLING_SIZE = "sampling_size"
CONF_MAX_AGE = "max_age"
CONF_PRECISION = "precision"
DEFAULT_NAME = 'Stats'
DEFAULT_NAME = "Stats"
DEFAULT_SIZE = 20
DEFAULT_PRECISION = 2
ICON = 'mdi:calculator'
ICON = "mdi:calculator"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_SAMPLING_SIZE, default=DEFAULT_SIZE):
vol.All(vol.Coerce(int), vol.Range(min=1)),
vol.Optional(CONF_MAX_AGE): cv.time_period,
vol.Optional(CONF_PRECISION, default=DEFAULT_PRECISION):
vol.Coerce(int)
})
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_SAMPLING_SIZE, default=DEFAULT_SIZE): vol.All(
vol.Coerce(int), vol.Range(min=1)
),
vol.Optional(CONF_MAX_AGE): cv.time_period,
vol.Optional(CONF_PRECISION, default=DEFAULT_PRECISION): vol.Coerce(int),
}
)
async def async_setup_platform(hass, config, async_add_entities,
discovery_info=None):
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Statistics sensor."""
entity_id = config.get(CONF_ENTITY_ID)
name = config.get(CONF_NAME)
@@ -62,8 +67,9 @@ async def async_setup_platform(hass, config, async_add_entities,
max_age = config.get(CONF_MAX_AGE, None)
precision = config.get(CONF_PRECISION)
async_add_entities([StatisticsSensor(entity_id, name, sampling_size,
max_age, precision)], True)
async_add_entities(
[StatisticsSensor(entity_id, name, sampling_size, max_age, precision)], True
)
return True
@@ -71,15 +77,14 @@ async def async_setup_platform(hass, config, async_add_entities,
class StatisticsSensor(Entity):
"""Representation of a Statistics sensor."""
def __init__(self, entity_id, name, sampling_size, max_age,
precision):
def __init__(self, entity_id, name, sampling_size, max_age, precision):
"""Initialize the Statistics sensor."""
self._entity_id = entity_id
self.is_binary = self._entity_id.split('.')[0] == 'binary_sensor'
self.is_binary = self._entity_id.split(".")[0] == "binary_sensor"
if not self.is_binary:
self._name = '{} {}'.format(name, ATTR_MEAN)
self._name = "{} {}".format(name, ATTR_MEAN)
else:
self._name = '{} {}'.format(name, ATTR_COUNT)
self._name = "{} {}".format(name, ATTR_COUNT)
self._sampling_size = sampling_size
self._max_age = max_age
self._precision = precision
@@ -95,11 +100,13 @@ class StatisticsSensor(Entity):
async def async_added_to_hass(self):
"""Register callbacks."""
@callback
def async_stats_sensor_state_listener(entity, old_state, new_state):
"""Handle the sensor state changes."""
self._unit_of_measurement = new_state.attributes.get(
ATTR_UNIT_OF_MEASUREMENT)
ATTR_UNIT_OF_MEASUREMENT
)
self._add_state_to_queue(new_state)
@@ -111,16 +118,16 @@ class StatisticsSensor(Entity):
_LOGGER.debug("Startup for %s", self.entity_id)
async_track_state_change(
self.hass, self._entity_id, async_stats_sensor_state_listener)
self.hass, self._entity_id, async_stats_sensor_state_listener
)
if 'recorder' in self.hass.config.components:
if "recorder" in self.hass.config.components:
# Only use the database if it's configured
self.hass.async_create_task(
self._async_initialize_from_database()
)
self.hass.async_create_task(self._async_initialize_from_database())
self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_START, async_stats_sensor_startup)
EVENT_HOMEASSISTANT_START, async_stats_sensor_startup
)
def _add_state_to_queue(self, new_state):
"""Add the state to the queue."""
@@ -135,8 +142,11 @@ class StatisticsSensor(Entity):
self.ages.append(new_state.last_updated)
except ValueError:
_LOGGER.error("%s: parsing error, expected number and received %s",
self.entity_id, new_state.state)
_LOGGER.error(
"%s: parsing error, expected number and received %s",
self.entity_id,
new_state.state,
)
@property
def name(self):
@@ -188,14 +198,20 @@ class StatisticsSensor(Entity):
"""Remove states which are older than self._max_age."""
now = dt_util.utcnow()
_LOGGER.debug("%s: purging records older then %s(%s)",
self.entity_id, dt_util.as_local(now - self._max_age),
self._max_age)
_LOGGER.debug(
"%s: purging records older then %s(%s)",
self.entity_id,
dt_util.as_local(now - self._max_age),
self._max_age,
)
while self.ages and (now - self.ages[0]) > self._max_age:
_LOGGER.debug("%s: purging record with datetime %s(%s)",
self.entity_id, dt_util.as_local(self.ages[0]),
(now - self.ages[0]))
_LOGGER.debug(
"%s: purging record with datetime %s(%s)",
self.entity_id,
dt_util.as_local(self.ages[0]),
(now - self.ages[0]),
)
self.ages.popleft()
self.states.popleft()
@@ -209,19 +225,15 @@ class StatisticsSensor(Entity):
if not self.is_binary:
try: # require only one data point
self.mean = round(statistics.mean(self.states),
self._precision)
self.median = round(statistics.median(self.states),
self._precision)
self.mean = round(statistics.mean(self.states), self._precision)
self.median = round(statistics.median(self.states), self._precision)
except statistics.StatisticsError as err:
_LOGGER.debug("%s: %s", self.entity_id, err)
self.mean = self.median = STATE_UNKNOWN
try: # require at least two data points
self.stdev = round(statistics.stdev(self.states),
self._precision)
self.variance = round(statistics.variance(self.states),
self._precision)
self.stdev = round(statistics.stdev(self.states), self._precision)
self.variance = round(statistics.variance(self.states), self._precision)
except statistics.StatisticsError as err:
_LOGGER.debug("%s: %s", self.entity_id, err)
self.stdev = self.variance = STATE_UNKNOWN
@@ -246,8 +258,7 @@ class StatisticsSensor(Entity):
self.change_rate = self.average_change / time_diff
self.change = round(self.change, self._precision)
self.average_change = round(self.average_change,
self._precision)
self.average_change = round(self.average_change, self._precision)
self.change_rate = round(self.change_rate, self._precision)
else:
@@ -267,24 +278,28 @@ class StatisticsSensor(Entity):
current datetime - MaxAge.
"""
from homeassistant.components.recorder.models import States
_LOGGER.debug("%s: initializing values from the database",
self.entity_id)
_LOGGER.debug("%s: initializing values from the database", self.entity_id)
with session_scope(hass=self.hass) as session:
query = session.query(States)\
.filter(States.entity_id == self._entity_id.lower())
query = session.query(States).filter(
States.entity_id == self._entity_id.lower()
)
if self._max_age is not None:
records_older_then = dt_util.utcnow() - self._max_age
_LOGGER.debug("%s: retrieve records not older then %s",
self.entity_id, records_older_then)
_LOGGER.debug(
"%s: retrieve records not older then %s",
self.entity_id,
records_older_then,
)
query = query.filter(States.last_updated >= records_older_then)
else:
_LOGGER.debug("%s: retrieving all records.", self.entity_id)
query = query\
.order_by(States.last_updated.desc())\
.limit(self._sampling_size)
query = query.order_by(States.last_updated.desc()).limit(
self._sampling_size
)
states = execute(query)
for state in reversed(states):
@@ -292,5 +307,4 @@ class StatisticsSensor(Entity):
self.async_schedule_update_ha_state(True)
_LOGGER.debug("%s: initializing from database completed",
self.entity_id)
_LOGGER.debug("%s: initializing from database completed", self.entity_id)