2021-11-29 08:57:37 +00:00
|
|
|
"""Support for ESPHome buttons."""
|
|
|
|
from __future__ import annotations
|
|
|
|
|
2023-06-21 20:24:26 +00:00
|
|
|
from aioesphomeapi import ButtonInfo, EntityInfo, EntityState
|
2021-11-29 08:57:37 +00:00
|
|
|
|
2021-11-30 10:54:06 +00:00
|
|
|
from homeassistant.components.button import ButtonDeviceClass, ButtonEntity
|
2021-11-29 08:57:37 +00:00
|
|
|
from homeassistant.config_entries import ConfigEntry
|
|
|
|
from homeassistant.core import HomeAssistant, callback
|
|
|
|
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
2023-02-02 11:34:01 +00:00
|
|
|
from homeassistant.util.enum import try_parse_enum
|
2021-11-29 08:57:37 +00:00
|
|
|
|
2023-06-25 03:12:36 +00:00
|
|
|
from .entity import (
|
|
|
|
EsphomeEntity,
|
|
|
|
platform_async_setup_entry,
|
|
|
|
)
|
2021-11-29 08:57:37 +00:00
|
|
|
|
|
|
|
|
|
|
|
async def async_setup_entry(
|
|
|
|
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
|
|
|
|
) -> None:
|
|
|
|
"""Set up ESPHome buttons based on a config entry."""
|
|
|
|
await platform_async_setup_entry(
|
|
|
|
hass,
|
|
|
|
entry,
|
|
|
|
async_add_entities,
|
|
|
|
info_type=ButtonInfo,
|
|
|
|
entity_type=EsphomeButton,
|
|
|
|
state_type=EntityState,
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
class EsphomeButton(EsphomeEntity[ButtonInfo, EntityState], ButtonEntity):
|
|
|
|
"""A button implementation for ESPHome."""
|
|
|
|
|
2023-06-21 20:24:26 +00:00
|
|
|
@callback
|
|
|
|
def _on_static_info_update(self, static_info: EntityInfo) -> None:
|
|
|
|
"""Set attrs from static info."""
|
|
|
|
super()._on_static_info_update(static_info)
|
|
|
|
self._attr_device_class = try_parse_enum(
|
|
|
|
ButtonDeviceClass, self._static_info.device_class
|
|
|
|
)
|
2021-11-30 07:33:14 +00:00
|
|
|
|
2021-11-29 08:57:37 +00:00
|
|
|
@callback
|
|
|
|
def _on_device_update(self) -> None:
|
2023-06-27 03:34:37 +00:00
|
|
|
"""Call when device updates or entry data changes.
|
|
|
|
|
|
|
|
The default behavior is only to write entity state when the
|
|
|
|
device is unavailable when the device state changes.
|
|
|
|
This method overrides the default behavior since buttons do
|
|
|
|
not have a state, so we will never get a state update for a
|
|
|
|
button. As such, we need to write the state on every device
|
|
|
|
update to ensure the button goes available and unavailable
|
|
|
|
as the device becomes available or unavailable.
|
|
|
|
"""
|
|
|
|
self._on_entry_data_changed()
|
|
|
|
self.async_write_ha_state()
|
2021-11-29 08:57:37 +00:00
|
|
|
|
2022-06-28 15:19:03 +00:00
|
|
|
async def async_press(self) -> None:
|
2021-11-29 08:57:37 +00:00
|
|
|
"""Press the button."""
|
2023-06-21 20:24:26 +00:00
|
|
|
await self._client.button_command(self._key)
|