Compare commits

...

3 Commits

Author SHA1 Message Date
Michael
269e9e04c4 Merge branch 'dev' into number/add-crossed_threshold-trigger 2026-03-08 23:07:25 +01:00
Michael
7820c4327f Apply suggestions from code review
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-03-08 22:37:23 +01:00
mib1185
b08717b9bd add number.crossed_threshold trigger 2026-03-08 20:46:37 +00:00
7 changed files with 550 additions and 2 deletions

View File

@@ -177,6 +177,9 @@
"triggers": {
"changed": {
"trigger": "mdi:counter"
},
"crossed_threshold": {
"trigger": "mdi:counter"
}
}
}

View File

@@ -1,4 +1,8 @@
{
"common": {
"trigger_behavior_description": "The behavior of the targeted numbers to trigger on.",
"trigger_behavior_name": "Behavior"
},
"device_automation": {
"action_type": {
"set_value": "Set value for {entity_name}"
@@ -192,6 +196,29 @@
"message": "Value {value} for {entity_id} is outside valid range {min_value} - {max_value}."
}
},
"selector": {
"number_or_entity": {
"choices": {
"entity": "Entity",
"number": "Number"
}
},
"trigger_behavior": {
"options": {
"any": "Any",
"first": "First",
"last": "Last"
}
},
"trigger_threshold_type": {
"options": {
"above": "Above a value",
"below": "Below a value",
"between": "In a range",
"outside": "Outside a range"
}
}
},
"services": {
"set_value": {
"description": "Sets the value of a number.",
@@ -209,6 +236,28 @@
"changed": {
"description": "Triggers when a number value changes.",
"name": "Number changed"
},
"crossed_threshold": {
"description": "Triggers after the value of one or more numbers crosses a threshold.",
"fields": {
"behavior": {
"description": "[%key:component::number::common::trigger_behavior_description%]",
"name": "[%key:component::number::common::trigger_behavior_name%]"
},
"lower_limit": {
"description": "Lower threshold limit.",
"name": "Lower threshold"
},
"threshold_type": {
"description": "Type of threshold crossing to trigger on.",
"name": "Threshold type"
},
"upper_limit": {
"description": "Upper threshold limit.",
"name": "Upper threshold"
}
},
"name": "Number crossed threshold"
}
}
}

View File

@@ -5,6 +5,7 @@ from homeassistant.core import HomeAssistant
from homeassistant.helpers.trigger import (
Trigger,
make_entity_numerical_state_changed_trigger,
make_entity_numerical_state_crossed_threshold_trigger,
)
from .const import DOMAIN
@@ -13,6 +14,9 @@ TRIGGERS: dict[str, type[Trigger]] = {
"changed": make_entity_numerical_state_changed_trigger(
{DOMAIN, INPUT_NUMBER_DOMAIN}
),
"crossed_threshold": make_entity_numerical_state_crossed_threshold_trigger(
{DOMAIN, INPUT_NUMBER_DOMAIN}
),
}

View File

@@ -1,6 +1,59 @@
changed:
target:
.trigger_common:
target: &trigger_number_target
entity:
domain:
- number
- input_number
fields:
behavior: &trigger_behavior
required: true
default: any
selector:
select:
translation_key: trigger_behavior
options:
- first
- last
- any
.number_or_entity: &number_or_entity
required: false
selector:
choose:
choices:
number:
selector:
number:
mode: box
entity:
selector:
entity:
filter:
domain:
- input_number
- number
- sensor
translation_key: number_or_entity
.trigger_threshold_type: &trigger_threshold_type
required: true
default: above
selector:
select:
options:
- above
- below
- between
- outside
translation_key: trigger_threshold_type
changed:
target: *trigger_number_target
crossed_threshold:
target: *trigger_number_target
fields:
behavior: *trigger_behavior
threshold_type: *trigger_threshold_type
lower_limit: *number_or_entity
upper_limit: *number_or_entity

View File

@@ -797,6 +797,74 @@ class EntityNumericalStateAttributeCrossedThresholdTriggerBase(EntityTriggerBase
return not between
class EntityNumericalStateCrossedThresholdTriggerBase(EntityTriggerBase):
"""Trigger for numerical state changes.
This trigger only fires when the observed state changes from not within to within
the defined threshold.
"""
_schema = NUMERICAL_ATTRIBUTE_CROSSED_THRESHOLD_SCHEMA
_lower_limit: float | str | None = None
_upper_limit: float | str | None = None
_threshold_type: ThresholdType
_converter: Callable[[Any], float] = float
def __init__(self, hass: HomeAssistant, config: TriggerConfig) -> None:
"""Initialize the state trigger."""
super().__init__(hass, config)
self._lower_limit = self._options.get(CONF_LOWER_LIMIT)
self._upper_limit = self._options.get(CONF_UPPER_LIMIT)
self._threshold_type = self._options[CONF_THRESHOLD_TYPE]
def is_valid_transition(self, from_state: State, to_state: State) -> bool:
"""Check if the origin state is valid and the state has changed."""
if from_state.state in (STATE_UNAVAILABLE, STATE_UNKNOWN):
return False
return not self.is_valid_state(from_state)
def is_valid_state(self, state: State) -> bool:
"""Check if the new state matches the expected thresholds."""
if state.state in (STATE_UNAVAILABLE, STATE_UNKNOWN):
return False
if self._lower_limit is not None:
if (
lower_limit := _get_numerical_value(self._hass, self._lower_limit)
) is None:
# Entity not found or invalid number, don't trigger
return False
if self._upper_limit is not None:
if (
upper_limit := _get_numerical_value(self._hass, self._upper_limit)
) is None:
# Entity not found or invalid number, don't trigger
return False
try:
current_value = self._converter(state.state)
except TypeError, ValueError:
# Attribute is not a valid number, don't trigger
return False
# Note: We do not need to check for lower_limit/upper_limit being None here
# because of the validation done in the schema.
if self._threshold_type == ThresholdType.ABOVE:
return current_value > lower_limit # type: ignore[operator]
if self._threshold_type == ThresholdType.BELOW:
return current_value < upper_limit # type: ignore[operator]
# Mode is BETWEEN or OUTSIDE
between = lower_limit < current_value < upper_limit # type: ignore[operator]
if self._threshold_type == ThresholdType.BETWEEN:
return between
return not between
def make_entity_target_state_trigger(
domain: str, to_states: str | set[str]
) -> type[EntityTargetStateTriggerBase]:
@@ -886,6 +954,19 @@ def make_entity_numerical_state_changed_trigger(
return CustomTrigger
def make_entity_numerical_state_crossed_threshold_trigger(
domains: set[str],
) -> type[EntityNumericalStateCrossedThresholdTriggerBase]:
"""Create a trigger for numerical state change."""
class CustomTrigger(EntityNumericalStateCrossedThresholdTriggerBase):
"""Trigger for numerical state changes."""
_domains = domains
return CustomTrigger
def make_entity_target_state_attribute_trigger(
domain: str, attribute: str, to_state: str
) -> type[EntityTargetStateAttributeTriggerBase]:

View File

@@ -635,6 +635,52 @@ def parametrize_numerical_attribute_crossed_threshold_trigger_states(
]
def parametrize_numerical_crossed_threshold_trigger_states(
trigger: str,
) -> list[tuple[str, dict[str, Any], list[TriggerStateDescription]]]:
"""Parametrize states and expected service call counts for numerical crossed threshold triggers."""
return [
*parametrize_trigger_states(
trigger=trigger,
trigger_options={
CONF_THRESHOLD_TYPE: ThresholdType.BETWEEN,
CONF_LOWER_LIMIT: 10,
CONF_UPPER_LIMIT: 90,
},
target_states=["50", "60"],
other_states=["None", "0", "100"],
),
*parametrize_trigger_states(
trigger=trigger,
trigger_options={
CONF_THRESHOLD_TYPE: ThresholdType.OUTSIDE,
CONF_LOWER_LIMIT: 10,
CONF_UPPER_LIMIT: 90,
},
target_states=["0", "100"],
other_states=["None", "50", "60"],
),
*parametrize_trigger_states(
trigger=trigger,
trigger_options={
CONF_THRESHOLD_TYPE: ThresholdType.ABOVE,
CONF_LOWER_LIMIT: 10,
},
target_states=["50", "100"],
other_states=["None", "0"],
),
*parametrize_trigger_states(
trigger=trigger,
trigger_options={
CONF_THRESHOLD_TYPE: ThresholdType.BELOW,
CONF_UPPER_LIMIT: 90,
},
target_states=["0", "50"],
other_states=["None", "100"],
),
]
async def arm_trigger(
hass: HomeAssistant,
trigger: str,

View File

@@ -1,5 +1,7 @@
"""Test number entity trigger."""
from typing import Any
import pytest
from homeassistant.components.input_number import DOMAIN as INPUT_NUMBER_DOMAIN
@@ -15,6 +17,7 @@ from homeassistant.core import HomeAssistant, ServiceCall
from tests.components import (
TriggerStateDescription,
arm_trigger,
parametrize_numerical_crossed_threshold_trigger_states,
parametrize_target_entities,
set_or_remove_state,
target_entities,
@@ -37,6 +40,7 @@ async def target_input_numbers(hass: HomeAssistant) -> list[str]:
"trigger_key",
[
"number.changed",
"number.crossed_threshold",
],
)
async def test_number_triggers_gated_by_labs_flag(
@@ -222,3 +226,311 @@ async def test_input_number_changed_trigger_behavior(
await hass.async_block_till_done()
assert len(service_calls) == (entities_in_target - 1) * state["count"]
service_calls.clear()
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities(DOMAIN),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_numerical_crossed_threshold_trigger_states(
"number.crossed_threshold"
)
],
)
async def test_number_crossed_threshold_trigger_behavior_any(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_numbers: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the number crossed threshold trigger fires when any number crosses a threshold."""
other_entity_ids = set(target_numbers) - {entity_id}
# Set all numbers, including the tested number, to the initial state
for eid in target_numbers:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, trigger_options, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Check if changing other numbers also triggers
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == (entities_in_target - 1) * state["count"]
service_calls.clear()
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities(INPUT_NUMBER_DOMAIN),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_numerical_crossed_threshold_trigger_states(
"number.crossed_threshold"
)
],
)
async def test_input_number_crossed_threshold_trigger_behavior_any(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_input_numbers: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the number crossed threshold trigger fires when any input number state changes to a specific state."""
other_entity_ids = set(target_input_numbers) - {entity_id}
# Set all input numbers, including the tested input number, to the initial state
for eid in target_input_numbers:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, trigger_options, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Check if changing other numbers also triggers
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == (entities_in_target - 1) * state["count"]
service_calls.clear()
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities(DOMAIN),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_numerical_crossed_threshold_trigger_states(
"number.crossed_threshold"
)
],
)
async def test_number_crossed_threshold_trigger_behavior_first(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_numbers: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the number crossed threshold trigger fires when the first number state changes to a specific state."""
other_entity_ids = set(target_numbers) - {entity_id}
# Set all numbers, including the tested number, to the initial state
for eid in target_numbers:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(
hass, trigger, {"behavior": "first"} | trigger_options, trigger_target_config
)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Triggering other numbers should not cause the trigger to fire again
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities(INPUT_NUMBER_DOMAIN),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_numerical_crossed_threshold_trigger_states(
"number.crossed_threshold"
)
],
)
async def test_input_number_crossed_threshold_trigger_behavior_first(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_input_numbers: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the number crossed threshold trigger fires when any input number state changes to a specific state."""
other_entity_ids = set(target_input_numbers) - {entity_id}
# Set all input numbers, including the tested input number, to the initial state
for eid in target_input_numbers:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(
hass, trigger, {"behavior": "first"} | trigger_options, trigger_target_config
)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Triggering other input numbers should not cause the trigger to fire again
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities(DOMAIN),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_numerical_crossed_threshold_trigger_states(
"number.crossed_threshold"
)
],
)
async def test_number_crossed_threshold_trigger_behavior_last(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_numbers: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the number crossed threshold trigger fires when the last number state changes to a specific state."""
other_entity_ids = set(target_numbers) - {entity_id}
# Set all numbers, including the tested number, to the initial state
for eid in target_numbers:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(
hass, trigger, {"behavior": "last"} | trigger_options, trigger_target_config
)
for state in states[1:]:
included_state = state["included"]
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities(INPUT_NUMBER_DOMAIN),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_numerical_crossed_threshold_trigger_states(
"number.crossed_threshold"
)
],
)
async def test_input_number_crossed_threshold_trigger_behavior_last(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_input_numbers: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the number crossed threshold trigger fires when the last input number state changes to a specific state."""
other_entity_ids = set(target_input_numbers) - {entity_id}
# Set all input numbers, including the tested input number, to the initial state
for eid in target_input_numbers:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(
hass, trigger, {"behavior": "last"} | trigger_options, trigger_target_config
)
for state in states[1:]:
included_state = state["included"]
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()