Expose statistics selector, use for recorder.get_statistics (#147056)

* Expose statistics selector, use for `recorder.get_statistics`

* code review

* syntax formatting

* rerun ci
This commit is contained in:
karwosts 2025-06-19 11:04:28 -07:00 committed by GitHub
parent 4aff032442
commit b003429912
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 61 additions and 1 deletions

View File

@ -69,7 +69,7 @@ get_statistics:
- sensor.energy_consumption
- sensor.temperature
selector:
entity:
statistic:
multiple: true
period:

View File

@ -1216,6 +1216,39 @@ class SelectSelector(Selector[SelectSelectorConfig]):
return [parent_schema(vol.Schema(str)(val)) for val in data]
class StatisticSelectorConfig(BaseSelectorConfig, total=False):
"""Class to represent a statistic selector config."""
multiple: bool
@SELECTORS.register("statistic")
class StatisticSelector(Selector[StatisticSelectorConfig]):
"""Selector of a single or list of statistics."""
selector_type = "statistic"
CONFIG_SCHEMA = BASE_SELECTOR_CONFIG_SCHEMA.extend(
{
vol.Optional("multiple", default=False): cv.boolean,
}
)
def __init__(self, config: StatisticSelectorConfig | None = None) -> None:
"""Instantiate a selector."""
super().__init__(config)
def __call__(self, data: Any) -> str | list[str]:
"""Validate the passed selection."""
if not self.config["multiple"]:
stat: str = vol.Schema(str)(data)
return stat
if not isinstance(data, list):
raise vol.Invalid("Value should be a list")
return [vol.Schema(str)(val) for val in data]
class TargetSelectorConfig(BaseSelectorConfig, total=False):
"""Class to represent a target selector config."""

View File

@ -1262,3 +1262,30 @@ def test_label_selector_schema(schema, valid_selections, invalid_selections) ->
def test_floor_selector_schema(schema, valid_selections, invalid_selections) -> None:
"""Test floor selector."""
_test_selector("floor", schema, valid_selections, invalid_selections)
@pytest.mark.parametrize(
("schema", "valid_selections", "invalid_selections"),
[
(
{},
("sensor.temperature",),
(None, ["sensor.temperature"]),
),
(
{"multiple": True},
(["sensor.temperature", "sensor:external_temperature"], []),
("sensor.temperature",),
),
(
{"multiple": False},
("sensor.temperature",),
(None, ["sensor.temperature"]),
),
],
)
def test_statistic_selector_schema(
schema, valid_selections, invalid_selections
) -> None:
"""Test statistic selector."""
_test_selector("statistic", schema, valid_selections, invalid_selections)