Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Support for ANEL PwrCtrl switches."""
2 
3 from __future__ import annotations
4 
5 from datetime import timedelta
6 import logging
7 from typing import Any
8 
9 from anel_pwrctrl import Device, DeviceMaster, Switch
10 import voluptuous as vol
11 
13  PLATFORM_SCHEMA as SWITCH_PLATFORM_SCHEMA,
14  SwitchEntity,
15 )
16 from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
17 from homeassistant.core import HomeAssistant
19 from homeassistant.helpers.entity_platform import AddEntitiesCallback
20 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
21 from homeassistant.util import Throttle
22 
23 _LOGGER = logging.getLogger(__name__)
24 
25 CONF_PORT_RECV = "port_recv"
26 CONF_PORT_SEND = "port_send"
27 
28 MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=5)
29 
30 PLATFORM_SCHEMA = SWITCH_PLATFORM_SCHEMA.extend(
31  {
32  vol.Required(CONF_PORT_RECV): cv.port,
33  vol.Required(CONF_PORT_SEND): cv.port,
34  vol.Required(CONF_USERNAME): cv.string,
35  vol.Required(CONF_PASSWORD): cv.string,
36  vol.Optional(CONF_HOST): cv.string,
37  }
38 )
39 
40 
42  hass: HomeAssistant,
43  config: ConfigType,
44  add_entities: AddEntitiesCallback,
45  discovery_info: DiscoveryInfoType | None = None,
46 ) -> None:
47  """Set up PwrCtrl devices/switches."""
48  host = config.get(CONF_HOST)
49  username = config[CONF_USERNAME]
50  password = config[CONF_PASSWORD]
51  port_recv = config[CONF_PORT_RECV]
52  port_send = config[CONF_PORT_SEND]
53 
54  try:
55  master = DeviceMaster(
56  username=username,
57  password=password,
58  read_port=port_send,
59  write_port=port_recv,
60  )
61  master.query(ip_addr=host)
62  except OSError as ex:
63  _LOGGER.error("Unable to discover PwrCtrl device: %s", str(ex))
64  return
65 
66  devices: list[SwitchEntity] = []
67  for device in master.devices.values():
68  parent_device = PwrCtrlDevice(device)
69  devices.extend(
70  PwrCtrlSwitch(switch, parent_device) for switch in device.switches.values()
71  )
72 
73  add_entities(devices)
74 
75 
77  """Representation of a PwrCtrl switch."""
78 
79  def __init__(self, port: Switch, parent_device: PwrCtrlDevice) -> None:
80  """Initialize the PwrCtrl switch."""
81  self._port_port = port
82  self._parent_device_parent_device = parent_device
83  self._attr_unique_id_attr_unique_id = f"{port.device.host}-{port.get_index()}"
84  self._attr_name_attr_name = port.label
85 
86  def update(self) -> None:
87  """Trigger update for all switches on the parent device."""
88  self._parent_device_parent_device.update()
89  self._attr_is_on_attr_is_on = self._port_port.get_state()
90 
91  def turn_on(self, **kwargs: Any) -> None:
92  """Turn the switch on."""
93  self._port_port.on()
94 
95  def turn_off(self, **kwargs: Any) -> None:
96  """Turn the switch off."""
97  self._port_port.off()
98 
99 
101  """Device representation for per device throttling."""
102 
103  def __init__(self, device: Device) -> None:
104  """Initialize the PwrCtrl device."""
105  self._device_device = device
106 
107  @Throttle(MIN_TIME_BETWEEN_UPDATES)
108  def update(self) -> None:
109  """Update the device and all its switches."""
110  self._device_device.update()
None __init__(self, Switch port, PwrCtrlDevice parent_device)
Definition: switch.py:79
None setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: switch.py:46
None add_entities(AsusWrtRouter router, AddEntitiesCallback async_add_entities, set[str] tracked)
str|float get_state(dict[str, float] data, str key)
Definition: sensor.py:26