Home Assistant Unofficial Reference 2024.12.1
climate.py
Go to the documentation of this file.
1 """Climate support for Shelly."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Mapping
6 from dataclasses import asdict, dataclass
7 from typing import Any, cast
8 
9 from aioshelly.block_device import Block
10 from aioshelly.const import RPC_GENERATIONS
11 from aioshelly.exceptions import DeviceConnectionError, InvalidAuthError
12 
14  DOMAIN as CLIMATE_DOMAIN,
15  PRESET_NONE,
16  ClimateEntity,
17  ClimateEntityFeature,
18  HVACAction,
19  HVACMode,
20 )
21 from homeassistant.const import ATTR_TEMPERATURE, UnitOfTemperature
22 from homeassistant.core import HomeAssistant, State, callback
23 from homeassistant.exceptions import HomeAssistantError
24 from homeassistant.helpers import entity_registry as er, issue_registry as ir
25 from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, DeviceInfo
26 from homeassistant.helpers.entity_platform import AddEntitiesCallback
27 from homeassistant.helpers.entity_registry import RegistryEntry
28 from homeassistant.helpers.restore_state import ExtraStoredData, RestoreEntity
29 from homeassistant.helpers.update_coordinator import CoordinatorEntity
30 from homeassistant.util.unit_conversion import TemperatureConverter
31 from homeassistant.util.unit_system import US_CUSTOMARY_SYSTEM
32 
33 from .const import (
34  DOMAIN,
35  LOGGER,
36  NOT_CALIBRATED_ISSUE_ID,
37  RPC_THERMOSTAT_SETTINGS,
38  SHTRV_01_TEMPERATURE_SETTINGS,
39 )
40 from .coordinator import ShellyBlockCoordinator, ShellyConfigEntry, ShellyRpcCoordinator
41 from .entity import ShellyRpcEntity
42 from .utils import (
43  async_remove_shelly_entity,
44  get_device_entry_gen,
45  get_rpc_key_ids,
46  is_rpc_thermostat_internal_actuator,
47 )
48 
49 
51  hass: HomeAssistant,
52  config_entry: ShellyConfigEntry,
53  async_add_entities: AddEntitiesCallback,
54 ) -> None:
55  """Set up climate device."""
56  if get_device_entry_gen(config_entry) in RPC_GENERATIONS:
57  async_setup_rpc_entry(hass, config_entry, async_add_entities)
58  return
59 
60  coordinator = config_entry.runtime_data.block
61  assert coordinator
62  if coordinator.device.initialized:
63  async_setup_climate_entities(async_add_entities, coordinator)
64  else:
66  hass, config_entry, async_add_entities, coordinator
67  )
68 
69 
70 @callback
72  async_add_entities: AddEntitiesCallback,
73  coordinator: ShellyBlockCoordinator,
74 ) -> None:
75  """Set up online climate devices."""
76 
77  device_block: Block | None = None
78  sensor_block: Block | None = None
79 
80  assert coordinator.device.blocks
81 
82  for block in coordinator.device.blocks:
83  if block.type == "device":
84  device_block = block
85  if hasattr(block, "targetTemp"):
86  sensor_block = block
87 
88  if sensor_block and device_block:
89  LOGGER.debug("Setup online climate device %s", coordinator.name)
91  [BlockSleepingClimate(coordinator, sensor_block, device_block)]
92  )
93 
94 
95 @callback
97  hass: HomeAssistant,
98  config_entry: ShellyConfigEntry,
99  async_add_entities: AddEntitiesCallback,
100  coordinator: ShellyBlockCoordinator,
101 ) -> None:
102  """Restore sleeping climate devices."""
103 
104  ent_reg = er.async_get(hass)
105  entries = er.async_entries_for_config_entry(ent_reg, config_entry.entry_id)
106 
107  for entry in entries:
108  if entry.domain != CLIMATE_DOMAIN:
109  continue
110 
111  LOGGER.debug("Setup sleeping climate device %s", coordinator.name)
112  LOGGER.debug("Found entry %s [%s]", entry.original_name, entry.domain)
113  async_add_entities([BlockSleepingClimate(coordinator, None, None, entry)])
114  break
115 
116 
117 @callback
119  hass: HomeAssistant,
120  config_entry: ShellyConfigEntry,
121  async_add_entities: AddEntitiesCallback,
122 ) -> None:
123  """Set up entities for RPC device."""
124  coordinator = config_entry.runtime_data.rpc
125  assert coordinator
126  climate_key_ids = get_rpc_key_ids(coordinator.device.status, "thermostat")
127 
128  climate_ids = []
129  for id_ in climate_key_ids:
130  climate_ids.append(id_)
131  # There are three configuration scenarios for WallDisplay:
132  # - relay mode (no thermostat)
133  # - thermostat mode using the internal relay as an actuator
134  # - thermostat mode using an external (from another device) relay as
135  # an actuator
136  if is_rpc_thermostat_internal_actuator(coordinator.device.status):
137  # Wall Display relay is used as the thermostat actuator,
138  # we need to remove a switch entity
139  unique_id = f"{coordinator.mac}-switch:{id_}"
140  async_remove_shelly_entity(hass, "switch", unique_id)
141 
142  if not climate_ids:
143  return
144 
145  async_add_entities(RpcClimate(coordinator, id_) for id_ in climate_ids)
146 
147 
148 @dataclass
150  """Object to hold extra stored data."""
151 
152  last_target_temp: float | None = None
153 
154  def as_dict(self) -> dict[str, Any]:
155  """Return a dict representation of the text data."""
156  return asdict(self)
157 
158 
160  CoordinatorEntity[ShellyBlockCoordinator], RestoreEntity, ClimateEntity
161 ):
162  """Representation of a Shelly climate device."""
163 
164  _attr_hvac_modes = [HVACMode.OFF, HVACMode.HEAT]
165  _attr_max_temp = SHTRV_01_TEMPERATURE_SETTINGS["max"]
166  _attr_min_temp = SHTRV_01_TEMPERATURE_SETTINGS["min"]
167  _attr_supported_features = (
168  ClimateEntityFeature.TARGET_TEMPERATURE
169  | ClimateEntityFeature.PRESET_MODE
170  | ClimateEntityFeature.TURN_OFF
171  | ClimateEntityFeature.TURN_ON
172  )
173  _attr_target_temperature_step = SHTRV_01_TEMPERATURE_SETTINGS["step"]
174  _attr_temperature_unit = UnitOfTemperature.CELSIUS
175  _enable_turn_on_off_backwards_compatibility = False
176 
177  def __init__(
178  self,
179  coordinator: ShellyBlockCoordinator,
180  sensor_block: Block | None,
181  device_block: Block | None,
182  entry: RegistryEntry | None = None,
183  ) -> None:
184  """Initialize climate."""
185  super().__init__(coordinator)
186 
187  self.blockblock: Block | None = sensor_block
188  self.control_result: dict[str, Any] | None = None
189  self.device_blockdevice_block: Block | None = device_block
190  self.last_statelast_state: State | None = None
191  self.last_state_attributeslast_state_attributes: Mapping[str, Any]
192  self._preset_modes_preset_modes: list[str] = []
193  self._last_target_temp_last_target_temp = SHTRV_01_TEMPERATURE_SETTINGS["default"]
194  self._attr_name_attr_name = coordinator.name
195 
196  if self.blockblock is not None and self.device_blockdevice_block is not None:
197  self._unique_id_unique_id = f"{self.coordinator.mac}-{self.block.description}"
198  assert self.blockblock.channel
199  self._preset_modes_preset_modes = [
200  PRESET_NONE,
201  *coordinator.device.settings["thermostats"][int(self.blockblock.channel)][
202  "schedule_profile_names"
203  ],
204  ]
205  elif entry is not None:
206  self._unique_id_unique_id = entry.unique_id
207  self._attr_device_info_attr_device_info = DeviceInfo(
208  connections={(CONNECTION_NETWORK_MAC, coordinator.mac)},
209  )
210 
211  self._channel_channel = cast(int, self._unique_id_unique_id.split("_")[1])
212 
213  @property
214  def extra_restore_state_data(self) -> ShellyClimateExtraStoredData:
215  """Return text specific state data to be restored."""
216  return ShellyClimateExtraStoredData(self._last_target_temp_last_target_temp)
217 
218  @property
219  def unique_id(self) -> str:
220  """Set unique id of entity."""
221  return self._unique_id_unique_id
222 
223  @property
224  def target_temperature(self) -> float | None:
225  """Set target temperature."""
226  if self.blockblock is not None:
227  return cast(float, self.blockblock.targetTemp)
228  # The restored value can be in Fahrenheit so we have to convert it to Celsius
229  # because we use this unit internally in integration.
230  target_temp = self.last_state_attributeslast_state_attributes.get("temperature")
231  if self.hasshass.config.units is US_CUSTOMARY_SYSTEM and target_temp:
232  return TemperatureConverter.convert(
233  cast(float, target_temp),
234  UnitOfTemperature.FAHRENHEIT,
235  UnitOfTemperature.CELSIUS,
236  )
237  return target_temp
238 
239  @property
240  def current_temperature(self) -> float | None:
241  """Return current temperature."""
242  if self.blockblock is not None:
243  return cast(float, self.blockblock.temp)
244  # The restored value can be in Fahrenheit so we have to convert it to Celsius
245  # because we use this unit internally in integration.
246  current_temp = self.last_state_attributeslast_state_attributes.get("current_temperature")
247  if self.hasshass.config.units is US_CUSTOMARY_SYSTEM and current_temp:
248  return TemperatureConverter.convert(
249  cast(float, current_temp),
250  UnitOfTemperature.FAHRENHEIT,
251  UnitOfTemperature.CELSIUS,
252  )
253  return current_temp
254 
255  @property
256  def available(self) -> bool:
257  """Device availability."""
258  if self.device_blockdevice_block is not None:
259  return not cast(bool, self.device_blockdevice_block.valveError)
260  return super().available
261 
262  @property
263  def hvac_mode(self) -> HVACMode:
264  """HVAC current mode."""
265  if self.device_blockdevice_block is None:
266  if self.last_statelast_state and self.last_statelast_state.state in list(HVACMode):
267  return HVACMode(self.last_statelast_state.state)
268  return HVACMode.OFF
269 
270  if self.device_blockdevice_block.mode is None or self._check_is_off_check_is_off():
271  return HVACMode.OFF
272 
273  return HVACMode.HEAT
274 
275  @property
276  def preset_mode(self) -> str | None:
277  """Preset current mode."""
278  if self.device_blockdevice_block is None:
279  return self.last_state_attributeslast_state_attributes.get("preset_mode")
280  if self.device_blockdevice_block.mode is None:
281  return PRESET_NONE
282  return self._preset_modes_preset_modes[cast(int, self.device_blockdevice_block.mode)]
283 
284  @property
285  def hvac_action(self) -> HVACAction:
286  """HVAC current action."""
287  if (
288  self.device_blockdevice_block is None
289  or self.device_blockdevice_block.status is None
290  or self._check_is_off_check_is_off()
291  ):
292  return HVACAction.OFF
293 
294  return HVACAction.HEATING if bool(self.device_blockdevice_block.status) else HVACAction.IDLE
295 
296  @property
297  def preset_modes(self) -> list[str]:
298  """Preset available modes."""
299  return self._preset_modes_preset_modes
300 
301  def _check_is_off(self) -> bool:
302  """Return if valve is off or on."""
303  return bool(
304  self.target_temperaturetarget_temperaturetarget_temperature is None
305  or (self.target_temperaturetarget_temperaturetarget_temperature <= self._attr_min_temp_attr_min_temp)
306  )
307 
308  async def set_state_full_path(self, **kwargs: Any) -> Any:
309  """Set block state (HTTP request)."""
310  LOGGER.debug("Setting state for entity %s, state: %s", self.namename, kwargs)
311  try:
312  return await self.coordinator.device.http_request(
313  "get", f"thermostat/{self._channel}", kwargs
314  )
315  except DeviceConnectionError as err:
316  self.coordinator.last_update_success = False
317  raise HomeAssistantError(
318  f"Setting state for entity {self.name} failed, state: {kwargs}, error:"
319  f" {err!r}"
320  ) from err
321  except InvalidAuthError:
322  await self.coordinator.async_shutdown_device_and_start_reauth()
323 
324  async def async_set_temperature(self, **kwargs: Any) -> None:
325  """Set new target temperature."""
326  if (current_temp := kwargs.get(ATTR_TEMPERATURE)) is None:
327  return
328 
329  # Shelly TRV accepts target_t in Fahrenheit or Celsius, but you must
330  # send the units that the device expects
331  if self.blockblock is not None and self.blockblock.channel is not None:
332  therm = self.coordinator.device.settings["thermostats"][
333  int(self.blockblock.channel)
334  ]
335  LOGGER.debug("Themostat settings: %s", therm)
336  if therm.get("target_t", {}).get("units", "C") == "F":
337  current_temp = TemperatureConverter.convert(
338  cast(float, current_temp),
339  UnitOfTemperature.CELSIUS,
340  UnitOfTemperature.FAHRENHEIT,
341  )
342 
343  await self.set_state_full_pathset_state_full_path(target_t_enabled=1, target_t=f"{current_temp}")
344 
345  async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None:
346  """Set hvac mode."""
347  if hvac_mode == HVACMode.OFF:
348  if isinstance(self.target_temperaturetarget_temperaturetarget_temperature, float):
349  self._last_target_temp_last_target_temp = self.target_temperaturetarget_temperaturetarget_temperature
350  await self.set_state_full_pathset_state_full_path(
351  target_t_enabled=1, target_t=f"{self._attr_min_temp}"
352  )
353  if hvac_mode == HVACMode.HEAT:
354  await self.set_state_full_pathset_state_full_path(
355  target_t_enabled=1, target_t=self._last_target_temp_last_target_temp
356  )
357 
358  async def async_set_preset_mode(self, preset_mode: str) -> None:
359  """Set preset mode."""
360  if not self._preset_modes_preset_modes:
361  return
362 
363  preset_index = self._preset_modes_preset_modes.index(preset_mode)
364 
365  if preset_index == 0:
366  await self.set_state_full_pathset_state_full_path(schedule=0)
367  else:
368  await self.set_state_full_pathset_state_full_path(
369  schedule=1, schedule_profile=f"{preset_index}"
370  )
371 
372  async def async_added_to_hass(self) -> None:
373  """Handle entity which will be added."""
374  LOGGER.info("Restoring entity %s", self.namename)
375 
376  last_state = await self.async_get_last_stateasync_get_last_state()
377  if last_state is not None:
378  self.last_statelast_state = last_state
379  self.last_state_attributeslast_state_attributes = self.last_statelast_state.attributes
380  self._preset_modes_preset_modes = cast(
381  list, self.last_statelast_state.attributes.get("preset_modes")
382  )
383 
384  last_extra_data = await self.async_get_last_extra_dataasync_get_last_extra_data()
385  if last_extra_data is not None:
386  self._last_target_temp_last_target_temp = last_extra_data.as_dict()["last_target_temp"]
387 
388  await super().async_added_to_hass()
389 
390  @callback
391  def _handle_coordinator_update(self) -> None:
392  """Handle device update."""
393  if not self.coordinator.device.initialized:
394  self.async_write_ha_stateasync_write_ha_state()
395  return
396 
397  if self.coordinator.device.status.get("calibrated") is False:
398  ir.async_create_issue(
399  self.hasshass,
400  DOMAIN,
401  NOT_CALIBRATED_ISSUE_ID.format(unique=self.coordinator.mac),
402  is_fixable=False,
403  is_persistent=False,
404  severity=ir.IssueSeverity.ERROR,
405  translation_key="device_not_calibrated",
406  translation_placeholders={
407  "device_name": self.coordinator.name,
408  "ip_address": self.coordinator.device.ip_address,
409  },
410  )
411  else:
412  ir.async_delete_issue(
413  self.hasshass,
414  DOMAIN,
415  NOT_CALIBRATED_ISSUE_ID.format(unique=self.coordinator.mac),
416  )
417 
418  assert self.coordinator.device.blocks
419 
420  for block in self.coordinator.device.blocks:
421  if block.type == "device":
422  self.device_blockdevice_block = block
423  if hasattr(block, "targetTemp"):
424  self.blockblock = block
425 
426  if self.device_blockdevice_block and self.blockblock:
427  LOGGER.debug("Entity %s attached to blocks", self.namename)
428 
429  assert self.blockblock.channel
430 
431  try:
432  self._preset_modes_preset_modes = [
433  PRESET_NONE,
434  *self.coordinator.device.settings["thermostats"][
435  int(self.blockblock.channel)
436  ]["schedule_profile_names"],
437  ]
438  except InvalidAuthError:
439  self.hasshass.async_create_task(
440  self.coordinator.async_shutdown_device_and_start_reauth(),
441  eager_start=True,
442  )
443  else:
444  self.async_write_ha_stateasync_write_ha_state()
445 
446 
448  """Entity that controls a thermostat on RPC based Shelly devices."""
449 
450  _attr_max_temp = RPC_THERMOSTAT_SETTINGS["max"]
451  _attr_min_temp = RPC_THERMOSTAT_SETTINGS["min"]
452  _attr_supported_features = (
453  ClimateEntityFeature.TARGET_TEMPERATURE
454  | ClimateEntityFeature.TURN_OFF
455  | ClimateEntityFeature.TURN_ON
456  )
457  _attr_target_temperature_step = RPC_THERMOSTAT_SETTINGS["step"]
458  _attr_temperature_unit = UnitOfTemperature.CELSIUS
459  _enable_turn_on_off_backwards_compatibility = False
460 
461  def __init__(self, coordinator: ShellyRpcCoordinator, id_: int) -> None:
462  """Initialize."""
463  super().__init__(coordinator, f"thermostat:{id_}")
464  self._id_id = id_
465  self._thermostat_type_thermostat_type = coordinator.device.config[f"thermostat:{id_}"].get(
466  "type", "heating"
467  )
468  if self._thermostat_type_thermostat_type == "cooling":
469  self._attr_hvac_modes_attr_hvac_modes = [HVACMode.OFF, HVACMode.COOL]
470  else:
471  self._attr_hvac_modes_attr_hvac_modes = [HVACMode.OFF, HVACMode.HEAT]
472  self._humidity_key_humidity_key: str | None = None
473  # Check if there is a corresponding humidity key for the thermostat ID
474  if (humidity_key := f"humidity:{id_}") in self.coordinator.device.status:
475  self._humidity_key_humidity_key = humidity_key
476 
477  @property
478  def target_temperature(self) -> float | None:
479  """Set target temperature."""
480  return cast(float, self.statusstatus["target_C"])
481 
482  @property
483  def current_temperature(self) -> float | None:
484  """Return current temperature."""
485  return cast(float, self.statusstatus["current_C"])
486 
487  @property
488  def current_humidity(self) -> float | None:
489  """Return current humidity."""
490  if self._humidity_key_humidity_key is None:
491  return None
492 
493  return cast(float, self.coordinator.device.status[self._humidity_key_humidity_key]["rh"])
494 
495  @property
496  def hvac_mode(self) -> HVACMode:
497  """HVAC current mode."""
498  if not self.statusstatus["enable"]:
499  return HVACMode.OFF
500 
501  return HVACMode.COOL if self._thermostat_type_thermostat_type == "cooling" else HVACMode.HEAT
502 
503  @property
504  def hvac_action(self) -> HVACAction:
505  """HVAC current action."""
506  if not self.statusstatus["output"]:
507  return HVACAction.IDLE
508 
509  return (
510  HVACAction.COOLING
511  if self._thermostat_type_thermostat_type == "cooling"
512  else HVACAction.HEATING
513  )
514 
515  async def async_set_temperature(self, **kwargs: Any) -> None:
516  """Set new target temperature."""
517  if (target_temp := kwargs.get(ATTR_TEMPERATURE)) is None:
518  return
519 
520  await self.call_rpccall_rpc(
521  "Thermostat.SetConfig",
522  {"config": {"id": self._id_id, "target_C": target_temp}},
523  )
524 
525  async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None:
526  """Set hvac mode."""
527  mode = hvac_mode in (HVACMode.COOL, HVACMode.HEAT)
528  await self.call_rpccall_rpc(
529  "Thermostat.SetConfig", {"config": {"id": self._id_id, "enable": mode}}
530  )
None __init__(self, ShellyBlockCoordinator coordinator, Block|None sensor_block, Block|None device_block, RegistryEntry|None entry=None)
Definition: climate.py:183
ShellyClimateExtraStoredData extra_restore_state_data(self)
Definition: climate.py:214
None async_set_temperature(self, **Any kwargs)
Definition: climate.py:515
None __init__(self, ShellyRpcCoordinator coordinator, int id_)
Definition: climate.py:461
None async_set_hvac_mode(self, HVACMode hvac_mode)
Definition: climate.py:525
Any call_rpc(self, str method, Any params)
Definition: entity.py:384
str|UndefinedType|None name(self)
Definition: entity.py:738
ExtraStoredData|None async_get_last_extra_data(self)
web.Response get(self, web.Request request, str config_key)
Definition: view.py:88
None async_restore_climate_entities(HomeAssistant hass, ShellyConfigEntry config_entry, AddEntitiesCallback async_add_entities, ShellyBlockCoordinator coordinator)
Definition: climate.py:101
None async_setup_climate_entities(AddEntitiesCallback async_add_entities, ShellyBlockCoordinator coordinator)
Definition: climate.py:74
None async_setup_entry(HomeAssistant hass, ShellyConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: climate.py:54
None async_setup_rpc_entry(HomeAssistant hass, ShellyConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: climate.py:122
bool is_rpc_thermostat_internal_actuator(dict[str, Any] status)
Definition: utils.py:395
list[int] get_rpc_key_ids(dict[str, Any] keys_dict, str key)
Definition: utils.py:369
int get_device_entry_gen(ConfigEntry entry)
Definition: utils.py:353
None async_remove_shelly_entity(HomeAssistant hass, str domain, str unique_id)
Definition: utils.py:67