Home Assistant Unofficial Reference 2024.12.1
button.py
Go to the documentation of this file.
1 """Support for button entity in wake on lan."""
2 
3 from __future__ import annotations
4 
5 from functools import partial
6 import logging
7 from typing import Any
8 
9 import wakeonlan
10 
11 from homeassistant.components.button import ButtonEntity
12 from homeassistant.config_entries import ConfigEntry
13 from homeassistant.const import CONF_BROADCAST_ADDRESS, CONF_BROADCAST_PORT, CONF_MAC
14 from homeassistant.core import HomeAssistant
15 from homeassistant.helpers import device_registry as dr
16 from homeassistant.helpers.entity_platform import AddEntitiesCallback
17 
18 _LOGGER = logging.getLogger(__name__)
19 
20 
22  hass: HomeAssistant,
23  entry: ConfigEntry,
24  async_add_entities: AddEntitiesCallback,
25 ) -> None:
26  """Set up the Wake on LAN button entry."""
27  broadcast_address: str | None = entry.options.get(CONF_BROADCAST_ADDRESS)
28  broadcast_port: int | None = entry.options.get(CONF_BROADCAST_PORT)
29  mac_address: str = entry.options[CONF_MAC]
30  name: str = entry.title
31 
33  [
34  WolButton(
35  name,
36  mac_address,
37  broadcast_address,
38  broadcast_port,
39  )
40  ]
41  )
42 
43 
45  """Representation of a wake on lan button."""
46 
47  _attr_name = None
48 
49  def __init__(
50  self,
51  name: str,
52  mac_address: str,
53  broadcast_address: str | None,
54  broadcast_port: int | None,
55  ) -> None:
56  """Initialize the WOL button."""
57  self._mac_address_mac_address = mac_address
58  self._broadcast_address_broadcast_address = broadcast_address
59  self._broadcast_port_broadcast_port = broadcast_port
60  self._attr_unique_id_attr_unique_id = dr.format_mac(mac_address)
61  self._attr_device_info_attr_device_info = dr.DeviceInfo(
62  connections={(dr.CONNECTION_NETWORK_MAC, self._attr_unique_id_attr_unique_id)},
63  default_name=name,
64  )
65 
66  async def async_press(self) -> None:
67  """Press the button."""
68  service_kwargs: dict[str, Any] = {}
69  if self._broadcast_address_broadcast_address is not None:
70  service_kwargs["ip_address"] = self._broadcast_address_broadcast_address
71  if self._broadcast_port_broadcast_port is not None:
72  service_kwargs["port"] = self._broadcast_port_broadcast_port
73 
74  _LOGGER.debug(
75  "Send magic packet to mac %s (broadcast: %s, port: %s)",
76  self._mac_address_mac_address,
77  self._broadcast_address_broadcast_address,
78  self._broadcast_port_broadcast_port,
79  )
80 
81  await self.hasshass.async_add_executor_job(
82  partial(wakeonlan.send_magic_packet, self._mac_address_mac_address, **service_kwargs)
83  )
None __init__(self, str name, str mac_address, str|None broadcast_address, int|None broadcast_port)
Definition: button.py:55
None async_setup_entry(HomeAssistant hass, ConfigEntry entry, AddEntitiesCallback async_add_entities)
Definition: button.py:25