Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Support for deCONZ switches."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
7 from pydeconz.models.event import EventType
8 from pydeconz.models.light.light import Light
9 
10 from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN, SwitchEntity
11 from homeassistant.config_entries import ConfigEntry
12 from homeassistant.core import HomeAssistant, callback
13 from homeassistant.helpers.entity_platform import AddEntitiesCallback
14 
15 from .const import POWER_PLUGS
16 from .entity import DeconzDevice
17 from .hub import DeconzHub
18 
19 
21  hass: HomeAssistant,
22  config_entry: ConfigEntry,
23  async_add_entities: AddEntitiesCallback,
24 ) -> None:
25  """Set up switches for deCONZ component.
26 
27  Switches are based on the same device class as lights in deCONZ.
28  """
29  hub = DeconzHub.get_hub(hass, config_entry)
30  hub.entities[SWITCH_DOMAIN] = set()
31 
32  @callback
33  def async_add_switch(_: EventType, switch_id: str) -> None:
34  """Add switch from deCONZ."""
35  switch = hub.api.lights.lights[switch_id]
36  if switch.type not in POWER_PLUGS:
37  return
38  async_add_entities([DeconzPowerPlug(switch, hub)])
39 
40  hub.register_platform_add_device_callback(
41  async_add_switch,
42  hub.api.lights.lights,
43  )
44 
45 
46 class DeconzPowerPlug(DeconzDevice[Light], SwitchEntity):
47  """Representation of a deCONZ power plug."""
48 
49  TYPE = SWITCH_DOMAIN
50 
51  @property
52  def is_on(self) -> bool:
53  """Return true if switch is on."""
54  return self._device.on
55 
56  async def async_turn_on(self, **kwargs: Any) -> None:
57  """Turn on switch."""
58  await self.hub.api.lights.lights.set_state(
59  id=self._device.resource_id,
60  on=True,
61  )
62 
63  async def async_turn_off(self, **kwargs: Any) -> None:
64  """Turn off switch."""
65  await self.hub.api.lights.lights.set_state(
66  id=self._device.resource_id,
67  on=False,
68  )
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: switch.py:24