Home Assistant Unofficial Reference 2024.12.1
button.py
Go to the documentation of this file.
1 """Support for ESPHome buttons."""
2 
3 from __future__ import annotations
4 
5 from functools import partial
6 
7 from aioesphomeapi import ButtonInfo, EntityInfo, EntityState
8 
9 from homeassistant.components.button import ButtonDeviceClass, ButtonEntity
10 from homeassistant.core import callback
11 from homeassistant.util.enum import try_parse_enum
12 
13 from .entity import (
14  EsphomeEntity,
15  convert_api_error_ha_error,
16  platform_async_setup_entry,
17 )
18 
19 
20 class EsphomeButton(EsphomeEntity[ButtonInfo, EntityState], ButtonEntity):
21  """A button implementation for ESPHome."""
22 
23  @callback
24  def _on_static_info_update(self, static_info: EntityInfo) -> None:
25  """Set attrs from static info."""
26  super()._on_static_info_update(static_info)
27  self._attr_device_class_attr_device_class = try_parse_enum(
28  ButtonDeviceClass, self._static_info_static_info.device_class
29  )
30 
31  @callback
32  def _on_device_update(self) -> None:
33  """Call when device updates or entry data changes.
34 
35  The default behavior is only to write entity state when the
36  device is unavailable when the device state changes.
37  This method overrides the default behavior since buttons do
38  not have a state, so we will never get a state update for a
39  button. As such, we need to write the state on every device
40  update to ensure the button goes available and unavailable
41  as the device becomes available or unavailable.
42  """
43  self._on_entry_data_changed_on_entry_data_changed()
44  self.async_write_ha_stateasync_write_ha_state()
45 
46  @convert_api_error_ha_error
47  async def async_press(self) -> None:
48  """Press the button."""
49  self._client_client.button_command(self._key_key)
50 
51 
52 async_setup_entry = partial(
53  platform_async_setup_entry,
54  info_type=ButtonInfo,
55  entity_type=EsphomeButton,
56  state_type=EntityState,
57 )
None _on_static_info_update(self, EntityInfo static_info)
Definition: button.py:24