Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Support for IKEA Tradfri switches."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable
6 from typing import Any, cast
7 
8 from pytradfri.command import Command
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
14 
15 from .const import CONF_GATEWAY_ID, COORDINATOR, COORDINATOR_LIST, DOMAIN, KEY_API
16 from .coordinator import TradfriDeviceDataUpdateCoordinator
17 from .entity import TradfriBaseEntity
18 
19 
21  hass: HomeAssistant,
22  config_entry: ConfigEntry,
23  async_add_entities: AddEntitiesCallback,
24 ) -> None:
25  """Load Tradfri switches based on a config entry."""
26  gateway_id = config_entry.data[CONF_GATEWAY_ID]
27  coordinator_data = hass.data[DOMAIN][config_entry.entry_id][COORDINATOR]
28  api = coordinator_data[KEY_API]
29 
32  device_coordinator,
33  api,
34  gateway_id,
35  )
36  for device_coordinator in coordinator_data[COORDINATOR_LIST]
37  if device_coordinator.device.has_socket_control
38  )
39 
40 
42  """The platform class required by Home Assistant."""
43 
44  _attr_name = None
45 
46  def __init__(
47  self,
48  device_coordinator: TradfriDeviceDataUpdateCoordinator,
49  api: Callable[[Command | list[Command]], Any],
50  gateway_id: str,
51  ) -> None:
52  """Initialize a switch."""
53  super().__init__(
54  device_coordinator=device_coordinator,
55  api=api,
56  gateway_id=gateway_id,
57  )
58 
59  self._device_control_device_control = self._device.socket_control
60  self._device_data_device_data = self._device_control_device_control.sockets[0]
61 
62  def _refresh(self) -> None:
63  """Refresh the device."""
64  self._device_data_device_data = self.coordinator.data.socket_control.sockets[0]
65 
66  @property
67  def is_on(self) -> bool:
68  """Return true if switch is on."""
69  if not self._device_data_device_data:
70  return False
71  return cast(bool, self._device_data_device_data.state)
72 
73  async def async_turn_off(self, **kwargs: Any) -> None:
74  """Instruct the switch to turn off."""
75  if not self._device_control_device_control:
76  return
77  await self._api_api(self._device_control_device_control.set_state(False))
78 
79  async def async_turn_on(self, **kwargs: Any) -> None:
80  """Instruct the switch to turn on."""
81  if not self._device_control_device_control:
82  return
83  await self._api_api(self._device_control_device_control.set_state(True))
None __init__(self, TradfriDeviceDataUpdateCoordinator device_coordinator, Callable[[Command|list[Command]], Any] api, str gateway_id)
Definition: switch.py:51
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: switch.py:24