Track availability of source sensor in utility meter (#91035)

* track availability of source sensor

* address review comments
pull/91180/head
Diogo Gomes 2023-04-10 17:37:45 +01:00 committed by GitHub
parent ee1644c24e
commit 86fe0c9683
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 13 additions and 5 deletions

View File

@ -423,6 +423,15 @@ class UtilityMeterSensor(RestoreSensor):
@callback
def async_reading(self, event: Event):
"""Handle the sensor state changes."""
if (
source_state := self.hass.states.get(self._sensor_source_id)
) is None or source_state.state == STATE_UNAVAILABLE:
self._attr_available = False
self.async_write_ha_state()
return
self._attr_available = True
old_state: State | None = event.data.get("old_state")
new_state: State = event.data.get("new_state") # type: ignore[assignment] # a state change event always has a new state

View File

@ -217,20 +217,19 @@ async def test_state(hass: HomeAssistant, yaml_config, config_entry_config) -> N
entity_id, "*", {ATTR_UNIT_OF_MEASUREMENT: UnitOfEnergy.KILO_WATT_HOUR}
)
await hass.async_block_till_done()
state = hass.states.get("sensor.energy_bill_midpeak")
state = hass.states.get("sensor.energy_bill_offpeak")
assert state is not None
assert state.state == "0.123"
assert state.state == "3"
# test unavailable source
hass.states.async_set(
entity_id,
STATE_UNAVAILABLE,
{ATTR_UNIT_OF_MEASUREMENT: UnitOfEnergy.KILO_WATT_HOUR},
)
await hass.async_block_till_done()
state = hass.states.get("sensor.energy_bill_midpeak")
state = hass.states.get("sensor.energy_bill_offpeak")
assert state is not None
assert state.state == "0.123"
assert state.state == "unavailable"
@pytest.mark.parametrize(