2021-05-16 17:23:37 +00:00
|
|
|
|
"""Statistics helper for sensor."""
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
2021-09-13 11:44:22 +00:00
|
|
|
|
from collections import defaultdict
|
2023-07-03 18:20:23 +00:00
|
|
|
|
from collections.abc import Callable, Iterable, MutableMapping
|
2021-05-16 17:23:37 +00:00
|
|
|
|
import datetime
|
2021-05-20 11:05:15 +00:00
|
|
|
|
import itertools
|
2021-06-29 10:20:10 +00:00
|
|
|
|
import logging
|
2021-09-08 15:05:16 +00:00
|
|
|
|
import math
|
2022-04-07 10:09:05 +00:00
|
|
|
|
from typing import Any
|
2021-05-16 17:23:37 +00:00
|
|
|
|
|
2021-09-30 15:14:36 +00:00
|
|
|
|
from sqlalchemy.orm.session import Session
|
|
|
|
|
|
|
|
|
|
from homeassistant.components.recorder import (
|
2022-09-12 16:53:05 +00:00
|
|
|
|
DOMAIN as RECORDER_DOMAIN,
|
2023-02-12 04:21:16 +00:00
|
|
|
|
get_instance,
|
2021-09-30 15:14:36 +00:00
|
|
|
|
history,
|
|
|
|
|
statistics,
|
|
|
|
|
util as recorder_util,
|
|
|
|
|
)
|
2021-09-22 20:31:33 +00:00
|
|
|
|
from homeassistant.components.recorder.models import (
|
|
|
|
|
StatisticData,
|
|
|
|
|
StatisticMetaData,
|
|
|
|
|
StatisticResult,
|
|
|
|
|
)
|
2022-10-11 11:51:28 +00:00
|
|
|
|
from homeassistant.const import (
|
|
|
|
|
ATTR_UNIT_OF_MEASUREMENT,
|
|
|
|
|
REVOLUTIONS_PER_MINUTE,
|
2022-12-08 17:41:38 +00:00
|
|
|
|
UnitOfIrradiance,
|
2022-12-08 19:06:02 +00:00
|
|
|
|
UnitOfSoundPressure,
|
2022-12-08 17:41:38 +00:00
|
|
|
|
UnitOfVolume,
|
2022-10-11 11:51:28 +00:00
|
|
|
|
)
|
2022-12-02 08:11:15 +00:00
|
|
|
|
from homeassistant.core import HomeAssistant, State, callback, split_entity_id
|
2021-09-30 14:49:16 +00:00
|
|
|
|
from homeassistant.exceptions import HomeAssistantError
|
2021-08-25 11:01:55 +00:00
|
|
|
|
from homeassistant.helpers.entity import entity_sources
|
2022-09-22 16:31:50 +00:00
|
|
|
|
from homeassistant.util import dt as dt_util
|
2023-02-03 09:49:41 +00:00
|
|
|
|
from homeassistant.util.enum import try_parse_enum
|
2021-05-16 17:23:37 +00:00
|
|
|
|
|
2023-02-03 09:49:41 +00:00
|
|
|
|
from .const import (
|
2021-12-13 08:39:13 +00:00
|
|
|
|
ATTR_LAST_RESET,
|
2022-12-02 08:11:15 +00:00
|
|
|
|
ATTR_OPTIONS,
|
2021-12-13 08:39:13 +00:00
|
|
|
|
ATTR_STATE_CLASS,
|
|
|
|
|
DOMAIN,
|
2023-02-03 09:49:41 +00:00
|
|
|
|
SensorStateClass,
|
2021-12-13 08:39:13 +00:00
|
|
|
|
)
|
2021-05-16 17:23:37 +00:00
|
|
|
|
|
2021-06-29 10:20:10 +00:00
|
|
|
|
_LOGGER = logging.getLogger(__name__)
|
|
|
|
|
|
2021-08-25 11:00:35 +00:00
|
|
|
|
DEFAULT_STATISTICS = {
|
2023-02-03 09:49:41 +00:00
|
|
|
|
SensorStateClass.MEASUREMENT: {"mean", "min", "max"},
|
|
|
|
|
SensorStateClass.TOTAL: {"sum"},
|
|
|
|
|
SensorStateClass.TOTAL_INCREASING: {"sum"},
|
2021-05-20 16:23:00 +00:00
|
|
|
|
}
|
2021-05-16 17:23:37 +00:00
|
|
|
|
|
2022-10-11 08:32:01 +00:00
|
|
|
|
EQUIVALENT_UNITS = {
|
2022-12-08 17:41:38 +00:00
|
|
|
|
"BTU/(h×ft²)": UnitOfIrradiance.BTUS_PER_HOUR_SQUARE_FOOT,
|
2022-12-08 19:06:02 +00:00
|
|
|
|
"dBa": UnitOfSoundPressure.WEIGHTED_DECIBEL_A,
|
2022-10-11 08:32:01 +00:00
|
|
|
|
"RPM": REVOLUTIONS_PER_MINUTE,
|
2022-12-08 17:41:38 +00:00
|
|
|
|
"ft3": UnitOfVolume.CUBIC_FEET,
|
|
|
|
|
"m3": UnitOfVolume.CUBIC_METERS,
|
2022-10-11 08:32:01 +00:00
|
|
|
|
}
|
|
|
|
|
|
2021-08-25 11:01:55 +00:00
|
|
|
|
# Keep track of entities for which a warning about decreasing value has been logged
|
2021-08-26 12:27:14 +00:00
|
|
|
|
SEEN_DIP = "sensor_seen_total_increasing_dip"
|
2021-08-25 11:01:55 +00:00
|
|
|
|
WARN_DIP = "sensor_warn_total_increasing_dip"
|
2021-09-30 14:49:16 +00:00
|
|
|
|
# Keep track of entities for which a warning about negative value has been logged
|
|
|
|
|
WARN_NEGATIVE = "sensor_warn_total_increasing_negative"
|
2021-07-02 07:51:47 +00:00
|
|
|
|
# Keep track of entities for which a warning about unsupported unit has been logged
|
2021-08-25 11:00:35 +00:00
|
|
|
|
WARN_UNSUPPORTED_UNIT = "sensor_warn_unsupported_unit"
|
|
|
|
|
WARN_UNSTABLE_UNIT = "sensor_warn_unstable_unit"
|
2022-01-02 21:13:21 +00:00
|
|
|
|
# Link to dev statistics where issues around LTS can be fixed
|
|
|
|
|
LINK_DEV_STATISTICS = "https://my.home-assistant.io/redirect/developer_statistics"
|
2021-05-16 17:23:37 +00:00
|
|
|
|
|
2021-08-13 10:35:23 +00:00
|
|
|
|
|
2021-09-29 21:57:16 +00:00
|
|
|
|
def _get_sensor_states(hass: HomeAssistant) -> list[State]:
|
|
|
|
|
"""Get the current state of all sensors for which to compile statistics."""
|
2021-05-16 17:23:37 +00:00
|
|
|
|
all_sensors = hass.states.all(DOMAIN)
|
2023-02-12 04:21:16 +00:00
|
|
|
|
instance = get_instance(hass)
|
2023-02-12 17:15:27 +00:00
|
|
|
|
return [
|
|
|
|
|
state
|
|
|
|
|
for state in all_sensors
|
|
|
|
|
if instance.entity_filter(state.entity_id)
|
|
|
|
|
and try_parse_enum(SensorStateClass, state.attributes.get(ATTR_STATE_CLASS))
|
|
|
|
|
]
|
2021-05-16 17:23:37 +00:00
|
|
|
|
|
|
|
|
|
|
2021-05-28 11:16:52 +00:00
|
|
|
|
def _time_weighted_average(
|
|
|
|
|
fstates: list[tuple[float, State]], start: datetime.datetime, end: datetime.datetime
|
|
|
|
|
) -> float:
|
|
|
|
|
"""Calculate a time weighted average.
|
|
|
|
|
|
2021-09-09 06:35:53 +00:00
|
|
|
|
The average is calculated by weighting the states by duration in seconds between
|
2021-05-28 11:16:52 +00:00
|
|
|
|
state changes.
|
|
|
|
|
Note: there's no interpolation of values between state changes.
|
|
|
|
|
"""
|
|
|
|
|
old_fstate: float | None = None
|
|
|
|
|
old_start_time: datetime.datetime | None = None
|
|
|
|
|
accumulated = 0.0
|
|
|
|
|
|
|
|
|
|
for fstate, state in fstates:
|
|
|
|
|
# The recorder will give us the last known state, which may be well
|
|
|
|
|
# before the requested start time for the statistics
|
|
|
|
|
start_time = start if state.last_updated < start else state.last_updated
|
|
|
|
|
if old_start_time is None:
|
|
|
|
|
# Adjust start time, if there was no last known state
|
|
|
|
|
start = start_time
|
|
|
|
|
else:
|
|
|
|
|
duration = start_time - old_start_time
|
|
|
|
|
# Accumulate the value, weighted by duration until next state change
|
|
|
|
|
assert old_fstate is not None
|
|
|
|
|
accumulated += old_fstate * duration.total_seconds()
|
|
|
|
|
|
|
|
|
|
old_fstate = fstate
|
|
|
|
|
old_start_time = start_time
|
|
|
|
|
|
|
|
|
|
if old_fstate is not None:
|
|
|
|
|
# Accumulate the value, weighted by duration until end of the period
|
|
|
|
|
assert old_start_time is not None
|
|
|
|
|
duration = end - old_start_time
|
|
|
|
|
accumulated += old_fstate * duration.total_seconds()
|
|
|
|
|
|
2023-03-22 01:12:45 +00:00
|
|
|
|
period_seconds = (end - start).total_seconds()
|
|
|
|
|
if period_seconds == 0:
|
|
|
|
|
# If the only state changed that happened was at the exact moment
|
|
|
|
|
# at the end of the period, we can't calculate a meaningful average
|
|
|
|
|
# so we return 0.0 since it represents a time duration smaller than
|
|
|
|
|
# we can measure. This probably means the precision of statistics
|
|
|
|
|
# column schema in the database is incorrect but it is actually possible
|
|
|
|
|
# to happen if the state change event fired at the exact microsecond
|
|
|
|
|
return 0.0
|
|
|
|
|
return accumulated / period_seconds
|
2021-05-28 11:16:52 +00:00
|
|
|
|
|
|
|
|
|
|
2021-08-25 11:00:35 +00:00
|
|
|
|
def _get_units(fstates: list[tuple[float, State]]) -> set[str | None]:
|
2022-10-11 08:32:01 +00:00
|
|
|
|
"""Return a set of all units."""
|
2021-08-25 11:00:35 +00:00
|
|
|
|
return {item[1].attributes.get(ATTR_UNIT_OF_MEASUREMENT) for item in fstates}
|
|
|
|
|
|
|
|
|
|
|
2022-10-11 08:32:01 +00:00
|
|
|
|
def _equivalent_units(units: set[str | None]) -> bool:
|
|
|
|
|
"""Return True if the units are equivalent."""
|
|
|
|
|
if len(units) == 1:
|
|
|
|
|
return True
|
|
|
|
|
units = {
|
|
|
|
|
EQUIVALENT_UNITS[unit] if unit in EQUIVALENT_UNITS else unit for unit in units
|
|
|
|
|
}
|
|
|
|
|
return len(units) == 1
|
|
|
|
|
|
|
|
|
|
|
2021-09-08 15:05:16 +00:00
|
|
|
|
def _parse_float(state: str) -> float:
|
|
|
|
|
"""Parse a float string, throw on inf or nan."""
|
|
|
|
|
fstate = float(state)
|
|
|
|
|
if math.isnan(fstate) or math.isinf(fstate):
|
|
|
|
|
raise ValueError
|
|
|
|
|
return fstate
|
|
|
|
|
|
|
|
|
|
|
2023-03-17 05:00:02 +00:00
|
|
|
|
def _float_or_none(state: str) -> float | None:
|
|
|
|
|
"""Return a float or None."""
|
|
|
|
|
try:
|
|
|
|
|
return _parse_float(state)
|
|
|
|
|
except (ValueError, TypeError):
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _entity_history_to_float_and_state(
|
|
|
|
|
entity_history: Iterable[State],
|
|
|
|
|
) -> list[tuple[float, State]]:
|
|
|
|
|
"""Return a list of (float, state) tuples for the given entity."""
|
|
|
|
|
return [
|
|
|
|
|
(fstate, state)
|
|
|
|
|
for state in entity_history
|
|
|
|
|
if (fstate := _float_or_none(state.state)) is not None
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
|
2021-06-29 10:20:10 +00:00
|
|
|
|
def _normalize_states(
|
2021-08-25 11:00:35 +00:00
|
|
|
|
hass: HomeAssistant,
|
2021-09-30 15:14:36 +00:00
|
|
|
|
old_metadatas: dict[str, tuple[int, StatisticMetaData]],
|
2023-03-17 05:00:02 +00:00
|
|
|
|
fstates: list[tuple[float, State]],
|
2021-08-25 11:00:35 +00:00
|
|
|
|
entity_id: str,
|
2022-10-11 10:24:52 +00:00
|
|
|
|
) -> tuple[str | None, list[tuple[float, State]]]:
|
2021-06-29 10:20:10 +00:00
|
|
|
|
"""Normalize units."""
|
2022-09-26 01:14:18 +00:00
|
|
|
|
state_unit: str | None = None
|
2022-10-06 18:01:54 +00:00
|
|
|
|
statistics_unit: str | None
|
2023-03-17 05:00:02 +00:00
|
|
|
|
state_unit = fstates[0][1].attributes.get(ATTR_UNIT_OF_MEASUREMENT)
|
|
|
|
|
old_metadata = old_metadatas[entity_id][1] if entity_id in old_metadatas else None
|
2022-10-06 18:01:54 +00:00
|
|
|
|
if not old_metadata:
|
|
|
|
|
# We've not seen this sensor before, the first valid state determines the unit
|
|
|
|
|
# used for statistics
|
|
|
|
|
statistics_unit = state_unit
|
|
|
|
|
else:
|
|
|
|
|
# We have seen this sensor before, use the unit from metadata
|
|
|
|
|
statistics_unit = old_metadata["unit_of_measurement"]
|
|
|
|
|
|
2023-01-12 08:20:00 +00:00
|
|
|
|
if statistics_unit not in statistics.STATISTIC_UNIT_TO_UNIT_CONVERTER:
|
2022-10-06 18:01:54 +00:00
|
|
|
|
# The unit used by this sensor doesn't support unit conversion
|
2022-10-04 01:50:05 +00:00
|
|
|
|
|
|
|
|
|
all_units = _get_units(fstates)
|
2022-10-11 08:32:01 +00:00
|
|
|
|
if not _equivalent_units(all_units):
|
2022-10-04 01:50:05 +00:00
|
|
|
|
if WARN_UNSTABLE_UNIT not in hass.data:
|
|
|
|
|
hass.data[WARN_UNSTABLE_UNIT] = set()
|
|
|
|
|
if entity_id not in hass.data[WARN_UNSTABLE_UNIT]:
|
|
|
|
|
hass.data[WARN_UNSTABLE_UNIT].add(entity_id)
|
|
|
|
|
extra = ""
|
|
|
|
|
if old_metadata:
|
|
|
|
|
extra = (
|
|
|
|
|
" and matches the unit of already compiled statistics "
|
|
|
|
|
f"({old_metadata['unit_of_measurement']})"
|
2021-08-25 11:00:35 +00:00
|
|
|
|
)
|
2022-10-04 01:50:05 +00:00
|
|
|
|
_LOGGER.warning(
|
2022-12-23 15:43:17 +00:00
|
|
|
|
(
|
|
|
|
|
"The unit of %s is changing, got multiple %s, generation of"
|
|
|
|
|
" long term statistics will be suppressed unless the unit is"
|
|
|
|
|
" stable%s. Go to %s to fix this"
|
|
|
|
|
),
|
2022-10-04 01:50:05 +00:00
|
|
|
|
entity_id,
|
|
|
|
|
all_units,
|
|
|
|
|
extra,
|
|
|
|
|
LINK_DEV_STATISTICS,
|
|
|
|
|
)
|
2022-10-11 10:24:52 +00:00
|
|
|
|
return None, []
|
2022-10-04 01:50:05 +00:00
|
|
|
|
state_unit = fstates[0][1].attributes.get(ATTR_UNIT_OF_MEASUREMENT)
|
2022-10-11 10:24:52 +00:00
|
|
|
|
return state_unit, fstates
|
2021-06-29 10:20:10 +00:00
|
|
|
|
|
2022-10-06 18:01:54 +00:00
|
|
|
|
converter = statistics.STATISTIC_UNIT_TO_UNIT_CONVERTER[statistics_unit]
|
2022-10-04 01:50:05 +00:00
|
|
|
|
valid_fstates: list[tuple[float, State]] = []
|
2023-07-03 18:20:23 +00:00
|
|
|
|
convert: Callable[[float], float]
|
|
|
|
|
last_unit: str | None | object = object()
|
2021-06-29 10:20:10 +00:00
|
|
|
|
|
2022-10-04 01:50:05 +00:00
|
|
|
|
for fstate, state in fstates:
|
2022-09-15 16:01:24 +00:00
|
|
|
|
state_unit = state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)
|
2022-10-04 01:50:05 +00:00
|
|
|
|
# Exclude states with unsupported unit from statistics
|
2022-09-26 01:14:18 +00:00
|
|
|
|
if state_unit not in converter.VALID_UNITS:
|
2021-09-08 15:05:16 +00:00
|
|
|
|
if WARN_UNSUPPORTED_UNIT not in hass.data:
|
|
|
|
|
hass.data[WARN_UNSUPPORTED_UNIT] = set()
|
|
|
|
|
if entity_id not in hass.data[WARN_UNSUPPORTED_UNIT]:
|
|
|
|
|
hass.data[WARN_UNSUPPORTED_UNIT].add(entity_id)
|
2021-12-01 17:18:58 +00:00
|
|
|
|
_LOGGER.warning(
|
2022-12-23 15:43:17 +00:00
|
|
|
|
(
|
2023-02-03 10:37:16 +00:00
|
|
|
|
"The unit of %s (%s) cannot be converted to the unit of"
|
2022-12-23 15:43:17 +00:00
|
|
|
|
" previously compiled statistics (%s). Generation of long term"
|
|
|
|
|
" statistics will be suppressed unless the unit changes back to"
|
|
|
|
|
" %s or a compatible unit. Go to %s to fix this"
|
|
|
|
|
),
|
2021-12-01 17:18:58 +00:00
|
|
|
|
entity_id,
|
2022-09-15 16:01:24 +00:00
|
|
|
|
state_unit,
|
2022-10-04 01:50:05 +00:00
|
|
|
|
statistics_unit,
|
2022-10-06 18:01:54 +00:00
|
|
|
|
statistics_unit,
|
|
|
|
|
LINK_DEV_STATISTICS,
|
2021-12-01 17:18:58 +00:00
|
|
|
|
)
|
2021-09-08 15:05:16 +00:00
|
|
|
|
continue
|
2023-07-03 18:20:23 +00:00
|
|
|
|
if state_unit != last_unit:
|
|
|
|
|
# The unit of measurement has changed since the last state change
|
|
|
|
|
# recreate the converter factory
|
|
|
|
|
convert = converter.converter_factory(state_unit, statistics_unit)
|
|
|
|
|
last_unit = state_unit
|
2021-09-08 15:05:16 +00:00
|
|
|
|
|
2023-07-03 18:20:23 +00:00
|
|
|
|
valid_fstates.append((convert(fstate), state))
|
2021-06-29 10:20:10 +00:00
|
|
|
|
|
2022-10-11 10:24:52 +00:00
|
|
|
|
return statistics_unit, valid_fstates
|
2021-06-29 10:20:10 +00:00
|
|
|
|
|
|
|
|
|
|
2021-09-30 14:49:16 +00:00
|
|
|
|
def _suggest_report_issue(hass: HomeAssistant, entity_id: str) -> str:
|
|
|
|
|
"""Suggest to report an issue."""
|
|
|
|
|
domain = entity_sources(hass).get(entity_id, {}).get("domain")
|
|
|
|
|
custom_component = entity_sources(hass).get(entity_id, {}).get("custom_component")
|
|
|
|
|
report_issue = ""
|
|
|
|
|
if custom_component:
|
2022-07-18 20:10:22 +00:00
|
|
|
|
report_issue = "report it to the custom integration author."
|
2021-09-30 14:49:16 +00:00
|
|
|
|
else:
|
|
|
|
|
report_issue = (
|
|
|
|
|
"create a bug report at "
|
|
|
|
|
"https://github.com/home-assistant/core/issues?q=is%3Aopen+is%3Aissue"
|
|
|
|
|
)
|
|
|
|
|
if domain:
|
|
|
|
|
report_issue += f"+label%3A%22integration%3A+{domain}%22"
|
|
|
|
|
|
|
|
|
|
return report_issue
|
|
|
|
|
|
|
|
|
|
|
2021-12-21 16:22:40 +00:00
|
|
|
|
def warn_dip(
|
|
|
|
|
hass: HomeAssistant, entity_id: str, state: State, previous_fstate: float
|
|
|
|
|
) -> None:
|
2021-08-26 12:27:14 +00:00
|
|
|
|
"""Log a warning once if a sensor with state_class_total has a decreasing value.
|
|
|
|
|
|
|
|
|
|
The log will be suppressed until two dips have been seen to prevent warning due to
|
|
|
|
|
rounding issues with databases storing the state as a single precision float, which
|
|
|
|
|
was fixed in recorder DB version 20.
|
|
|
|
|
"""
|
|
|
|
|
if SEEN_DIP not in hass.data:
|
|
|
|
|
hass.data[SEEN_DIP] = set()
|
|
|
|
|
if entity_id not in hass.data[SEEN_DIP]:
|
|
|
|
|
hass.data[SEEN_DIP].add(entity_id)
|
|
|
|
|
return
|
2021-08-25 11:01:55 +00:00
|
|
|
|
if WARN_DIP not in hass.data:
|
|
|
|
|
hass.data[WARN_DIP] = set()
|
|
|
|
|
if entity_id not in hass.data[WARN_DIP]:
|
|
|
|
|
hass.data[WARN_DIP].add(entity_id)
|
|
|
|
|
domain = entity_sources(hass).get(entity_id, {}).get("domain")
|
|
|
|
|
if domain in ["energy", "growatt_server", "solaredge"]:
|
|
|
|
|
return
|
|
|
|
|
_LOGGER.warning(
|
2022-12-23 15:43:17 +00:00
|
|
|
|
(
|
|
|
|
|
"Entity %s %shas state class total_increasing, but its state is not"
|
|
|
|
|
" strictly increasing. Triggered by state %s (%s) with last_updated set"
|
|
|
|
|
" to %s. Please %s"
|
|
|
|
|
),
|
2021-08-25 11:01:55 +00:00
|
|
|
|
entity_id,
|
|
|
|
|
f"from integration {domain} " if domain else "",
|
2021-10-13 15:15:04 +00:00
|
|
|
|
state.state,
|
2021-12-21 16:22:40 +00:00
|
|
|
|
previous_fstate,
|
2021-10-13 15:15:04 +00:00
|
|
|
|
state.last_updated.isoformat(),
|
2021-09-30 14:49:16 +00:00
|
|
|
|
_suggest_report_issue(hass, entity_id),
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
2021-10-13 15:15:04 +00:00
|
|
|
|
def warn_negative(hass: HomeAssistant, entity_id: str, state: State) -> None:
|
2021-09-30 14:49:16 +00:00
|
|
|
|
"""Log a warning once if a sensor with state_class_total has a negative value."""
|
|
|
|
|
if WARN_NEGATIVE not in hass.data:
|
|
|
|
|
hass.data[WARN_NEGATIVE] = set()
|
|
|
|
|
if entity_id not in hass.data[WARN_NEGATIVE]:
|
|
|
|
|
hass.data[WARN_NEGATIVE].add(entity_id)
|
|
|
|
|
domain = entity_sources(hass).get(entity_id, {}).get("domain")
|
|
|
|
|
_LOGGER.warning(
|
2022-12-23 15:43:17 +00:00
|
|
|
|
(
|
|
|
|
|
"Entity %s %shas state class total_increasing, but its state is "
|
|
|
|
|
"negative. Triggered by state %s with last_updated set to %s. Please %s"
|
|
|
|
|
),
|
2021-09-30 14:49:16 +00:00
|
|
|
|
entity_id,
|
|
|
|
|
f"from integration {domain} " if domain else "",
|
2021-10-13 15:15:04 +00:00
|
|
|
|
state.state,
|
|
|
|
|
state.last_updated.isoformat(),
|
2021-09-30 14:49:16 +00:00
|
|
|
|
_suggest_report_issue(hass, entity_id),
|
2021-08-25 11:01:55 +00:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def reset_detected(
|
2021-10-13 15:15:04 +00:00
|
|
|
|
hass: HomeAssistant,
|
|
|
|
|
entity_id: str,
|
|
|
|
|
fstate: float,
|
|
|
|
|
previous_fstate: float | None,
|
|
|
|
|
state: State,
|
2021-08-25 11:01:55 +00:00
|
|
|
|
) -> bool:
|
2021-08-24 15:23:55 +00:00
|
|
|
|
"""Test if a total_increasing sensor has been reset."""
|
2021-10-13 15:15:04 +00:00
|
|
|
|
if previous_fstate is None:
|
2021-08-25 11:01:55 +00:00
|
|
|
|
return False
|
|
|
|
|
|
2021-10-13 15:15:04 +00:00
|
|
|
|
if 0.9 * previous_fstate <= fstate < previous_fstate:
|
2021-12-21 16:22:40 +00:00
|
|
|
|
warn_dip(hass, entity_id, state, previous_fstate)
|
2021-08-25 11:01:55 +00:00
|
|
|
|
|
2021-10-13 15:15:04 +00:00
|
|
|
|
if fstate < 0:
|
|
|
|
|
warn_negative(hass, entity_id, state)
|
2021-09-30 14:49:16 +00:00
|
|
|
|
raise HomeAssistantError
|
|
|
|
|
|
2021-10-13 15:15:04 +00:00
|
|
|
|
return fstate < 0.9 * previous_fstate
|
2021-08-24 15:23:55 +00:00
|
|
|
|
|
|
|
|
|
|
2021-09-29 21:57:16 +00:00
|
|
|
|
def _wanted_statistics(sensor_states: list[State]) -> dict[str, set[str]]:
|
2021-09-01 04:30:52 +00:00
|
|
|
|
"""Prepare a dict with wanted statistics for entities."""
|
2023-02-12 17:15:27 +00:00
|
|
|
|
return {
|
|
|
|
|
state.entity_id: DEFAULT_STATISTICS[state.attributes[ATTR_STATE_CLASS]]
|
|
|
|
|
for state in sensor_states
|
|
|
|
|
}
|
2021-09-01 04:30:52 +00:00
|
|
|
|
|
|
|
|
|
|
2021-10-08 17:48:52 +00:00
|
|
|
|
def _last_reset_as_utc_isoformat(last_reset_s: Any, entity_id: str) -> str | None:
|
2021-09-24 07:16:50 +00:00
|
|
|
|
"""Parse last_reset and convert it to UTC."""
|
|
|
|
|
if last_reset_s is None:
|
|
|
|
|
return None
|
2021-10-08 17:48:52 +00:00
|
|
|
|
if isinstance(last_reset_s, str):
|
|
|
|
|
last_reset = dt_util.parse_datetime(last_reset_s)
|
|
|
|
|
else:
|
|
|
|
|
last_reset = None
|
2021-09-24 07:16:50 +00:00
|
|
|
|
if last_reset is None:
|
|
|
|
|
_LOGGER.warning(
|
|
|
|
|
"Ignoring invalid last reset '%s' for %s", last_reset_s, entity_id
|
|
|
|
|
)
|
|
|
|
|
return None
|
|
|
|
|
return dt_util.as_utc(last_reset).isoformat()
|
|
|
|
|
|
|
|
|
|
|
2023-02-10 16:26:46 +00:00
|
|
|
|
def _timestamp_to_isoformat_or_none(timestamp: float | None) -> str | None:
|
|
|
|
|
"""Convert a timestamp to ISO format or return None."""
|
|
|
|
|
if timestamp is None:
|
|
|
|
|
return None
|
|
|
|
|
return dt_util.utc_from_timestamp(timestamp).isoformat()
|
|
|
|
|
|
|
|
|
|
|
2021-09-30 15:14:36 +00:00
|
|
|
|
def compile_statistics(
|
2021-05-16 17:23:37 +00:00
|
|
|
|
hass: HomeAssistant, start: datetime.datetime, end: datetime.datetime
|
2022-04-22 10:25:42 +00:00
|
|
|
|
) -> statistics.PlatformCompiledStatistics:
|
2021-05-16 17:23:37 +00:00
|
|
|
|
"""Compile statistics for all entities during start-end.
|
|
|
|
|
|
|
|
|
|
Note: This will query the database and must not be run in the event loop
|
|
|
|
|
"""
|
2023-03-17 05:00:02 +00:00
|
|
|
|
# There is already an active session when this code is called since
|
|
|
|
|
# it is called from the recorder statistics. We need to make sure
|
|
|
|
|
# this session never gets committed since it would be out of sync
|
|
|
|
|
# with the recorder statistics session so we mark it as read only.
|
|
|
|
|
#
|
|
|
|
|
# If we ever need to write to the database from this function we
|
|
|
|
|
# will need to refactor the recorder statistics to use a single
|
|
|
|
|
# session.
|
|
|
|
|
with recorder_util.session_scope(hass=hass, read_only=True) as session:
|
2022-04-22 10:25:42 +00:00
|
|
|
|
compiled = _compile_statistics(hass, session, start, end)
|
|
|
|
|
return compiled
|
2021-09-30 15:14:36 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _compile_statistics( # noqa: C901
|
|
|
|
|
hass: HomeAssistant,
|
|
|
|
|
session: Session,
|
|
|
|
|
start: datetime.datetime,
|
|
|
|
|
end: datetime.datetime,
|
2022-04-22 10:25:42 +00:00
|
|
|
|
) -> statistics.PlatformCompiledStatistics:
|
2021-09-30 15:14:36 +00:00
|
|
|
|
"""Compile statistics for all entities during start-end."""
|
2021-09-22 20:31:33 +00:00
|
|
|
|
result: list[StatisticResult] = []
|
2021-05-16 17:23:37 +00:00
|
|
|
|
|
2021-09-29 21:57:16 +00:00
|
|
|
|
sensor_states = _get_sensor_states(hass)
|
|
|
|
|
wanted_statistics = _wanted_statistics(sensor_states)
|
2021-05-16 17:23:37 +00:00
|
|
|
|
# Get history between start and end
|
2021-09-29 21:57:16 +00:00
|
|
|
|
entities_full_history = [
|
|
|
|
|
i.entity_id for i in sensor_states if "sum" in wanted_statistics[i.entity_id]
|
|
|
|
|
]
|
2022-04-07 10:09:05 +00:00
|
|
|
|
history_list: MutableMapping[str, list[State]] = {}
|
2021-09-01 04:30:52 +00:00
|
|
|
|
if entities_full_history:
|
2022-04-07 10:09:05 +00:00
|
|
|
|
history_list = history.get_full_significant_states_with_session(
|
2021-09-01 04:30:52 +00:00
|
|
|
|
hass,
|
2021-09-30 15:14:36 +00:00
|
|
|
|
session,
|
2021-09-01 04:30:52 +00:00
|
|
|
|
start - datetime.timedelta.resolution,
|
|
|
|
|
end,
|
|
|
|
|
entity_ids=entities_full_history,
|
|
|
|
|
significant_changes_only=False,
|
|
|
|
|
)
|
|
|
|
|
entities_significant_history = [
|
2021-09-29 21:57:16 +00:00
|
|
|
|
i.entity_id
|
|
|
|
|
for i in sensor_states
|
|
|
|
|
if "sum" not in wanted_statistics[i.entity_id]
|
2021-09-01 04:30:52 +00:00
|
|
|
|
]
|
|
|
|
|
if entities_significant_history:
|
2022-04-07 10:09:05 +00:00
|
|
|
|
_history_list = history.get_full_significant_states_with_session(
|
2021-09-01 04:30:52 +00:00
|
|
|
|
hass,
|
2021-09-30 15:14:36 +00:00
|
|
|
|
session,
|
2021-09-01 04:30:52 +00:00
|
|
|
|
start - datetime.timedelta.resolution,
|
|
|
|
|
end,
|
|
|
|
|
entity_ids=entities_significant_history,
|
|
|
|
|
)
|
|
|
|
|
history_list = {**history_list, **_history_list}
|
2021-09-29 21:57:16 +00:00
|
|
|
|
|
2023-03-17 05:00:02 +00:00
|
|
|
|
entities_with_float_states: dict[str, list[tuple[float, State]]] = {}
|
2022-04-15 16:13:29 +00:00
|
|
|
|
for _state in sensor_states:
|
2021-09-29 21:57:16 +00:00
|
|
|
|
entity_id = _state.entity_id
|
2023-03-17 05:00:02 +00:00
|
|
|
|
# If there are no recent state changes, the sensor's state may already be pruned
|
|
|
|
|
# from the recorder. Get the state from the state machine instead.
|
|
|
|
|
if not (entity_history := history_list.get(entity_id, [_state])):
|
2021-05-16 17:23:37 +00:00
|
|
|
|
continue
|
2023-03-17 05:00:02 +00:00
|
|
|
|
if not (float_states := _entity_history_to_float_and_state(entity_history)):
|
|
|
|
|
continue
|
|
|
|
|
entities_with_float_states[entity_id] = float_states
|
2021-05-16 17:23:37 +00:00
|
|
|
|
|
2023-03-17 05:00:02 +00:00
|
|
|
|
# Only lookup metadata for entities that have valid float states
|
|
|
|
|
# since it will result in cache misses for statistic_ids
|
|
|
|
|
# that are not in the metadata table and we are not working
|
|
|
|
|
# with them anyway.
|
|
|
|
|
old_metadatas = statistics.get_metadata_with_session(
|
2023-03-20 02:01:16 +00:00
|
|
|
|
get_instance(hass), session, statistic_ids=set(entities_with_float_states)
|
2023-03-17 05:00:02 +00:00
|
|
|
|
)
|
|
|
|
|
to_process: list[tuple[str, str | None, str, list[tuple[float, State]]]] = []
|
2023-03-20 02:01:16 +00:00
|
|
|
|
to_query: set[str] = set()
|
2023-03-17 05:00:02 +00:00
|
|
|
|
for _state in sensor_states:
|
|
|
|
|
entity_id = _state.entity_id
|
|
|
|
|
if not (maybe_float_states := entities_with_float_states.get(entity_id)):
|
|
|
|
|
continue
|
|
|
|
|
statistics_unit, valid_float_states = _normalize_states(
|
2022-03-25 00:58:38 +00:00
|
|
|
|
hass,
|
|
|
|
|
old_metadatas,
|
2023-03-17 05:00:02 +00:00
|
|
|
|
maybe_float_states,
|
2022-03-25 00:58:38 +00:00
|
|
|
|
entity_id,
|
2021-09-30 15:14:36 +00:00
|
|
|
|
)
|
2023-03-17 05:00:02 +00:00
|
|
|
|
if not valid_float_states:
|
2021-05-16 17:23:37 +00:00
|
|
|
|
continue
|
2023-03-17 05:00:02 +00:00
|
|
|
|
state_class: str = _state.attributes[ATTR_STATE_CLASS]
|
|
|
|
|
to_process.append((entity_id, statistics_unit, state_class, valid_float_states))
|
2022-04-15 16:13:29 +00:00
|
|
|
|
if "sum" in wanted_statistics[entity_id]:
|
2023-03-20 02:01:16 +00:00
|
|
|
|
to_query.add(entity_id)
|
2022-04-15 16:13:29 +00:00
|
|
|
|
|
2022-04-22 10:25:42 +00:00
|
|
|
|
last_stats = statistics.get_latest_short_term_statistics(
|
2022-11-16 16:36:30 +00:00
|
|
|
|
hass, to_query, {"last_reset", "state", "sum"}, metadata=old_metadatas
|
2022-04-22 10:25:42 +00:00
|
|
|
|
)
|
2022-04-15 16:13:29 +00:00
|
|
|
|
for ( # pylint: disable=too-many-nested-blocks
|
|
|
|
|
entity_id,
|
2022-10-03 19:42:44 +00:00
|
|
|
|
statistics_unit,
|
2022-04-15 16:13:29 +00:00
|
|
|
|
state_class,
|
2023-03-17 05:00:02 +00:00
|
|
|
|
valid_float_states,
|
2022-04-15 16:13:29 +00:00
|
|
|
|
) in to_process:
|
2021-08-25 11:00:35 +00:00
|
|
|
|
# Check metadata
|
2021-09-30 15:14:36 +00:00
|
|
|
|
if old_metadata := old_metadatas.get(entity_id):
|
2022-10-11 08:32:01 +00:00
|
|
|
|
if not _equivalent_units(
|
|
|
|
|
{old_metadata[1]["unit_of_measurement"], statistics_unit}
|
|
|
|
|
):
|
2021-08-25 11:00:35 +00:00
|
|
|
|
if WARN_UNSTABLE_UNIT not in hass.data:
|
|
|
|
|
hass.data[WARN_UNSTABLE_UNIT] = set()
|
|
|
|
|
if entity_id not in hass.data[WARN_UNSTABLE_UNIT]:
|
|
|
|
|
hass.data[WARN_UNSTABLE_UNIT].add(entity_id)
|
|
|
|
|
_LOGGER.warning(
|
2022-12-23 15:43:17 +00:00
|
|
|
|
(
|
2023-02-03 10:37:16 +00:00
|
|
|
|
"The unit of %s (%s) cannot be converted to the unit of"
|
2022-12-23 15:43:17 +00:00
|
|
|
|
" previously compiled statistics (%s). Generation of long"
|
|
|
|
|
" term statistics will be suppressed unless the unit"
|
|
|
|
|
" changes back to %s or a compatible unit. Go to %s to fix"
|
|
|
|
|
" this"
|
|
|
|
|
),
|
2021-08-25 11:00:35 +00:00
|
|
|
|
entity_id,
|
2022-10-03 19:42:44 +00:00
|
|
|
|
statistics_unit,
|
2021-09-30 15:14:36 +00:00
|
|
|
|
old_metadata[1]["unit_of_measurement"],
|
|
|
|
|
old_metadata[1]["unit_of_measurement"],
|
2022-01-02 21:13:21 +00:00
|
|
|
|
LINK_DEV_STATISTICS,
|
2021-08-25 11:00:35 +00:00
|
|
|
|
)
|
|
|
|
|
continue
|
|
|
|
|
|
2021-06-30 11:32:17 +00:00
|
|
|
|
# Set meta data
|
2021-09-22 20:31:33 +00:00
|
|
|
|
meta: StatisticMetaData = {
|
2021-09-01 04:30:52 +00:00
|
|
|
|
"has_mean": "mean" in wanted_statistics[entity_id],
|
|
|
|
|
"has_sum": "sum" in wanted_statistics[entity_id],
|
2021-10-26 08:26:50 +00:00
|
|
|
|
"name": None,
|
|
|
|
|
"source": RECORDER_DOMAIN,
|
|
|
|
|
"statistic_id": entity_id,
|
2022-10-03 19:42:44 +00:00
|
|
|
|
"unit_of_measurement": statistics_unit,
|
2021-07-02 11:17:00 +00:00
|
|
|
|
}
|
2021-06-30 11:32:17 +00:00
|
|
|
|
|
2021-05-16 17:23:37 +00:00
|
|
|
|
# Make calculations
|
2021-09-22 20:31:33 +00:00
|
|
|
|
stat: StatisticData = {"start": start}
|
2021-09-01 04:30:52 +00:00
|
|
|
|
if "max" in wanted_statistics[entity_id]:
|
2023-01-08 23:40:08 +00:00
|
|
|
|
stat["max"] = max(
|
|
|
|
|
*itertools.islice(
|
2023-03-17 05:00:02 +00:00
|
|
|
|
zip(*valid_float_states), # type: ignore[typeddict-item]
|
2023-01-08 23:40:08 +00:00
|
|
|
|
1,
|
|
|
|
|
)
|
|
|
|
|
)
|
2021-09-01 04:30:52 +00:00
|
|
|
|
if "min" in wanted_statistics[entity_id]:
|
2023-01-08 23:40:08 +00:00
|
|
|
|
stat["min"] = min(
|
|
|
|
|
*itertools.islice(
|
2023-03-17 05:00:02 +00:00
|
|
|
|
zip(*valid_float_states), # type: ignore[typeddict-item]
|
2023-01-08 23:40:08 +00:00
|
|
|
|
1,
|
|
|
|
|
)
|
|
|
|
|
)
|
2021-05-16 17:23:37 +00:00
|
|
|
|
|
2021-09-01 04:30:52 +00:00
|
|
|
|
if "mean" in wanted_statistics[entity_id]:
|
2023-03-17 05:00:02 +00:00
|
|
|
|
stat["mean"] = _time_weighted_average(valid_float_states, start, end)
|
2021-05-20 11:05:15 +00:00
|
|
|
|
|
2021-09-01 04:30:52 +00:00
|
|
|
|
if "sum" in wanted_statistics[entity_id]:
|
2021-08-24 15:02:34 +00:00
|
|
|
|
last_reset = old_last_reset = None
|
2021-05-20 11:05:15 +00:00
|
|
|
|
new_state = old_state = None
|
2021-09-09 06:35:53 +00:00
|
|
|
|
_sum = 0.0
|
2021-05-20 11:05:15 +00:00
|
|
|
|
if entity_id in last_stats:
|
2023-01-08 23:40:08 +00:00
|
|
|
|
# We have compiled history for this sensor before,
|
|
|
|
|
# use that as a starting point.
|
2023-03-14 19:06:56 +00:00
|
|
|
|
last_stat = last_stats[entity_id][0]
|
|
|
|
|
last_reset = _timestamp_to_isoformat_or_none(last_stat["last_reset"])
|
|
|
|
|
old_last_reset = last_reset
|
2023-04-30 18:46:26 +00:00
|
|
|
|
# If there are no previous values and has_sum
|
|
|
|
|
# was previously false there will be no last_stat
|
|
|
|
|
# for state or sum
|
|
|
|
|
new_state = old_state = last_stat.get("state")
|
|
|
|
|
_sum = last_stat.get("sum") or 0.0
|
2021-05-20 11:05:15 +00:00
|
|
|
|
|
2023-03-17 05:00:02 +00:00
|
|
|
|
for fstate, state in valid_float_states:
|
2021-08-13 10:35:23 +00:00
|
|
|
|
reset = False
|
2021-08-24 15:02:34 +00:00
|
|
|
|
if (
|
2023-02-03 09:49:41 +00:00
|
|
|
|
state_class != SensorStateClass.TOTAL_INCREASING
|
2021-09-24 07:16:50 +00:00
|
|
|
|
and (
|
|
|
|
|
last_reset := _last_reset_as_utc_isoformat(
|
|
|
|
|
state.attributes.get("last_reset"), entity_id
|
|
|
|
|
)
|
|
|
|
|
)
|
2021-08-24 15:02:34 +00:00
|
|
|
|
!= old_last_reset
|
2021-09-27 10:17:09 +00:00
|
|
|
|
and last_reset is not None
|
2021-08-24 15:02:34 +00:00
|
|
|
|
):
|
2021-08-31 17:15:22 +00:00
|
|
|
|
if old_state is None:
|
|
|
|
|
_LOGGER.info(
|
2022-12-23 15:43:17 +00:00
|
|
|
|
(
|
|
|
|
|
"Compiling initial sum statistics for %s, zero point"
|
|
|
|
|
" set to %s"
|
|
|
|
|
),
|
2021-08-31 17:15:22 +00:00
|
|
|
|
entity_id,
|
|
|
|
|
fstate,
|
|
|
|
|
)
|
|
|
|
|
else:
|
|
|
|
|
_LOGGER.info(
|
2022-12-23 15:43:17 +00:00
|
|
|
|
(
|
|
|
|
|
"Detected new cycle for %s, last_reset set to %s (old"
|
|
|
|
|
" last_reset %s)"
|
|
|
|
|
),
|
2021-08-31 17:15:22 +00:00
|
|
|
|
entity_id,
|
|
|
|
|
last_reset,
|
|
|
|
|
old_last_reset,
|
|
|
|
|
)
|
2021-08-24 15:02:34 +00:00
|
|
|
|
reset = True
|
|
|
|
|
elif old_state is None and last_reset is None:
|
2021-08-13 10:35:23 +00:00
|
|
|
|
reset = True
|
2021-08-24 09:18:59 +00:00
|
|
|
|
_LOGGER.info(
|
|
|
|
|
"Compiling initial sum statistics for %s, zero point set to %s",
|
|
|
|
|
entity_id,
|
|
|
|
|
fstate,
|
|
|
|
|
)
|
2023-02-03 09:49:41 +00:00
|
|
|
|
elif state_class == SensorStateClass.TOTAL_INCREASING:
|
2021-09-30 14:49:16 +00:00
|
|
|
|
try:
|
|
|
|
|
if old_state is None or reset_detected(
|
2021-10-13 15:15:04 +00:00
|
|
|
|
hass, entity_id, fstate, new_state, state
|
2021-09-30 14:49:16 +00:00
|
|
|
|
):
|
|
|
|
|
reset = True
|
|
|
|
|
_LOGGER.info(
|
2022-12-23 15:43:17 +00:00
|
|
|
|
(
|
|
|
|
|
"Detected new cycle for %s, value dropped from %s"
|
|
|
|
|
" to %s, triggered by state with last_updated set"
|
|
|
|
|
" to %s"
|
|
|
|
|
),
|
2021-09-30 14:49:16 +00:00
|
|
|
|
entity_id,
|
|
|
|
|
new_state,
|
|
|
|
|
fstate,
|
2023-02-25 11:05:24 +00:00
|
|
|
|
state.last_updated.isoformat(),
|
2021-09-30 14:49:16 +00:00
|
|
|
|
)
|
|
|
|
|
except HomeAssistantError:
|
|
|
|
|
continue
|
2021-08-13 10:35:23 +00:00
|
|
|
|
|
|
|
|
|
if reset:
|
2021-05-20 11:05:15 +00:00
|
|
|
|
# The sensor has been reset, update the sum
|
2023-03-14 19:06:56 +00:00
|
|
|
|
if old_state is not None and new_state is not None:
|
2021-05-20 11:05:15 +00:00
|
|
|
|
_sum += new_state - old_state
|
|
|
|
|
# ..and update the starting point
|
|
|
|
|
new_state = fstate
|
2021-08-24 15:02:34 +00:00
|
|
|
|
old_last_reset = last_reset
|
2021-08-31 08:45:17 +00:00
|
|
|
|
# Force a new cycle for an existing sensor to start at 0
|
|
|
|
|
if old_state is not None:
|
2021-08-18 08:03:27 +00:00
|
|
|
|
old_state = 0.0
|
2021-08-17 21:05:31 +00:00
|
|
|
|
else:
|
|
|
|
|
old_state = new_state
|
2021-05-20 11:05:15 +00:00
|
|
|
|
else:
|
|
|
|
|
new_state = fstate
|
|
|
|
|
|
2021-08-13 10:35:23 +00:00
|
|
|
|
if new_state is None or old_state is None:
|
2021-05-20 11:05:15 +00:00
|
|
|
|
# No valid updates
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
# Update the sum with the last state
|
|
|
|
|
_sum += new_state - old_state
|
2021-08-24 15:02:34 +00:00
|
|
|
|
if last_reset is not None:
|
|
|
|
|
stat["last_reset"] = dt_util.parse_datetime(last_reset)
|
2021-06-30 11:32:17 +00:00
|
|
|
|
stat["sum"] = _sum
|
|
|
|
|
stat["state"] = new_state
|
|
|
|
|
|
2021-10-26 08:26:50 +00:00
|
|
|
|
result.append({"meta": meta, "stat": stat})
|
2021-05-16 17:23:37 +00:00
|
|
|
|
|
2022-04-22 10:25:42 +00:00
|
|
|
|
return statistics.PlatformCompiledStatistics(result, old_metadatas)
|
2021-07-14 09:54:55 +00:00
|
|
|
|
|
|
|
|
|
|
2022-03-22 04:14:47 +00:00
|
|
|
|
def list_statistic_ids(
|
|
|
|
|
hass: HomeAssistant,
|
|
|
|
|
statistic_ids: list[str] | tuple[str] | None = None,
|
|
|
|
|
statistic_type: str | None = None,
|
|
|
|
|
) -> dict:
|
|
|
|
|
"""Return all or filtered statistic_ids and meta data."""
|
2021-09-29 21:57:16 +00:00
|
|
|
|
entities = _get_sensor_states(hass)
|
2021-07-14 09:54:55 +00:00
|
|
|
|
|
2022-08-31 09:30:45 +00:00
|
|
|
|
result: dict[str, StatisticMetaData] = {}
|
2021-07-14 09:54:55 +00:00
|
|
|
|
|
2021-09-29 21:57:16 +00:00
|
|
|
|
for state in entities:
|
|
|
|
|
state_class = state.attributes[ATTR_STATE_CLASS]
|
2022-09-15 16:01:24 +00:00
|
|
|
|
state_unit = state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)
|
2021-09-29 21:57:16 +00:00
|
|
|
|
|
2022-01-11 12:59:08 +00:00
|
|
|
|
provided_statistics = DEFAULT_STATISTICS[state_class]
|
2021-07-14 09:54:55 +00:00
|
|
|
|
if statistic_type is not None and statistic_type not in provided_statistics:
|
|
|
|
|
continue
|
|
|
|
|
|
2022-03-22 04:14:47 +00:00
|
|
|
|
if statistic_ids is not None and state.entity_id not in statistic_ids:
|
|
|
|
|
continue
|
|
|
|
|
|
2021-08-18 08:03:27 +00:00
|
|
|
|
if (
|
|
|
|
|
"sum" in provided_statistics
|
|
|
|
|
and ATTR_LAST_RESET not in state.attributes
|
2023-02-03 09:49:41 +00:00
|
|
|
|
and state.attributes.get(ATTR_STATE_CLASS) == SensorStateClass.MEASUREMENT
|
2021-08-18 08:03:27 +00:00
|
|
|
|
):
|
2021-07-14 09:54:55 +00:00
|
|
|
|
continue
|
|
|
|
|
|
2022-03-22 04:14:47 +00:00
|
|
|
|
result[state.entity_id] = {
|
2022-03-24 09:12:01 +00:00
|
|
|
|
"has_mean": "mean" in provided_statistics,
|
|
|
|
|
"has_sum": "sum" in provided_statistics,
|
2022-08-31 09:30:45 +00:00
|
|
|
|
"name": None,
|
2021-10-26 08:26:50 +00:00
|
|
|
|
"source": RECORDER_DOMAIN,
|
2022-08-31 09:30:45 +00:00
|
|
|
|
"statistic_id": state.entity_id,
|
2022-10-03 19:42:44 +00:00
|
|
|
|
"unit_of_measurement": state_unit,
|
2021-10-26 08:26:50 +00:00
|
|
|
|
}
|
2022-10-04 01:50:05 +00:00
|
|
|
|
continue
|
2021-07-14 09:54:55 +00:00
|
|
|
|
|
2022-03-22 04:14:47 +00:00
|
|
|
|
return result
|
2021-09-13 11:44:22 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def validate_statistics(
|
|
|
|
|
hass: HomeAssistant,
|
|
|
|
|
) -> dict[str, list[statistics.ValidationIssue]]:
|
|
|
|
|
"""Validate statistics."""
|
|
|
|
|
validation_result = defaultdict(list)
|
|
|
|
|
|
2021-10-04 16:47:44 +00:00
|
|
|
|
sensor_states = hass.states.all(DOMAIN)
|
2021-10-20 13:57:22 +00:00
|
|
|
|
metadatas = statistics.get_metadata(hass, statistic_source=RECORDER_DOMAIN)
|
|
|
|
|
sensor_entity_ids = {i.entity_id for i in sensor_states}
|
|
|
|
|
sensor_statistic_ids = set(metadatas)
|
2023-02-12 04:21:16 +00:00
|
|
|
|
instance = get_instance(hass)
|
2021-09-13 11:44:22 +00:00
|
|
|
|
|
2021-09-29 21:57:16 +00:00
|
|
|
|
for state in sensor_states:
|
|
|
|
|
entity_id = state.entity_id
|
2023-02-03 09:49:41 +00:00
|
|
|
|
state_class = try_parse_enum(
|
|
|
|
|
SensorStateClass, state.attributes.get(ATTR_STATE_CLASS)
|
|
|
|
|
)
|
2021-09-13 11:44:22 +00:00
|
|
|
|
state_unit = state.attributes.get(ATTR_UNIT_OF_MEASUREMENT)
|
|
|
|
|
|
2021-10-04 16:47:44 +00:00
|
|
|
|
if metadata := metadatas.get(entity_id):
|
2023-02-12 04:21:16 +00:00
|
|
|
|
if not instance.entity_filter(state.entity_id):
|
2021-10-04 16:47:44 +00:00
|
|
|
|
# Sensor was previously recorded, but no longer is
|
|
|
|
|
validation_result[entity_id].append(
|
|
|
|
|
statistics.ValidationIssue(
|
2021-10-20 13:58:28 +00:00
|
|
|
|
"entity_no_longer_recorded",
|
2021-10-04 16:47:44 +00:00
|
|
|
|
{"statistic_id": entity_id},
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
|
2023-02-03 09:49:41 +00:00
|
|
|
|
if state_class is None:
|
2021-10-04 16:47:44 +00:00
|
|
|
|
# Sensor no longer has a valid state class
|
|
|
|
|
validation_result[entity_id].append(
|
|
|
|
|
statistics.ValidationIssue(
|
|
|
|
|
"unsupported_state_class",
|
|
|
|
|
{"statistic_id": entity_id, "state_class": state_class},
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
metadata_unit = metadata[1]["unit_of_measurement"]
|
2022-10-04 01:50:05 +00:00
|
|
|
|
converter = statistics.STATISTIC_UNIT_TO_UNIT_CONVERTER.get(metadata_unit)
|
|
|
|
|
if not converter:
|
2022-10-25 07:50:01 +00:00
|
|
|
|
if not _equivalent_units({state_unit, metadata_unit}):
|
2022-10-04 01:50:05 +00:00
|
|
|
|
# The unit has changed, and it's not possible to convert
|
2021-10-04 16:47:44 +00:00
|
|
|
|
validation_result[entity_id].append(
|
|
|
|
|
statistics.ValidationIssue(
|
2022-10-04 01:50:05 +00:00
|
|
|
|
"units_changed",
|
2021-10-04 16:47:44 +00:00
|
|
|
|
{
|
|
|
|
|
"statistic_id": entity_id,
|
|
|
|
|
"state_unit": state_unit,
|
|
|
|
|
"metadata_unit": metadata_unit,
|
2022-10-04 01:50:05 +00:00
|
|
|
|
"supported_unit": metadata_unit,
|
2021-10-04 16:47:44 +00:00
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
)
|
2022-10-04 01:50:05 +00:00
|
|
|
|
elif state_unit not in converter.VALID_UNITS:
|
|
|
|
|
# The state unit can't be converted to the unit in metadata
|
2023-01-12 08:20:00 +00:00
|
|
|
|
valid_units = (unit or "<None>" for unit in converter.VALID_UNITS)
|
|
|
|
|
valid_units_str = ", ".join(sorted(valid_units))
|
2021-09-13 11:44:22 +00:00
|
|
|
|
validation_result[entity_id].append(
|
|
|
|
|
statistics.ValidationIssue(
|
2022-10-04 01:50:05 +00:00
|
|
|
|
"units_changed",
|
2021-09-13 11:44:22 +00:00
|
|
|
|
{
|
|
|
|
|
"statistic_id": entity_id,
|
2022-10-04 01:50:05 +00:00
|
|
|
|
"state_unit": state_unit,
|
2021-09-13 11:44:22 +00:00
|
|
|
|
"metadata_unit": metadata_unit,
|
2023-01-12 08:20:00 +00:00
|
|
|
|
"supported_unit": valid_units_str,
|
2021-09-13 11:44:22 +00:00
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
)
|
2023-02-03 09:49:41 +00:00
|
|
|
|
elif state_class is not None:
|
2023-02-12 04:21:16 +00:00
|
|
|
|
if not instance.entity_filter(state.entity_id):
|
2021-10-20 13:58:28 +00:00
|
|
|
|
# Sensor is not recorded
|
|
|
|
|
validation_result[entity_id].append(
|
|
|
|
|
statistics.ValidationIssue(
|
|
|
|
|
"entity_not_recorded",
|
|
|
|
|
{"statistic_id": entity_id},
|
|
|
|
|
)
|
|
|
|
|
)
|
2021-09-13 11:44:22 +00:00
|
|
|
|
|
2021-10-20 13:57:22 +00:00
|
|
|
|
for statistic_id in sensor_statistic_ids - sensor_entity_ids:
|
2022-10-06 19:17:46 +00:00
|
|
|
|
if split_entity_id(statistic_id)[0] != DOMAIN:
|
|
|
|
|
continue
|
2021-10-20 13:57:22 +00:00
|
|
|
|
# There is no sensor matching the statistics_id
|
|
|
|
|
validation_result[statistic_id].append(
|
|
|
|
|
statistics.ValidationIssue(
|
|
|
|
|
"no_state",
|
|
|
|
|
{
|
|
|
|
|
"statistic_id": statistic_id,
|
|
|
|
|
},
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
|
2021-09-13 11:44:22 +00:00
|
|
|
|
return validation_result
|
2022-12-02 08:11:15 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@callback
|
|
|
|
|
def exclude_attributes(hass: HomeAssistant) -> set[str]:
|
|
|
|
|
"""Exclude attributes from being recorded in the database."""
|
|
|
|
|
return {ATTR_OPTIONS}
|