Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Support for HomeMatic switches."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
7 from homeassistant.components.switch import SwitchEntity
8 from homeassistant.core import HomeAssistant
9 from homeassistant.helpers.entity_platform import AddEntitiesCallback
10 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
11 
12 from .const import ATTR_DISCOVER_DEVICES
13 from .entity import HMDevice
14 
15 
17  hass: HomeAssistant,
18  config: ConfigType,
19  add_entities: AddEntitiesCallback,
20  discovery_info: DiscoveryInfoType | None = None,
21 ) -> None:
22  """Set up the HomeMatic switch platform."""
23  if discovery_info is None:
24  return
25 
26  devices = []
27  for conf in discovery_info[ATTR_DISCOVER_DEVICES]:
28  new_device = HMSwitch(conf)
29  devices.append(new_device)
30 
31  add_entities(devices, True)
32 
33 
35  """Representation of a HomeMatic switch."""
36 
37  @property
38  def is_on(self):
39  """Return True if switch is on."""
40  try:
41  return self._hm_get_state_hm_get_state() > 0
42  except TypeError:
43  return False
44 
45  @property
46  def today_energy_kwh(self):
47  """Return the current power usage in kWh."""
48  if "ENERGY_COUNTER" in self._data:
49  try:
50  return self._data["ENERGY_COUNTER"] / 1000
51  except ZeroDivisionError:
52  return 0
53 
54  return None
55 
56  def turn_on(self, **kwargs: Any) -> None:
57  """Turn the switch on."""
58  self._hmdevice_hmdevice.on(self._channel_channel)
59 
60  def turn_off(self, **kwargs: Any) -> None:
61  """Turn the switch off."""
62  self._hmdevice_hmdevice.off(self._channel_channel)
63 
64  def _init_data_struct(self):
65  """Generate the data dictionary (self._data) from metadata."""
66  self._state_state_state = "STATE"
67  self._data.update({self._state_state_state: None})
68 
69  # Need sensor values for SwitchPowermeter
70  for node in self._hmdevice_hmdevice.SENSORNODE:
71  self._data.update({node: None})
None add_entities(AsusWrtRouter router, AddEntitiesCallback async_add_entities, set[str] tracked)
None setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: switch.py:21