Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Switch platform for La Marzocco espresso machines."""
2 
3 from collections.abc import Callable, Coroutine
4 from dataclasses import dataclass
5 from typing import Any
6 
7 from pylamarzocco.const import BoilerType
8 from pylamarzocco.exceptions import RequestNotSuccessful
9 from pylamarzocco.lm_machine import LaMarzoccoMachine
10 from pylamarzocco.models import LaMarzoccoMachineConfig
11 
12 from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
13 from homeassistant.const import EntityCategory
14 from homeassistant.core import HomeAssistant
15 from homeassistant.exceptions import HomeAssistantError
16 from homeassistant.helpers.entity_platform import AddEntitiesCallback
17 
18 from .const import DOMAIN
19 from .coordinator import LaMarzoccoConfigEntry, LaMarzoccoUpdateCoordinator
20 from .entity import LaMarzoccoBaseEntity, LaMarzoccoEntity, LaMarzoccoEntityDescription
21 
22 PARALLEL_UPDATES = 1
23 
24 
25 @dataclass(frozen=True, kw_only=True)
27  LaMarzoccoEntityDescription,
28  SwitchEntityDescription,
29 ):
30  """Description of a La Marzocco Switch."""
31 
32  control_fn: Callable[[LaMarzoccoMachine, bool], Coroutine[Any, Any, bool]]
33  is_on_fn: Callable[[LaMarzoccoMachineConfig], bool]
34 
35 
36 ENTITIES: tuple[LaMarzoccoSwitchEntityDescription, ...] = (
38  key="main",
39  translation_key="main",
40  name=None,
41  control_fn=lambda machine, state: machine.set_power(state),
42  is_on_fn=lambda config: config.turned_on,
43  ),
45  key="steam_boiler_enable",
46  translation_key="steam_boiler",
47  control_fn=lambda machine, state: machine.set_steam(state),
48  is_on_fn=lambda config: config.boilers[BoilerType.STEAM].enabled,
49  ),
51  key="smart_standby_enabled",
52  translation_key="smart_standby_enabled",
53  entity_category=EntityCategory.CONFIG,
54  control_fn=lambda machine, state: machine.set_smart_standby(
55  enabled=state,
56  mode=machine.config.smart_standby.mode,
57  minutes=machine.config.smart_standby.minutes,
58  ),
59  is_on_fn=lambda config: config.smart_standby.enabled,
60  ),
61 )
62 
63 
65  hass: HomeAssistant,
66  entry: LaMarzoccoConfigEntry,
67  async_add_entities: AddEntitiesCallback,
68 ) -> None:
69  """Set up switch entities and services."""
70 
71  coordinator = entry.runtime_data
72 
73  entities: list[SwitchEntity] = []
74  entities.extend(
75  LaMarzoccoSwitchEntity(coordinator, description)
76  for description in ENTITIES
77  if description.supported_fn(coordinator)
78  )
79 
80  entities.extend(
81  LaMarzoccoAutoOnOffSwitchEntity(coordinator, wake_up_sleep_entry_id)
82  for wake_up_sleep_entry_id in coordinator.device.config.wake_up_sleep_entries
83  )
84 
85  async_add_entities(entities)
86 
87 
89  """Switches representing espresso machine power, prebrew, and auto on/off."""
90 
91  entity_description: LaMarzoccoSwitchEntityDescription
92 
93  async def async_turn_on(self, **kwargs: Any) -> None:
94  """Turn device on."""
95  try:
96  await self.entity_descriptionentity_description.control_fn(self.coordinator.device, True)
97  except RequestNotSuccessful as exc:
98  raise HomeAssistantError(
99  translation_domain=DOMAIN,
100  translation_key="switch_on_error",
101  translation_placeholders={"key": self.entity_descriptionentity_description.key},
102  ) from exc
103  self.async_write_ha_stateasync_write_ha_state()
104 
105  async def async_turn_off(self, **kwargs: Any) -> None:
106  """Turn device off."""
107  try:
108  await self.entity_descriptionentity_description.control_fn(self.coordinator.device, False)
109  except RequestNotSuccessful as exc:
110  raise HomeAssistantError(
111  translation_domain=DOMAIN,
112  translation_key="switch_off_error",
113  translation_placeholders={"key": self.entity_descriptionentity_description.key},
114  ) from exc
115  self.async_write_ha_stateasync_write_ha_state()
116 
117  @property
118  def is_on(self) -> bool:
119  """Return true if device is on."""
120  return self.entity_descriptionentity_description.is_on_fn(self.coordinator.device.config)
121 
122 
124  """Switch representing espresso machine auto on/off."""
125 
126  coordinator: LaMarzoccoUpdateCoordinator
127  _attr_translation_key = "auto_on_off"
128 
129  def __init__(
130  self,
131  coordinator: LaMarzoccoUpdateCoordinator,
132  identifier: str,
133  ) -> None:
134  """Initialize the switch."""
135  super().__init__(coordinator, f"auto_on_off_{identifier}")
136  self._identifier_identifier = identifier
137  self._attr_translation_placeholders_attr_translation_placeholders = {"id": identifier}
138  self.entity_categoryentity_categoryentity_category = EntityCategory.CONFIG
139 
140  async def _async_enable(self, state: bool) -> None:
141  """Enable or disable the auto on/off schedule."""
142  wake_up_sleep_entry = self.coordinator.device.config.wake_up_sleep_entries[
143  self._identifier_identifier
144  ]
145  wake_up_sleep_entry.enabled = state
146  try:
147  await self.coordinator.device.set_wake_up_sleep(wake_up_sleep_entry)
148  except RequestNotSuccessful as exc:
149  raise HomeAssistantError(
150  translation_domain=DOMAIN,
151  translation_key="auto_on_off_error",
152  translation_placeholders={"id": self._identifier_identifier, "state": str(state)},
153  ) from exc
154  self.async_write_ha_stateasync_write_ha_state()
155 
156  async def async_turn_on(self, **kwargs: Any) -> None:
157  """Turn switch on."""
158  await self._async_enable_async_enable(True)
159 
160  async def async_turn_off(self, **kwargs: Any) -> None:
161  """Turn switch off."""
162  await self._async_enable_async_enable(False)
163 
164  @property
165  def is_on(self) -> bool:
166  """Return true if switch is on."""
167  return self.coordinator.device.config.wake_up_sleep_entries[
168  self._identifier_identifier
169  ].enabled
None __init__(self, LaMarzoccoUpdateCoordinator coordinator, str identifier)
Definition: switch.py:133
EntityCategory|None entity_category(self)
Definition: entity.py:895
None async_turn_off(self, **Any kwargs)
Definition: entity.py:1709
None async_setup_entry(HomeAssistant hass, LaMarzoccoConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: switch.py:68