Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Switch statistics config to require either/both 'max_age' and 'sampling_size' #80999

Merged
merged 5 commits into from
Nov 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
97 changes: 35 additions & 62 deletions homeassistant/components/statistics/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,10 @@
Event,
HomeAssistant,
State,
async_get_hass,
callback,
split_entity_id,
)
from homeassistant.helpers import config_validation as cv, issue_registry
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.event import (
async_track_point_in_utc_time,
Expand Down Expand Up @@ -180,7 +179,7 @@
CONF_QUANTILE_INTERVALS = "quantile_intervals"
CONF_QUANTILE_METHOD = "quantile_method"

DEFAULT_NAME = "Stats"
DEFAULT_NAME = "Statistical characteristic"
DEFAULT_PRECISION = 2
DEFAULT_QUANTILE_INTERVALS = 4
DEFAULT_QUANTILE_METHOD = "exclusive"
Expand All @@ -190,24 +189,6 @@
def valid_state_characteristic_configuration(config: dict[str, Any]) -> dict[str, Any]:
"""Validate that the characteristic selected is valid for the source sensor type, throw if it isn't."""
is_binary = split_entity_id(config[CONF_ENTITY_ID])[0] == BINARY_SENSOR_DOMAIN

if config.get(CONF_STATE_CHARACTERISTIC) is None:
config[CONF_STATE_CHARACTERISTIC] = STAT_COUNT if is_binary else STAT_MEAN
issue_registry.async_create_issue(
hass=async_get_hass(),
domain=DOMAIN,
issue_id=f"{config[CONF_ENTITY_ID]}_default_characteristic",
breaks_in_ha_version="2022.12.0",
is_fixable=False,
severity=issue_registry.IssueSeverity.WARNING,
translation_key="deprecation_warning_characteristic",
translation_placeholders={
"entity": config[CONF_NAME],
"characteristic": config[CONF_STATE_CHARACTERISTIC],
},
learn_more_url="https://github.com/home-assistant/core/pull/60402",
)

characteristic = cast(str, config[CONF_STATE_CHARACTERISTIC])
if (is_binary and characteristic not in STATS_BINARY_SUPPORT) or (
not is_binary and characteristic not in STATS_NUMERIC_SUPPORT
Expand All @@ -221,20 +202,14 @@ def valid_state_characteristic_configuration(config: dict[str, Any]) -> dict[str


def valid_boundary_configuration(config: dict[str, Any]) -> dict[str, Any]:
"""Validate that sampling_size, max_age, or both are provided."""

if config.get(CONF_SAMPLES_MAX_BUFFER_SIZE) is None:
config[CONF_SAMPLES_MAX_BUFFER_SIZE] = 20
issue_registry.async_create_issue(
hass=async_get_hass(),
domain=DOMAIN,
issue_id=f"{config[CONF_ENTITY_ID]}_invalid_boundary_config",
breaks_in_ha_version="2022.12.0",
is_fixable=False,
severity=issue_registry.IssueSeverity.WARNING,
translation_key="deprecation_warning_size",
translation_placeholders={"entity": config[CONF_NAME]},
learn_more_url="https://github.com/home-assistant/core/pull/69700",
"""Validate that max_age, sampling_size, or both are provided."""

if (
config.get(CONF_SAMPLES_MAX_BUFFER_SIZE) is None
and config.get(CONF_MAX_AGE) is None
):
raise vol.RequiredFieldInvalid(
"The sensor configuration must provide 'max_age' and/or 'sampling_size'"
)
return config

Expand All @@ -244,8 +219,10 @@ def valid_boundary_configuration(config: dict[str, Any]) -> dict[str, Any]:
vol.Required(CONF_ENTITY_ID): cv.entity_id,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_UNIQUE_ID): cv.string,
vol.Optional(CONF_STATE_CHARACTERISTIC): cv.string,
vol.Optional(CONF_SAMPLES_MAX_BUFFER_SIZE): vol.Coerce(int),
vol.Required(CONF_STATE_CHARACTERISTIC): cv.string,
vol.Optional(CONF_SAMPLES_MAX_BUFFER_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),
vol.Optional(
Expand Down Expand Up @@ -280,7 +257,7 @@ async def async_setup_platform(
name=config[CONF_NAME],
unique_id=config.get(CONF_UNIQUE_ID),
state_characteristic=config[CONF_STATE_CHARACTERISTIC],
samples_max_buffer_size=config[CONF_SAMPLES_MAX_BUFFER_SIZE],
samples_max_buffer_size=config.get(CONF_SAMPLES_MAX_BUFFER_SIZE),
samples_max_age=config.get(CONF_MAX_AGE),
precision=config[CONF_PRECISION],
quantile_intervals=config[CONF_QUANTILE_INTERVALS],
Expand All @@ -300,7 +277,7 @@ def __init__(
name: str,
unique_id: str | None,
state_characteristic: str,
samples_max_buffer_size: int,
samples_max_buffer_size: int | None,
samples_max_age: timedelta | None,
precision: int,
quantile_intervals: int,
Expand All @@ -316,21 +293,18 @@ def __init__(
split_entity_id(self._source_entity_id)[0] == BINARY_SENSOR_DOMAIN
)
self._state_characteristic: str = state_characteristic
self._samples_max_buffer_size: int = samples_max_buffer_size
self._samples_max_buffer_size: int | None = samples_max_buffer_size
self._samples_max_age: timedelta | None = samples_max_age
self._precision: int = precision
self._quantile_intervals: int = quantile_intervals
self._quantile_method: Literal["exclusive", "inclusive"] = quantile_method
self._value: StateType | datetime = None
self._unit_of_measurement: str | None = None
self._available: bool = False

self.states: deque[float | bool] = deque(maxlen=self._samples_max_buffer_size)
self.ages: deque[datetime] = deque(maxlen=self._samples_max_buffer_size)
self.attributes: dict[str, StateType] = {
STAT_AGE_COVERAGE_RATIO: None,
STAT_BUFFER_USAGE_RATIO: None,
STAT_SOURCE_VALUE_VALID: None,
}
self.attributes: dict[str, StateType] = {}

self._state_characteristic_fn: Callable[[], StateType | datetime]
if self.is_binary:
Expand Down Expand Up @@ -505,11 +479,8 @@ async def async_update(self) -> None:
self._update_value()

# If max_age is set, ensure to update again after the defined interval.
next_to_purge_timestamp = self._next_to_purge_timestamp()
if next_to_purge_timestamp:
_LOGGER.debug(
"%s: scheduling update at %s", self.entity_id, next_to_purge_timestamp
)
if timestamp := self._next_to_purge_timestamp():
_LOGGER.debug("%s: scheduling update at %s", self.entity_id, timestamp)
if self._update_listener:
self._update_listener()
self._update_listener = None
Expand All @@ -522,7 +493,7 @@ def _scheduled_update(now: datetime) -> None:
self._update_listener = None

self._update_listener = async_track_point_in_utc_time(
self.hass, _scheduled_update, next_to_purge_timestamp
self.hass, _scheduled_update, timestamp
)

def _fetch_states_from_database(self) -> list[State]:
Expand Down Expand Up @@ -572,18 +543,20 @@ async def _initialize_from_database(self) -> None:

def _update_attributes(self) -> None:
"""Calculate and update the various attributes."""
self.attributes[STAT_BUFFER_USAGE_RATIO] = round(
len(self.states) / self._samples_max_buffer_size, 2
)

if len(self.states) >= 1 and self._samples_max_age is not None:
self.attributes[STAT_AGE_COVERAGE_RATIO] = round(
(self.ages[-1] - self.ages[0]).total_seconds()
/ self._samples_max_age.total_seconds(),
2,
if self._samples_max_buffer_size is not None:
self.attributes[STAT_BUFFER_USAGE_RATIO] = round(
len(self.states) / self._samples_max_buffer_size, 2
)
else:
self.attributes[STAT_AGE_COVERAGE_RATIO] = None

if self._samples_max_age is not None:
if len(self.states) >= 1:
self.attributes[STAT_AGE_COVERAGE_RATIO] = round(
(self.ages[-1] - self.ages[0]).total_seconds()
/ self._samples_max_age.total_seconds(),
2,
)
else:
self.attributes[STAT_AGE_COVERAGE_RATIO] = None

def _update_value(self) -> None:
"""Front to call the right statistical characteristics functions.
Expand Down
12 changes: 0 additions & 12 deletions homeassistant/components/statistics/strings.json

This file was deleted.

1 change: 1 addition & 0 deletions tests/components/statistics/fixtures/configuration.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ sensor:
entity_id: sensor.cpu
name: cputest
state_characteristic: mean
sampling_size: 20