From 2d197fd59efafd7f9edb4ee4d192e395af9932fe Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 19 Aug 2022 15:24:53 +0200 Subject: [PATCH] Add state selector (#77024) Co-authored-by: Paulus Schoutsen --- homeassistant/helpers/selector.py | 24 ++++++++++++++++++++++++ tests/helpers/test_selector.py | 15 +++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/homeassistant/helpers/selector.py b/homeassistant/helpers/selector.py index deacc821672..deb5cc7401c 100644 --- a/homeassistant/helpers/selector.py +++ b/homeassistant/helpers/selector.py @@ -741,6 +741,30 @@ class TargetSelectorConfig(TypedDict, total=False): device: SingleDeviceSelectorConfig +class StateSelectorConfig(TypedDict): + """Class to represent an state selector config.""" + + entity_id: str + + +@SELECTORS.register("state") +class StateSelector(Selector): + """Selector for an entity state.""" + + selector_type = "state" + + CONFIG_SCHEMA = vol.Schema({vol.Required("entity_id"): cv.entity_id}) + + def __init__(self, config: StateSelectorConfig) -> None: + """Instantiate a selector.""" + super().__init__(config) + + def __call__(self, data: Any) -> str: + """Validate the passed selection.""" + state: str = vol.Schema(str)(data) + return state + + @SELECTORS.register("target") class TargetSelector(Selector): """Selector of a target value (area ID, device ID, entity ID etc). diff --git a/tests/helpers/test_selector.py b/tests/helpers/test_selector.py index d1018299d96..70e17058923 100644 --- a/tests/helpers/test_selector.py +++ b/tests/helpers/test_selector.py @@ -294,6 +294,21 @@ def test_time_selector_schema(schema, valid_selections, invalid_selections): _test_selector("time", schema, valid_selections, invalid_selections) +@pytest.mark.parametrize( + "schema,valid_selections,invalid_selections", + ( + ( + {"entity_id": "sensor.abc"}, + ("on", "armed"), + (None, True, 1), + ), + ), +) +def test_state_selector_schema(schema, valid_selections, invalid_selections): + """Test state selector.""" + _test_selector("state", schema, valid_selections, invalid_selections) + + @pytest.mark.parametrize( "schema,valid_selections,invalid_selections", (