Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Control switches."""
2 
3 import asyncio
4 from datetime import timedelta
5 import logging
6 from typing import Any
7 
8 from ProgettiHWSW.relay import Relay
9 
10 from homeassistant.components.switch import SwitchEntity
11 from homeassistant.config_entries import ConfigEntry
12 from homeassistant.core import HomeAssistant
13 from homeassistant.helpers.entity_platform import AddEntitiesCallback
15  CoordinatorEntity,
16  DataUpdateCoordinator,
17 )
18 
19 from . import setup_switch
20 from .const import DEFAULT_POLLING_INTERVAL_SEC, DOMAIN
21 
22 _LOGGER = logging.getLogger(DOMAIN)
23 
24 
26  hass: HomeAssistant,
27  config_entry: ConfigEntry,
28  async_add_entities: AddEntitiesCallback,
29 ) -> None:
30  """Set up the switches from a config entry."""
31  board_api = hass.data[DOMAIN][config_entry.entry_id]
32  relay_count = config_entry.data["relay_count"]
33 
34  async def async_update_data():
35  """Fetch data from API endpoint of board."""
36  async with asyncio.timeout(5):
37  return await board_api.get_switches()
38 
39  coordinator = DataUpdateCoordinator(
40  hass,
41  _LOGGER,
42  name="switch",
43  update_method=async_update_data,
44  update_interval=timedelta(seconds=DEFAULT_POLLING_INTERVAL_SEC),
45  )
46  await coordinator.async_refresh()
47 
50  coordinator,
51  f"Relay #{i}",
52  setup_switch(board_api, i, config_entry.data[f"relay_{i!s}"]),
53  )
54  for i in range(1, int(relay_count) + 1)
55  )
56 
57 
59  """Represent a switch entity."""
60 
61  def __init__(self, coordinator, name, switch: Relay) -> None:
62  """Initialize the values."""
63  super().__init__(coordinator)
64  self._switch_switch = switch
65  self._attr_name_attr_name = name
66 
67  async def async_turn_on(self, **kwargs: Any) -> None:
68  """Turn the switch on."""
69  await self._switch_switch.control(True)
70  await self.coordinator.async_request_refresh()
71 
72  async def async_turn_off(self, **kwargs: Any) -> None:
73  """Turn the switch off."""
74  await self._switch_switch.control(False)
75  await self.coordinator.async_request_refresh()
76 
77  async def async_toggle(self, **kwargs: Any) -> None:
78  """Toggle the state of switch."""
79  await self._switch_switch.toggle()
80  await self.coordinator.async_request_refresh()
81 
82  @property
83  def is_on(self):
84  """Get switch state."""
85  return self.coordinator.data[self._switch_switch.id]
None __init__(self, coordinator, name, Relay switch)
Definition: switch.py:61
None toggle(self, **Any kwargs)
Definition: entity.py:1714
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: switch.py:29
Relay setup_switch(ProgettiHWSWAPI api, int switch_number, str mode)
Definition: __init__.py:45