1
0
mirror of https://github.com/home-assistant/core.git synced 2026-06-30 19:26:31 +01:00
Files
core/homeassistant/components/hdmi_cec/switch.py
T
2026-05-10 20:53:17 -04:00

67 lines
2.3 KiB
Python

"""Support for HDMI CEC devices as switches."""
import logging
from typing import Any
from pycec.commands import CecCommand
from pycec.const import CMD_STANDBY, POWER_OFF, POWER_ON
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN, SwitchEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from .const import ATTR_NEW, DOMAIN
from .entity import CecEntity
_LOGGER = logging.getLogger(__name__)
ENTITY_ID_FORMAT = SWITCH_DOMAIN + ".{}"
async def async_setup_platform(
hass: HomeAssistant,
config: ConfigType,
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Find and return HDMI devices as switches."""
if discovery_info and ATTR_NEW in discovery_info:
_LOGGER.debug("Setting up HDMI devices %s", discovery_info[ATTR_NEW])
entities = []
for device in discovery_info[ATTR_NEW]:
hdmi_device = hass.data[DOMAIN][device]
entities.append(CecSwitchEntity(hdmi_device, hdmi_device.logical_address))
async_add_entities(entities, True)
class CecSwitchEntity(CecEntity, SwitchEntity):
"""Representation of a HDMI device as a Switch."""
def __init__(self, device, logical) -> None:
"""Initialize the HDMI device."""
CecEntity.__init__(self, device, logical)
self.entity_id = f"{SWITCH_DOMAIN}.hdmi_{hex(self._logical_address)[2:]}"
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn device on."""
self._device.turn_on()
self._attr_is_on = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn device off."""
self._device.send_command(CecCommand(CMD_STANDBY, dst=self._logical_address))
self._attr_is_on = False
self.async_write_ha_state()
async def async_update(self) -> None:
"""Update device status."""
device = self._device
if device.power_status in {POWER_OFF, 3}:
self._attr_is_on = False
elif device.power_status in {POWER_ON, 4}:
self._attr_is_on = True
else:
_LOGGER.warning("Unknown state: %d", device.power_status)