Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Support for Ridwell buttons."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
7 from aioridwell.errors import RidwellError
8 from aioridwell.model import EventState, RidwellAccount
9 
10 from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
11 from homeassistant.config_entries import ConfigEntry
12 from homeassistant.core import HomeAssistant
13 from homeassistant.exceptions import HomeAssistantError
14 from homeassistant.helpers.entity_platform import AddEntitiesCallback
15 
16 from .const import DOMAIN
17 from .coordinator import RidwellDataUpdateCoordinator
18 from .entity import RidwellEntity
19 
20 SWITCH_DESCRIPTION = SwitchEntityDescription(
21  key="opt_in",
22  translation_key="opt_in",
23 )
24 
25 
27  hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
28 ) -> None:
29  """Set up Ridwell sensors based on a config entry."""
30  coordinator: RidwellDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
31 
33  RidwellSwitch(coordinator, account, SWITCH_DESCRIPTION)
34  for account in coordinator.accounts.values()
35  )
36 
37 
39  """Define a Ridwell switch."""
40 
41  def __init__(
42  self,
43  coordinator: RidwellDataUpdateCoordinator,
44  account: RidwellAccount,
45  description: SwitchEntityDescription,
46  ) -> None:
47  """Initialize."""
48  super().__init__(coordinator, account)
49 
50  self._attr_unique_id_attr_unique_id = f"{account.account_id}_{description.key}"
51  self.entity_descriptionentity_description = description
52 
53  @property
54  def is_on(self) -> bool:
55  """Return True if entity is on."""
56  return self.next_pickup_eventnext_pickup_event.state == EventState.SCHEDULED
57 
58  async def async_turn_off(self, **kwargs: Any) -> None:
59  """Turn the switch off."""
60  try:
61  await self.next_pickup_eventnext_pickup_event.async_opt_out()
62  except RidwellError as err:
63  raise HomeAssistantError(f"Error while opting out: {err}") from err
64 
65  await self.coordinator.async_request_refresh()
66 
67  async def async_turn_on(self, **kwargs: Any) -> None:
68  """Turn the switch on."""
69  try:
70  await self.next_pickup_eventnext_pickup_event.async_opt_in()
71  except RidwellError as err:
72  raise HomeAssistantError(f"Error while opting in: {err}") from err
73 
74  await self.coordinator.async_request_refresh()
None __init__(self, RidwellDataUpdateCoordinator coordinator, RidwellAccount account, SwitchEntityDescription description)
Definition: switch.py:46
None async_setup_entry(HomeAssistant hass, ConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: switch.py:28