Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Switch implementation for Energenie-Power-Sockets Platform."""
2 
3 from typing import Any
4 
5 from pyegps import __version__ as PYEGPS_VERSION
6 from pyegps.exceptions import EgpsException
7 from pyegps.powerstrip import PowerStrip
8 
9 from homeassistant.components.switch import SwitchDeviceClass, SwitchEntity
10 from homeassistant.config_entries import ConfigEntry
11 from homeassistant.core import HomeAssistant
12 from homeassistant.exceptions import HomeAssistantError
13 from homeassistant.helpers.device_registry import DeviceInfo
14 from homeassistant.helpers.entity_platform import AddEntitiesCallback
15 
16 from .const import DOMAIN
17 
18 
20  hass: HomeAssistant,
21  config_entry: ConfigEntry,
22  async_add_entities: AddEntitiesCallback,
23 ) -> None:
24  """Add EGPS sockets for passed config_entry in HA."""
25  powerstrip: PowerStrip = hass.data[DOMAIN][config_entry.entry_id]
26 
28  (
29  EGPowerStripSocket(powerstrip, socket)
30  for socket in range(powerstrip.numberOfSockets)
31  ),
32  update_before_add=True,
33  )
34 
35 
37  """Represents a socket of an Energenie-Socket-Strip."""
38 
39  _attr_device_class = SwitchDeviceClass.OUTLET
40  _attr_has_entity_name = True
41  _attr_translation_key = "socket"
42 
43  def __init__(self, dev: PowerStrip, socket: int) -> None:
44  """Initiate a new socket."""
45  self._dev_dev = dev
46  self._socket_socket = socket
47  self._attr_translation_placeholders_attr_translation_placeholders = {"socket_id": str(socket)}
48 
49  self._attr_unique_id_attr_unique_id = f"{dev.device_id}_{socket}"
50  self._attr_device_info_attr_device_info = DeviceInfo(
51  identifiers={(DOMAIN, dev.device_id)},
52  name=dev.name,
53  manufacturer=dev.manufacturer,
54  model=dev.name,
55  sw_version=PYEGPS_VERSION,
56  )
57 
58  def turn_on(self, **kwargs: Any) -> None:
59  """Switch the socket on."""
60  try:
61  self._dev_dev.switch_on(self._socket_socket)
62  except EgpsException as err:
63  raise HomeAssistantError(f"Couldn't access USB device: {err}") from err
64 
65  def turn_off(self, **kwargs: Any) -> None:
66  """Switch the socket off."""
67  try:
68  self._dev_dev.switch_off(self._socket_socket)
69  except EgpsException as err:
70  raise HomeAssistantError(f"Couldn't access USB device: {err}") from err
71 
72  def update(self) -> None:
73  """Read the current state from the device."""
74  try:
75  self._attr_is_on_attr_is_on = self._dev_dev.get_status(self._socket_socket)
76  except EgpsException as err:
77  raise HomeAssistantError(f"Couldn't access USB device: {err}") from err
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: switch.py:23
def get_status(hass, host, port)
Definition: panel.py:387