Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Allows to configuration ecoal (esterownik.pl) pumps as switches."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
7 from homeassistant.components.switch import SwitchEntity
8 from homeassistant.core import HomeAssistant
9 from homeassistant.helpers.entity_platform import AddEntitiesCallback
10 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
11 
12 from . import AVAILABLE_PUMPS, DATA_ECOAL_BOILER
13 
14 
16  hass: HomeAssistant,
17  config: ConfigType,
18  add_entities: AddEntitiesCallback,
19  discovery_info: DiscoveryInfoType | None = None,
20 ) -> None:
21  """Set up switches based on ecoal interface."""
22  if discovery_info is None:
23  return
24  ecoal_contr = hass.data[DATA_ECOAL_BOILER]
25  switches = []
26  for pump_id in discovery_info:
27  name = AVAILABLE_PUMPS[pump_id]
28  switches.append(EcoalSwitch(ecoal_contr, name, pump_id))
29  add_entities(switches, True)
30 
31 
33  """Representation of Ecoal switch."""
34 
35  def __init__(self, ecoal_contr, name, state_attr):
36  """Initialize switch.
37 
38  Sets HA switch to state as read from controller.
39  """
40  self._ecoal_contr_ecoal_contr = ecoal_contr
41  self._attr_name_attr_name = name
42  self._state_attr_state_attr = state_attr
43  # Ecoalcotroller holds convention that same postfix is used
44  # to set attribute
45  # set_<attr>()
46  # as attribute name in status instance:
47  # status.<attr>
48  self._contr_set_fun_contr_set_fun = getattr(self._ecoal_contr_ecoal_contr, f"set_{state_attr}")
49 
50  def update(self) -> None:
51  """Fetch new state data for the sensor.
52 
53  This is the only method that should fetch new data for Home Assistant.
54  """
55  status = self._ecoal_contr_ecoal_contr.get_cached_status()
56  self._attr_is_on_attr_is_on = getattr(status, self._state_attr_state_attr)
57 
59  """Invalidate ecoal interface cache.
60 
61  Forces that next read from ecaol interface to not use cache.
62  """
63  self._ecoal_contr_ecoal_contr.status = None
64 
65  def turn_on(self, **kwargs: Any) -> None:
66  """Turn the device on."""
67  self._contr_set_fun_contr_set_fun(1)
68  self.invalidate_ecoal_cacheinvalidate_ecoal_cache()
69 
70  def turn_off(self, **kwargs: Any) -> None:
71  """Turn the device off."""
72  self._contr_set_fun_contr_set_fun(0)
73  self.invalidate_ecoal_cacheinvalidate_ecoal_cache()
def __init__(self, ecoal_contr, name, state_attr)
Definition: switch.py:35
None add_entities(AsusWrtRouter router, AddEntitiesCallback async_add_entities, set[str] tracked)
None setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: switch.py:20