Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Track availability of source sensor in utility meter #91035

Merged
merged 2 commits into from
Apr 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions homeassistant/components/utility_meter/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,15 @@ def calculate_adjustment(
@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
bdraco marked this conversation as resolved.
Show resolved Hide resolved
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

Expand Down
9 changes: 4 additions & 5 deletions tests/components/utility_meter/test_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down