"""VoIP switch entities.""" from typing import Any, override from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription from homeassistant.const import STATE_ON, EntityCategory from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import restore_state from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import VoipConfigEntry from .devices import VoIPDevice from .entity import VoIPEntity async def async_setup_entry( hass: HomeAssistant, config_entry: VoipConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up VoIP switch entities.""" domain_data = config_entry.runtime_data.domain_data @callback def async_add_device(device: VoIPDevice) -> None: """Add device.""" async_add_entities([VoIPCallAllowedSwitch(device)]) domain_data.devices.async_add_new_device_listener(async_add_device) async_add_entities( [VoIPCallAllowedSwitch(device) for device in domain_data.devices] ) class VoIPCallAllowedSwitch(VoIPEntity, restore_state.RestoreEntity, SwitchEntity): """Entity to represent voip is allowed.""" entity_description = SwitchEntityDescription( key="allow_call", translation_key="allow_call", entity_category=EntityCategory.CONFIG, ) @override async def async_added_to_hass(self) -> None: """Call when entity about to be added to hass.""" await super().async_added_to_hass() state = await self.async_get_last_state() self._attr_is_on = state is not None and state.state == STATE_ON @override async def async_turn_on(self, **kwargs: Any) -> None: """Turn on.""" self._attr_is_on = True self.async_write_ha_state() @override async def async_turn_off(self, **kwargs: Any) -> None: """Turn off.""" self._attr_is_on = False self.async_write_ha_state()