Files
home-assistant-mb-secure/custom_components/mb_secure/switch.py
T

62 lines
2.0 KiB
Python

"""Switch entities for MB-Secure outputs."""
from __future__ import annotations
from typing import Any
from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .coordinator import MBSecureCoordinator
from .entity import MBSecureEntity, async_setup_dynamic_entities
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry[MBSecureCoordinator],
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up capability-reported output switches."""
coordinator = entry.runtime_data
assert coordinator.info is not None and coordinator.info.bridge_id is not None
bridge_id = coordinator.info.bridge_id
async_setup_dynamic_entities(
entry,
async_add_entities,
collection_name="outputs",
capability="set",
factory=lambda object_id: MBSecureOutputEntity(
coordinator, bridge_id, object_id
),
)
class MBSecureOutputEntity(MBSecureEntity, SwitchEntity):
"""Represent one controllable normalized output."""
def __init__(
self, coordinator: MBSecureCoordinator, bridge_id: str, object_id: str
) -> None:
"""Initialize an output switch."""
super().__init__(coordinator, bridge_id, "outputs", object_id)
@property
def is_on(self) -> bool | None:
"""Return the normalized output state."""
item = self.bridge_object
if item is None:
return None
return item.state == "on"
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the output on."""
await self.coordinator.client.async_set_output(self._object_id, "on")
await self.coordinator.async_request_refresh()
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the output off."""
await self.coordinator.client.async_set_output(self._object_id, "off")
await self.coordinator.async_request_refresh()