Fix filter sensor dropping first reading after unit change (#187645)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Raman Gupta
2026-10-20 23:21:58 -04:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 569e2bfb1e
commit b330c60105
2 changed files with 59 additions and 9 deletions
+10 -9
View File
@@ -287,6 +287,16 @@ class SensorFilter(SensorEntity):
temp_state = _State(new_state.last_updated, new_state.state)
# Reset before filtering so the new unit's first reading is kept
if self._attr_native_unit_of_measurement != new_state.attributes.get(
EntityStateAttribute.UNIT_OF_MEASUREMENT
):
for filt in self._filters:
filt.reset()
self._attr_native_unit_of_measurement = new_state.attributes.get(
EntityStateAttribute.UNIT_OF_MEASUREMENT
)
try:
for filt in self._filters:
filtered_state = filt.filter_state(copy(temp_state))
@@ -318,15 +328,6 @@ class SensorFilter(SensorEntity):
SensorEntityCapabilityAttribute.STATE_CLASS
)
if self._attr_native_unit_of_measurement != new_state.attributes.get(
EntityStateAttribute.UNIT_OF_MEASUREMENT
):
for filt in self._filters:
filt.reset()
self._attr_native_unit_of_measurement = new_state.attributes.get(
EntityStateAttribute.UNIT_OF_MEASUREMENT
)
if update_ha:
self.async_write_ha_state()
+49
View File
@@ -107,6 +107,55 @@ async def test_chain(
assert state.state == "18.05"
@pytest.mark.parametrize(
("readings", "expected_states"),
[
pytest.param(
[("10", None), ("20", None), ("30", None)],
["10.0", "11.0", "12.9"],
id="no_unit",
),
pytest.param(
[("10", "W"), ("20", "W"), ("30", "W")],
["10.0", "11.0", "12.9"],
id="constant_unit",
),
pytest.param(
[("10", "W"), ("20", "W"), ("30", "kW"), ("40", "kW")],
["10.0", "11.0", "30.0", "31.0"],
id="unit_change_resets_filters",
),
],
)
async def test_unit_of_measurement_reset(
recorder_mock: Recorder,
hass: HomeAssistant,
readings: list[tuple[str, str | None]],
expected_states: list[str],
) -> None:
"""Test filters are reset before, not after, a reading with a new unit."""
config = {
"sensor": {
"platform": "filter",
"name": "test",
"entity_id": "sensor.test_monitored",
"filters": [{"filter": "lowpass", "time_constant": 10, "precision": 2}],
}
}
assert await async_setup_component(hass, "sensor", config)
await hass.async_block_till_done()
states = []
for value, unit in readings:
hass.states.async_set(
"sensor.test_monitored", value, {ATTR_UNIT_OF_MEASUREMENT: unit}
)
await hass.async_block_till_done()
states.append(hass.states.get("sensor.test").state)
assert states == expected_states
async def test_from_config_entry(
recorder_mock: Recorder,
hass: HomeAssistant,