Add RestoreClimate base which stores unconverted temperatures (#186105)

This commit is contained in:
Erik Montnemery
2026-10-13 13:55:30 +02:00
committed by GitHub
parent 723477a0cc
commit de7e90f494
4 changed files with 542 additions and 6 deletions
+146 -3
View File
@@ -1,9 +1,11 @@
"""Provides functionality to interact with climate devices."""
from dataclasses import asdict, dataclass
from datetime import timedelta
import functools as ft
import logging
from typing import Any, Final, Literal, final, override
import math
from typing import Any, Final, Literal, Self, final, override
from propcache.api import cached_property
@@ -20,7 +22,7 @@ from homeassistant.const import ( # noqa: F401
SERVICE_TURN_ON,
UnitOfTemperature,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.core import HomeAssistant, State, callback
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.deprecation import (
@@ -31,9 +33,13 @@ from homeassistant.helpers.deprecation import (
from homeassistant.helpers.entity import Entity, EntityDescription
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.frame import ReportBehavior
from homeassistant.helpers.restore_state import ExtraStoredData, RestoreEntity
from homeassistant.helpers.temperature import display_temp as show_temp
from homeassistant.helpers.typing import ConfigType
from homeassistant.util.unit_conversion import TemperatureConverter
from homeassistant.util.unit_conversion import (
TemperatureConverter,
TemperatureDeltaConverter,
)
from .const import ( # noqa: F401
ATTR_CURRENT_HUMIDITY,
@@ -765,3 +771,140 @@ class ClimateEntity(Entity, cached_properties=CACHED_PROPERTIES_WITH_ATTR_):
def target_humidity_step(self) -> int | None:
"""Return the supported step of humidity."""
return self._attr_target_humidity_step
@dataclass(kw_only=True)
class ClimateExtraStoredData(ExtraStoredData):
"""Native temperatures of a climate entity, stored for restoring."""
native_current_temperature: float | None
native_target_temperature: float | None
native_target_temperature_high: float | None
native_target_temperature_low: float | None
native_temperature_unit: str
@override
def as_dict(self) -> dict[str, Any]:
"""Return a dict representation of the climate data."""
return asdict(self)
@classmethod
def from_dict(cls, restored: dict[str, Any]) -> Self | None:
"""Initialize stored climate data from a dict."""
try:
return cls(
native_current_temperature=restored["native_current_temperature"],
native_target_temperature=restored["native_target_temperature"],
native_target_temperature_high=restored[
"native_target_temperature_high"
],
native_target_temperature_low=restored["native_target_temperature_low"],
native_temperature_unit=restored["native_temperature_unit"],
)
except KeyError:
return None
@classmethod
def from_state(cls, state: State, default_unit: str) -> Self:
"""Initialize stored climate data from the attributes of a state.
The attributes are in the unit of the system; states written before the
temperature_unit attribute was added are assumed to be in default_unit.
"""
attributes = state.attributes
return cls(
native_current_temperature=attributes.get(
ClimateEntityStateAttribute.CURRENT_TEMPERATURE
),
native_target_temperature=attributes.get(
ClimateEntityStateAttribute.TARGET_TEMPERATURE
),
native_target_temperature_high=attributes.get(
ClimateEntityStateAttribute.TARGET_TEMP_HIGH
),
native_target_temperature_low=attributes.get(
ClimateEntityStateAttribute.TARGET_TEMP_LOW
),
native_temperature_unit=attributes.get(
ClimateEntityStateAttribute.TEMPERATURE_UNIT, default_unit
),
)
class RestoreClimate(ClimateEntity, RestoreEntity):
"""Mixin class for restoring previous climate temperatures."""
@property
@override
def extra_restore_state_data(self) -> ClimateExtraStoredData:
"""Return climate specific state data to be restored."""
high = low = None
# High/low have no default and are only implemented with this feature
if ClimateEntityFeature.TARGET_TEMPERATURE_RANGE in self.supported_features:
high = self.native_target_temperature_high
low = self.native_target_temperature_low
return ClimateExtraStoredData(
native_current_temperature=self.native_current_temperature,
native_target_temperature=self.native_target_temperature,
native_target_temperature_high=high,
native_target_temperature_low=low,
native_temperature_unit=self.native_temperature_unit,
)
async def async_get_last_climate_data(
self, *, validate_range: bool = False
) -> ClimateExtraStoredData | None:
"""Return the last stored temperatures, in the current native unit.
Falls back to the attributes of the last state when it was saved without
extra data. Temperatures which are not valid numbers are returned as None.
With validate_range, target temperatures outside min_temp and max_temp are
returned as None. Use it when the restored targets are sent to the device,
e.g. by entities which can't read their state back from it. Targets up to
half a degree (in the stored unit) outside the range are clamped instead,
as the attributes of the last state may be rounded for display.
"""
if (extra_data := await self.async_get_last_extra_data()) is None or (
stored := ClimateExtraStoredData.from_dict(extra_data.as_dict())
) is None:
if (state := await self.async_get_last_state()) is None:
return None
stored = ClimateExtraStoredData.from_state(
state, self.hass.config.units.temperature_unit
)
if (unit := stored.native_temperature_unit) not in (
TemperatureConverter.VALID_UNITS
):
return None
native_unit = self.native_temperature_unit
def _convert(value: Any) -> float | None:
try:
value = TemperatureConverter.convert(float(value), unit, native_unit)
except TypeError, ValueError, OverflowError:
return None
return value if math.isfinite(value) else None
def _convert_target(value: Any) -> float | None:
if (temperature := _convert(value)) is None or not validate_range:
return temperature
min_temp = self.min_temp
max_temp = self.max_temp
tolerance = TemperatureDeltaConverter.convert(0.5, unit, native_unit)
if not min_temp - tolerance <= temperature <= max_temp + tolerance:
return None
return min(max(temperature, min_temp), max_temp)
return ClimateExtraStoredData(
native_current_temperature=_convert(stored.native_current_temperature),
native_target_temperature=_convert_target(stored.native_target_temperature),
native_target_temperature_high=_convert_target(
stored.native_target_temperature_high
),
native_target_temperature_low=_convert_target(
stored.native_target_temperature_low
),
native_temperature_unit=native_unit,
)
@@ -32,7 +32,7 @@ _MODULES: dict[str, set[str]] = {
Platform.BUTTON: {"ButtonEntity", "ButtonEntityDescription"},
Platform.CALENDAR: {"CalendarEntity", "CalendarEntityDescription"},
Platform.CAMERA: {"Camera", "CameraEntityDescription"},
Platform.CLIMATE: {"ClimateEntity", "ClimateEntityDescription"},
Platform.CLIMATE: {"ClimateEntity", "ClimateEntityDescription", "RestoreClimate"},
Module.COORDINATOR: {"DataUpdateCoordinator"},
Platform.CONVERSATION: {"ConversationEntity"},
Platform.COVER: {"CoverEntity", "CoverEntityDescription"},
@@ -1307,6 +1307,19 @@ _INHERITANCE_MATCH: dict[str, list[ClassTypeHintMatch]] = {
),
],
),
ClassTypeHintMatch(
base_class="RestoreClimate",
matches=[
TypeHintMatch(
function_name="extra_restore_state_data",
return_type="ClimateExtraStoredData",
),
TypeHintMatch(
function_name="async_get_last_climate_data",
return_type=["ClimateExtraStoredData", None],
),
],
),
],
Platform.COVER: [
ClassTypeHintMatch(
+382 -2
View File
@@ -9,7 +9,13 @@ import probatio
from propcache.api import cached_property
import pytest
from homeassistant.components.climate import DOMAIN, ClimateEntity, HVACMode
from homeassistant.components.climate import (
DOMAIN,
ClimateEntity,
ClimateExtraStoredData,
HVACMode,
RestoreClimate,
)
from homeassistant.components.climate.const import (
ATTR_CURRENT_TEMPERATURE,
ATTR_FAN_MODE,
@@ -40,8 +46,10 @@ from homeassistant.components.climate.services import (
_async_service_temperature_set,
)
from homeassistant.const import ATTR_TEMPERATURE, PRECISION_WHOLE, UnitOfTemperature
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.core import HomeAssistant, ServiceCall, State
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers.restore_state import STORAGE_KEY as RESTORE_STATE_KEY
from homeassistant.util.unit_conversion import TemperatureConverter
from homeassistant.util.unit_system import (
METRIC_SYSTEM,
US_CUSTOMARY_SYSTEM,
@@ -51,7 +59,9 @@ from homeassistant.util.unit_system import (
from tests.common import (
MockConfigEntry,
MockEntity,
async_mock_restore_state_shutdown_restart,
async_mock_service,
mock_restore_cache_with_extra_data,
setup_test_component_platform,
)
@@ -1951,3 +1961,373 @@ async def test_migrated_grandparent_property_wins_over_descendant_attributes(
assert getattr(entity, f"native_{member}") is grandparent_value
assert getattr(entity, member) is grandparent_value
class MockRestoreClimate(MockClimateEntity, RestoreClimate):
"""Mock climate entity restoring its temperatures when added."""
_attr_min_temp = 4
_attr_max_temp = 30
restored: ClimateExtraStoredData | None
def __init__(self, validate_range: bool = False, **values: Any) -> None:
"""Initialize the entity."""
super().__init__(**values)
self._validate_range = validate_range
async def async_added_to_hass(self) -> None:
"""Restore the temperatures."""
await super().async_added_to_hass()
self.restored = await self.async_get_last_climate_data(
validate_range=self._validate_range
)
@pytest.mark.parametrize(
("supported_features", "expected"),
[
pytest.param(
ClimateEntityFeature.TARGET_TEMPERATURE,
{
"native_current_temperature": 21.5,
"native_target_temperature": 20,
"native_target_temperature_high": None,
"native_target_temperature_low": None,
"native_temperature_unit": UnitOfTemperature.FAHRENHEIT,
},
id="target",
),
pytest.param(
ClimateEntityFeature.TARGET_TEMPERATURE_RANGE,
{
"native_current_temperature": 21.5,
"native_target_temperature": 20,
"native_target_temperature_high": 25,
"native_target_temperature_low": 15,
"native_temperature_unit": UnitOfTemperature.FAHRENHEIT,
},
id="range",
),
],
)
async def test_restore_climate_save_state(
hass: HomeAssistant,
hass_storage: dict[str, Any],
register_test_integration: MockConfigEntry,
supported_features: ClimateEntityFeature,
expected: dict[str, Any],
) -> None:
"""Test RestoreClimate stores its temperatures in the native unit."""
entity = MockRestoreClimate(name="test", entity_id="climate.test")
entity._attr_supported_features = supported_features
entity._attr_native_current_temperature = 21.5
entity._attr_native_temperature_unit = UnitOfTemperature.FAHRENHEIT
setup_test_component_platform(
hass, DOMAIN, entities=[entity], from_config_entry=True
)
await hass.config_entries.async_setup(register_test_integration.entry_id)
await hass.async_block_till_done()
await async_mock_restore_state_shutdown_restart(hass)
assert len(hass_storage[RESTORE_STATE_KEY]["data"]) == 1
assert hass_storage[RESTORE_STATE_KEY]["data"][0]["extra_data"] == expected
STORED_CELSIUS = {
"native_current_temperature": 21.5,
"native_target_temperature": 20,
"native_target_temperature_high": 25,
"native_target_temperature_low": 15,
"native_temperature_unit": UnitOfTemperature.CELSIUS,
}
STORED_FAHRENHEIT = {
"native_current_temperature": 50,
"native_target_temperature": 68,
"native_target_temperature_high": 77,
"native_target_temperature_low": 59,
"native_temperature_unit": UnitOfTemperature.FAHRENHEIT,
}
ATTRIBUTES_FAHRENHEIT = {
ClimateEntityStateAttribute.CURRENT_TEMPERATURE: 50,
ClimateEntityStateAttribute.TARGET_TEMPERATURE: 68,
ClimateEntityStateAttribute.TARGET_TEMP_HIGH: 77,
ClimateEntityStateAttribute.TARGET_TEMP_LOW: 59,
}
def _restored(
current: float | None, target: float | None, high: float | None, low: float | None
) -> ClimateExtraStoredData:
"""Return restored climate data in Celsius."""
return ClimateExtraStoredData(
native_current_temperature=current,
native_target_temperature=target,
native_target_temperature_high=high,
native_target_temperature_low=low,
native_temperature_unit=UnitOfTemperature.CELSIUS,
)
@pytest.mark.parametrize(
("unit_system", "attributes", "extra_data", "validate_range", "expected"),
[
pytest.param(
METRIC_SYSTEM,
{},
STORED_CELSIUS,
False,
_restored(21.5, 20, 25, 15),
id="extra_data",
),
pytest.param(
METRIC_SYSTEM,
{},
STORED_FAHRENHEIT,
False,
_restored(10, 20, 25, 15),
id="extra_data_other_native_unit",
),
pytest.param(
US_CUSTOMARY_SYSTEM,
{
**ATTRIBUTES_FAHRENHEIT,
ClimateEntityStateAttribute.TEMPERATURE_UNIT: (
UnitOfTemperature.FAHRENHEIT
),
},
STORED_CELSIUS,
False,
_restored(21.5, 20, 25, 15),
id="extra_data_preferred_over_attributes",
),
pytest.param(
METRIC_SYSTEM,
{
**ATTRIBUTES_FAHRENHEIT,
ClimateEntityStateAttribute.TEMPERATURE_UNIT: (
UnitOfTemperature.FAHRENHEIT
),
},
None,
False,
_restored(10, 20, 25, 15),
id="attributes_with_unit",
),
pytest.param(
METRIC_SYSTEM,
{
**ATTRIBUTES_FAHRENHEIT,
ClimateEntityStateAttribute.TEMPERATURE_UNIT: (
UnitOfTemperature.FAHRENHEIT
),
},
{"native_target_temperature": 21},
False,
_restored(10, 20, 25, 15),
id="attributes_with_incomplete_extra_data",
),
pytest.param(
US_CUSTOMARY_SYSTEM,
ATTRIBUTES_FAHRENHEIT,
None,
False,
_restored(10, 20, 25, 15),
id="attributes_without_unit_in_system_unit",
),
pytest.param(
METRIC_SYSTEM,
{ClimateEntityStateAttribute.TARGET_TEMPERATURE: 20},
None,
False,
_restored(None, 20, None, None),
id="attributes_without_unit_metric",
),
pytest.param(
METRIC_SYSTEM,
{},
{**STORED_CELSIUS, "native_temperature_unit": "invalid"},
False,
None,
id="invalid_unit_extra_data",
),
pytest.param(
METRIC_SYSTEM,
{
ClimateEntityStateAttribute.TARGET_TEMPERATURE: 20,
ClimateEntityStateAttribute.TEMPERATURE_UNIT: "invalid",
},
None,
False,
None,
id="invalid_unit_attributes",
),
pytest.param(
METRIC_SYSTEM,
{},
{
**STORED_CELSIUS,
"native_current_temperature": 0,
"native_target_temperature": "abc",
"native_target_temperature_high": [],
"native_target_temperature_low": "nan",
},
False,
_restored(0, None, None, None),
id="invalid_values",
),
pytest.param(
METRIC_SYSTEM,
{},
{
**STORED_CELSIUS,
"native_current_temperature": "inf",
"native_target_temperature": "21.5",
},
False,
_restored(None, 21.5, 25, 15),
id="numeric_strings",
),
pytest.param(
METRIC_SYSTEM,
{},
{
**STORED_CELSIUS,
"native_current_temperature": 40,
"native_target_temperature": 31,
"native_target_temperature_high": 30,
"native_target_temperature_low": 3,
},
False,
_restored(40, 31, 30, 3),
id="out_of_range_kept",
),
pytest.param(
METRIC_SYSTEM,
{},
{
**STORED_CELSIUS,
"native_current_temperature": 40,
"native_target_temperature": 31,
"native_target_temperature_high": 30,
"native_target_temperature_low": 3,
},
True,
_restored(40, None, 30, None),
id="out_of_range_validated",
),
pytest.param(
METRIC_SYSTEM,
{},
{
**STORED_CELSIUS,
"native_target_temperature": 30.4,
"native_target_temperature_high": 30.5,
"native_target_temperature_low": 3.4,
},
True,
_restored(21.5, 30, 30, None),
id="slightly_out_of_range_clamped",
),
pytest.param(
US_CUSTOMARY_SYSTEM,
{ClimateEntityStateAttribute.TARGET_TEMPERATURE: 39},
None,
False,
_restored(
None,
TemperatureConverter.convert(
39, UnitOfTemperature.FAHRENHEIT, UnitOfTemperature.CELSIUS
),
None,
None,
),
id="rounded_attribute",
),
pytest.param(
US_CUSTOMARY_SYSTEM,
{ClimateEntityStateAttribute.TARGET_TEMPERATURE: 39},
None,
True,
_restored(None, 4, None, None),
id="rounded_attribute_clamped",
),
pytest.param(
US_CUSTOMARY_SYSTEM,
{ClimateEntityStateAttribute.TARGET_TEMPERATURE: 38},
None,
True,
_restored(None, None, None, None),
id="attribute_out_of_range_validated",
),
],
)
async def test_restore_climate_restore_state(
hass: HomeAssistant,
register_test_integration: MockConfigEntry,
unit_system: UnitSystem,
attributes: dict[str, Any],
extra_data: dict[str, Any] | None,
validate_range: bool,
expected: ClimateExtraStoredData | None,
) -> None:
"""Test RestoreClimate restores its temperatures in the native unit."""
hass.config.units = unit_system
mock_restore_cache_with_extra_data(
hass, ((State("climate.test", HVACMode.HEAT, attributes), extra_data),)
)
entity = MockRestoreClimate(
validate_range=validate_range, name="test", entity_id="climate.test"
)
setup_test_component_platform(
hass, DOMAIN, entities=[entity], from_config_entry=True
)
await hass.config_entries.async_setup(register_test_integration.entry_id)
await hass.async_block_till_done()
assert entity.restored == expected
async def test_restore_climate_overflow(
hass: HomeAssistant, register_test_integration: MockConfigEntry
) -> None:
"""Test RestoreClimate drops temperatures which overflow a float."""
mock_restore_cache_with_extra_data(
hass,
(
(
State("climate.test", HVACMode.HEAT),
{
**STORED_CELSIUS,
# Finite in Celsius, but infinite once converted to Fahrenheit
"native_current_temperature": 1e308,
"native_target_temperature": 10**400,
},
),
),
)
entity = MockRestoreClimate(name="test", entity_id="climate.test")
entity._attr_native_temperature_unit = UnitOfTemperature.FAHRENHEIT
setup_test_component_platform(
hass, DOMAIN, entities=[entity], from_config_entry=True
)
await hass.config_entries.async_setup(register_test_integration.entry_id)
await hass.async_block_till_done()
assert entity.restored is not None
assert entity.restored.native_current_temperature is None
assert entity.restored.native_target_temperature is None
async def test_restore_climate_no_last_state(
hass: HomeAssistant, register_test_integration: MockConfigEntry
) -> None:
"""Test RestoreClimate restores nothing without a last state."""
entity = MockRestoreClimate(name="test", entity_id="climate.test")
setup_test_component_platform(
hass, DOMAIN, entities=[entity], from_config_entry=True
)
await hass.config_entries.async_setup(register_test_integration.entry_id)
await hass.async_block_till_done()
assert entity.restored is None