Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Switch for Refoss."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
7 from refoss_ha.controller.toggle import ToggleXMix
8 
9 from homeassistant.components.switch import SwitchEntity
10 from homeassistant.config_entries import ConfigEntry
11 from homeassistant.core import HomeAssistant, callback
12 from homeassistant.helpers.dispatcher import async_dispatcher_connect
13 from homeassistant.helpers.entity_platform import AddEntitiesCallback
14 
15 from .bridge import RefossDataUpdateCoordinator
16 from .const import COORDINATORS, DISPATCH_DEVICE_DISCOVERED, DOMAIN
17 from .entity import RefossEntity
18 
19 
21  hass: HomeAssistant,
22  config_entry: ConfigEntry,
23  async_add_entities: AddEntitiesCallback,
24 ) -> None:
25  """Set up the Refoss device from a config entry."""
26 
27  @callback
28  def init_device(coordinator):
29  """Register the device."""
30  device = coordinator.device
31  if not isinstance(device, ToggleXMix):
32  return
33 
34  new_entities = []
35  for channel in device.channels:
36  entity = RefossSwitch(coordinator=coordinator, channel=channel)
37  new_entities.append(entity)
38 
39  async_add_entities(new_entities)
40 
41  for coordinator in hass.data[DOMAIN][COORDINATORS]:
42  init_device(coordinator)
43 
44  config_entry.async_on_unload(
45  async_dispatcher_connect(hass, DISPATCH_DEVICE_DISCOVERED, init_device)
46  )
47 
48 
50  """Refoss Switch Device."""
51 
52  def __init__(
53  self,
54  coordinator: RefossDataUpdateCoordinator,
55  channel: int,
56  ) -> None:
57  """Init Refoss switch."""
58  super().__init__(coordinator, channel)
59  self._attr_name_attr_name = str(channel)
60 
61  @property
62  def is_on(self) -> bool | None:
63  """Return true if switch is on."""
64  return self.coordinator.device.is_on(channel=self.channel_idchannel_id)
65 
66  async def async_turn_on(self, **kwargs: Any) -> None:
67  """Turn the switch on."""
68  await self.coordinator.device.async_turn_on(self.channel_idchannel_id)
69  self.async_write_ha_stateasync_write_ha_state()
70 
71  async def async_turn_off(self, **kwargs: Any) -> None:
72  """Turn the switch off."""
73  await self.coordinator.device.async_turn_off(self.channel_idchannel_id)
74  self.async_write_ha_stateasync_write_ha_state()
75 
76  async def async_toggle(self, **kwargs: Any) -> None:
77  """Toggle the switch."""
78  await self.coordinator.device.async_toggle(channel=self.channel_idchannel_id)
79  self.async_write_ha_stateasync_write_ha_state()
None __init__(self, RefossDataUpdateCoordinator coordinator, int channel)
Definition: switch.py:56
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: switch.py:24
Callable[[], None] async_dispatcher_connect(HomeAssistant hass, str signal, Callable[..., Any] target)
Definition: dispatcher.py:103