Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """Support for ESPHome switches."""
2 
3 from __future__ import annotations
4 
5 from functools import partial
6 from typing import Any
7 
8 from aioesphomeapi import EntityInfo, SwitchInfo, SwitchState
9 
10 from homeassistant.components.switch import SwitchDeviceClass, SwitchEntity
11 from homeassistant.core import callback
12 from homeassistant.util.enum import try_parse_enum
13 
14 from .entity import (
15  EsphomeEntity,
16  convert_api_error_ha_error,
17  esphome_state_property,
18  platform_async_setup_entry,
19 )
20 
21 
22 class EsphomeSwitch(EsphomeEntity[SwitchInfo, SwitchState], SwitchEntity):
23  """A switch implementation for ESPHome."""
24 
25  @callback
26  def _on_static_info_update(self, static_info: EntityInfo) -> None:
27  """Set attrs from static info."""
28  super()._on_static_info_update(static_info)
29  static_info = self._static_info_static_info
30  self._attr_assumed_state_attr_assumed_state = static_info.assumed_state
31  self._attr_device_class_attr_device_class = try_parse_enum(
32  SwitchDeviceClass, static_info.device_class
33  )
34 
35  @property
36  @esphome_state_property
37  def is_on(self) -> bool | None:
38  """Return true if the switch is on."""
39  return self._state_state.state
40 
41  @convert_api_error_ha_error
42  async def async_turn_on(self, **kwargs: Any) -> None:
43  """Turn the entity on."""
44  self._client_client.switch_command(self._key_key, True)
45 
46  @convert_api_error_ha_error
47  async def async_turn_off(self, **kwargs: Any) -> None:
48  """Turn the entity off."""
49  self._client_client.switch_command(self._key_key, False)
50 
51 
52 async_setup_entry = partial(
53  platform_async_setup_entry,
54  info_type=SwitchInfo,
55  entity_type=EsphomeSwitch,
56  state_type=SwitchState,
57 )
None _on_static_info_update(self, EntityInfo static_info)
Definition: switch.py:26