Home Assistant Unofficial Reference 2024.12.1
button.py
Go to the documentation of this file.
1 """Support for buttons which integrates with other components."""
2 
3 from __future__ import annotations
4 
5 import logging
6 from typing import Any
7 
8 import voluptuous as vol
9 
10 from homeassistant.components.button import DEVICE_CLASSES_SCHEMA, ButtonEntity
11 from homeassistant.config_entries import ConfigEntry
12 from homeassistant.const import (
13  CONF_DEVICE_CLASS,
14  CONF_DEVICE_ID,
15  CONF_NAME,
16  CONF_UNIQUE_ID,
17 )
18 from homeassistant.core import HomeAssistant
19 from homeassistant.exceptions import PlatformNotReady
20 from homeassistant.helpers import config_validation as cv, selector
21 from homeassistant.helpers.device import async_device_info_to_link_from_device_id
22 from homeassistant.helpers.entity_platform import AddEntitiesCallback
23 from homeassistant.helpers.script import Script
24 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
25 
26 from .const import CONF_PRESS, DOMAIN
27 from .template_entity import (
28  TEMPLATE_ENTITY_AVAILABILITY_SCHEMA,
29  TEMPLATE_ENTITY_ICON_SCHEMA,
30  TemplateEntity,
31 )
32 
33 _LOGGER = logging.getLogger(__name__)
34 
35 DEFAULT_NAME = "Template Button"
36 DEFAULT_OPTIMISTIC = False
37 
38 BUTTON_SCHEMA = (
39  vol.Schema(
40  {
41  vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.template,
42  vol.Required(CONF_PRESS): cv.SCRIPT_SCHEMA,
43  vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
44  vol.Optional(CONF_UNIQUE_ID): cv.string,
45  }
46  )
47  .extend(TEMPLATE_ENTITY_AVAILABILITY_SCHEMA.schema)
48  .extend(TEMPLATE_ENTITY_ICON_SCHEMA.schema)
49 )
50 
51 CONFIG_BUTTON_SCHEMA = vol.Schema(
52  {
53  vol.Optional(CONF_NAME): cv.template,
54  vol.Optional(CONF_PRESS): cv.SCRIPT_SCHEMA,
55  vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
56  vol.Optional(CONF_DEVICE_ID): selector.DeviceSelector(),
57  }
58 )
59 
60 
62  hass: HomeAssistant, definitions: list[dict[str, Any]], unique_id_prefix: str | None
63 ) -> list[TemplateButtonEntity]:
64  """Create the Template button."""
65  entities = []
66  for definition in definitions:
67  unique_id = definition.get(CONF_UNIQUE_ID)
68  if unique_id and unique_id_prefix:
69  unique_id = f"{unique_id_prefix}-{unique_id}"
70  entities.append(TemplateButtonEntity(hass, definition, unique_id))
71  return entities
72 
73 
75  hass: HomeAssistant,
76  config: ConfigType,
77  async_add_entities: AddEntitiesCallback,
78  discovery_info: DiscoveryInfoType | None = None,
79 ) -> None:
80  """Set up the template button."""
81  if not discovery_info or "coordinator" in discovery_info:
82  raise PlatformNotReady(
83  "The template button platform doesn't support trigger entities"
84  )
85 
88  hass, discovery_info["entities"], discovery_info["unique_id"]
89  )
90  )
91 
92 
94  hass: HomeAssistant,
95  config_entry: ConfigEntry,
96  async_add_entities: AddEntitiesCallback,
97 ) -> None:
98  """Initialize config entry."""
99  _options = dict(config_entry.options)
100  _options.pop("template_type")
101  validated_config = CONFIG_BUTTON_SCHEMA(_options)
103  [TemplateButtonEntity(hass, validated_config, config_entry.entry_id)]
104  )
105 
106 
108  """Representation of a template button."""
109 
110  _attr_should_poll = False
111 
112  def __init__(
113  self,
114  hass: HomeAssistant,
115  config,
116  unique_id: str | None,
117  ) -> None:
118  """Initialize the button."""
119  super().__init__(hass, config=config, unique_id=unique_id)
120  assert self._attr_name_attr_name is not None
121  self._command_press_command_press = (
122  Script(hass, config.get(CONF_PRESS), self._attr_name_attr_name, DOMAIN)
123  if config.get(CONF_PRESS, None) is not None
124  else None
125  )
126  self._attr_device_class_attr_device_class = config.get(CONF_DEVICE_CLASS)
127  self._attr_state_attr_state = None
129  hass,
130  config.get(CONF_DEVICE_ID),
131  )
132 
133  async def async_press(self) -> None:
134  """Press the button."""
135  if self._command_press_command_press:
136  await self.async_run_scriptasync_run_script(self._command_press_command_press, context=self._context_context)
None __init__(self, HomeAssistant hass, config, str|None unique_id)
Definition: button.py:117
None async_run_script(self, Script script, *_VarsType|None run_variables=None, Context|None context=None)
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: button.py:97
None async_setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback async_add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: button.py:79
list[TemplateButtonEntity] _async_create_entities(HomeAssistant hass, list[dict[str, Any]] definitions, str|None unique_id_prefix)
Definition: button.py:63
dr.DeviceInfo|None async_device_info_to_link_from_device_id(HomeAssistant hass, str|None device_id)
Definition: device.py:44