Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Support for myStrom switches/plugs."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 from pymystrom.exceptions import MyStromConnectionError
9 
10 from homeassistant.components.switch import SwitchEntity
11 from homeassistant.config_entries import ConfigEntry
12 from homeassistant.core import HomeAssistant
13 from homeassistant.helpers.device_registry import DeviceInfo, format_mac
14 from homeassistant.helpers.entity_platform import AddEntitiesCallback
15 
16 from .const import DOMAIN, MANUFACTURER
17 
18 DEFAULT_NAME = "myStrom Switch"
19 
20 _LOGGER = logging.getLogger(__name__)
21 
22 
24  hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
25 ) -> None:
26  """Set up the myStrom entities."""
27  device = hass.data[DOMAIN][entry.entry_id].device
28  async_add_entities([MyStromSwitch(device, entry.title)])
29 
30 
32  """Representation of a myStrom switch/plug."""
33 
34  _attr_has_entity_name = True
35  _attr_name = None
36 
37  def __init__(self, plug, name):
38  """Initialize the myStrom switch/plug."""
39  self.plugplug = plug
40  self._attr_unique_id_attr_unique_id = self.plugplug.mac
41  self._attr_device_info_attr_device_info = DeviceInfo(
42  identifiers={(DOMAIN, self.plugplug.mac)},
43  name=name,
44  manufacturer=MANUFACTURER,
45  sw_version=self.plugplug.firmware,
46  connections={("mac", format_mac(self.plugplug.mac))},
47  configuration_url=self.plugplug.uri,
48  )
49 
50  async def async_turn_on(self, **kwargs: Any) -> None:
51  """Turn the switch on."""
52  try:
53  await self.plugplug.turn_on()
54  except MyStromConnectionError:
55  _LOGGER.error("No route to myStrom plug")
56 
57  async def async_turn_off(self, **kwargs: Any) -> None:
58  """Turn the switch off."""
59  try:
60  await self.plugplug.turn_off()
61  except MyStromConnectionError:
62  _LOGGER.error("No route to myStrom plug")
63 
64  async def async_update(self) -> None:
65  """Get the latest data from the device and update the data."""
66  try:
67  await self.plugplug.get_state()
68  self._attr_is_on_attr_is_on = self.plugplug.relay
69  self._attr_available_attr_available = True
70  except MyStromConnectionError:
71  if self.availableavailable:
72  self._attr_available_attr_available = False
73  _LOGGER.error("No route to myStrom plug")
None turn_off(self, **Any kwargs)
Definition: entity.py:1705
None turn_on(self, **Any kwargs)
Definition: entity.py:1697
str|float get_state(dict[str, float] data, str key)
Definition: sensor.py:26
None async_setup_entry(HomeAssistant hass, ConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: switch.py:25