Skip to content

Commit

Permalink
Mark trend sensor unavailable when source entity is unknown/unavailab…
Browse files Browse the repository at this point in the history
…le (#132080)
  • Loading branch information
jpbede authored and frenck committed Dec 3, 2024
1 parent 895ffba commit c6468ac
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 3 deletions.
9 changes: 7 additions & 2 deletions homeassistant/components/trend/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,10 +227,15 @@ def trend_sensor_state_listener(
state = new_state.attributes.get(self._attribute)
else:
state = new_state.state
if state not in (STATE_UNKNOWN, STATE_UNAVAILABLE):

if state in (STATE_UNKNOWN, STATE_UNAVAILABLE):
self._attr_available = False
else:
self._attr_available = True
sample = (new_state.last_updated.timestamp(), float(state)) # type: ignore[arg-type]
self.samples.append(sample)
self.async_schedule_update_ha_state(True)

self.async_schedule_update_ha_state(True)
except (ValueError, TypeError) as ex:
_LOGGER.error(ex)

Expand Down
44 changes: 43 additions & 1 deletion tests/components/trend/test_binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

from homeassistant import setup
from homeassistant.components.trend.const import DOMAIN
from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNKNOWN
from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNAVAILABLE, STATE_UNKNOWN
from homeassistant.core import HomeAssistant, State
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.setup import async_setup_component
Expand Down Expand Up @@ -395,3 +395,45 @@ async def test_device_id(
trend_entity = entity_registry.async_get("binary_sensor.trend")
assert trend_entity is not None
assert trend_entity.device_id == source_entity.device_id


@pytest.mark.parametrize(
"error_state",
[
STATE_UNKNOWN,
STATE_UNAVAILABLE,
],
)
async def test_unavailable_source(
hass: HomeAssistant,
config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
setup_component: ComponentSetup,
error_state: str,
) -> None:
"""Test for unavailable source."""
await setup_component(
{
"sample_duration": 10000,
"min_gradient": 1,
"max_samples": 25,
"min_samples": 5,
},
)

for val in (10, 20, 30, 40, 50, 60):
freezer.tick(timedelta(seconds=2))
hass.states.async_set("sensor.test_state", val)
await hass.async_block_till_done()

assert hass.states.get("binary_sensor.test_trend_sensor").state == "on"

hass.states.async_set("sensor.test_state", error_state)
await hass.async_block_till_done()

assert hass.states.get("binary_sensor.test_trend_sensor").state == STATE_UNAVAILABLE

hass.states.async_set("sensor.test_state", 50)
await hass.async_block_till_done()

assert hass.states.get("binary_sensor.test_trend_sensor").state == "on"

0 comments on commit c6468ac

Please sign in to comment.