Home Assistant Unofficial Reference 2024.12.1
switch.py
Go to the documentation of this file.
1 """VoIP switch entities."""
2 
3 from __future__ import annotations
4 
5 from typing import TYPE_CHECKING, Any
6 
7 from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
8 from homeassistant.config_entries import ConfigEntry
9 from homeassistant.const import STATE_ON, EntityCategory
10 from homeassistant.core import HomeAssistant, callback
11 from homeassistant.helpers import restore_state
12 from homeassistant.helpers.entity_platform import AddEntitiesCallback
13 
14 from .const import DOMAIN
15 from .devices import VoIPDevice
16 from .entity import VoIPEntity
17 
18 if TYPE_CHECKING:
19  from . import DomainData
20 
21 
23  hass: HomeAssistant,
24  config_entry: ConfigEntry,
25  async_add_entities: AddEntitiesCallback,
26 ) -> None:
27  """Set up VoIP switch entities."""
28  domain_data: DomainData = hass.data[DOMAIN]
29 
30  @callback
31  def async_add_device(device: VoIPDevice) -> None:
32  """Add device."""
34 
35  domain_data.devices.async_add_new_device_listener(async_add_device)
36 
38  [VoIPCallAllowedSwitch(device) for device in domain_data.devices]
39  )
40 
41 
42 class VoIPCallAllowedSwitch(VoIPEntity, restore_state.RestoreEntity, SwitchEntity):
43  """Entity to represent voip is allowed."""
44 
45  entity_description = SwitchEntityDescription(
46  key="allow_call",
47  translation_key="allow_call",
48  entity_category=EntityCategory.CONFIG,
49  )
50 
51  async def async_added_to_hass(self) -> None:
52  """Call when entity about to be added to hass."""
53  await super().async_added_to_hass()
54 
55  state = await self.async_get_last_state()
56  self._attr_is_on_attr_is_on = state is not None and state.state == STATE_ON
57 
58  async def async_turn_on(self, **kwargs: Any) -> None:
59  """Turn on."""
60  self._attr_is_on_attr_is_on = True
61  self.async_write_ha_stateasync_write_ha_state()
62 
63  async def async_turn_off(self, **kwargs: Any) -> None:
64  """Turn off."""
65  self._attr_is_on_attr_is_on = False
66  self.async_write_ha_stateasync_write_ha_state()
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: switch.py:26