Fix availability for manual trigger entities

This commit is contained in:
G Johansson 2024-10-09 18:59:04 +00:00
parent e6bba49bcd
commit cfe681f441
2 changed files with 71 additions and 4 deletions

View file

@ -26,6 +26,7 @@ from homeassistant.const import (
)
from homeassistant.core import HomeAssistant, State, callback
from homeassistant.exceptions import TemplateError
from homeassistant.util import dt as dt_util
from homeassistant.util.json import JSON_DECODE_EXCEPTIONS, json_loads
from . import config_validation as cv
@ -231,10 +232,26 @@ class ManualTriggerEntity(TriggerBaseEntity):
Ex: self._process_manual_data(payload)
"""
self.async_write_ha_state()
this = None
if state := self.hass.states.get(self.entity_id):
this = state.as_dict()
now = dt_util.utcnow()
attr = {}
if state_attributes := self.state_attributes:
attr.update(state_attributes)
if extra_state_attributes := self.extra_state_attributes:
attr.update(extra_state_attributes)
state = State(
self.entity_id,
str(value),
attr,
now,
now,
now,
None,
True,
None,
now.timestamp(),
)
this = state.as_dict()
run_variables: dict[str, Any] = {"value": value}
# Silently try if variable is a json and store result in `value_json` if it is.
@ -243,6 +260,7 @@ class ManualTriggerEntity(TriggerBaseEntity):
variables = {"this": this, **(run_variables or {})}
self._render_templates(variables)
self.async_write_ha_state()
class ManualTriggerSensorEntity(ManualTriggerEntity, SensorEntity):

View file

@ -808,3 +808,52 @@ async def test_availability(
entity_state = hass.states.get("sensor.test")
assert entity_state
assert entity_state.state == STATE_UNAVAILABLE
@pytest.mark.parametrize(
"get_config",
[
{
"command_line": [
{
"sensor": {
"name": "Test",
"command": "echo {{ states.sensor.input_sensor.state }}",
"availability": "{{ value|is_number}}",
"unit_of_measurement": " ",
"state_class": "measurement",
}
}
]
}
],
)
async def test_template_render_not_break_for_availability(
hass: HomeAssistant, load_yaml_integration: None
) -> None:
"""Ensure command with templates get rendered properly."""
hass.states.async_set("sensor.input_sensor", "sensor_value")
# Give time for template to load
async_fire_time_changed(
hass,
dt_util.utcnow() + timedelta(minutes=1),
)
await hass.async_block_till_done(wait_background_tasks=True)
entity_state = hass.states.get("sensor.test")
assert entity_state
assert entity_state.state == STATE_UNAVAILABLE
hass.states.async_set("sensor.input_sensor", "1")
# Give time for template to load
async_fire_time_changed(
hass,
dt_util.utcnow() + timedelta(minutes=1),
)
await hass.async_block_till_done(wait_background_tasks=True)
entity_state = hass.states.get("sensor.test")
assert entity_state
assert entity_state.state == "1"