Add configurable zha switch entity (#71784)

* add configurable zha switch entity

* final zha configurable switch

* fix codecov

* replaced errorneous cluster with local quirk

* test fix

* minor changes
This commit is contained in:
rforro 2022-05-25 01:43:35 +02:00 committed by GitHub
parent 6cac1dadeb
commit 0c2f22d478
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 314 additions and 1 deletions

View file

@ -2,8 +2,10 @@
from __future__ import annotations
import functools
from typing import Any
import logging
from typing import TYPE_CHECKING, Any
import zigpy.exceptions
from zigpy.zcl.clusters.general import OnOff
from zigpy.zcl.foundation import Status
@ -12,6 +14,7 @@ from homeassistant.config_entries import ConfigEntry
from homeassistant.const import STATE_ON, STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant, State, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import EntityCategory
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .core import discovery
@ -24,8 +27,17 @@ from .core.const import (
from .core.registries import ZHA_ENTITIES
from .entity import ZhaEntity, ZhaGroupEntity
if TYPE_CHECKING:
from .core.channels.base import ZigbeeChannel
from .core.device import ZHADevice
STRICT_MATCH = functools.partial(ZHA_ENTITIES.strict_match, Platform.SWITCH)
GROUP_MATCH = functools.partial(ZHA_ENTITIES.group_match, Platform.SWITCH)
CONFIG_DIAGNOSTIC_MATCH = functools.partial(
ZHA_ENTITIES.config_diagnostic_match, Platform.SWITCH
)
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
@ -138,3 +150,118 @@ class SwitchGroup(ZhaGroupEntity, SwitchEntity):
self._state = len(on_states) > 0
self._available = any(state.state != STATE_UNAVAILABLE for state in states)
class ZHASwitchConfigurationEntity(ZhaEntity, SwitchEntity):
"""Representation of a ZHA switch configuration entity."""
_zcl_attribute: str
_zcl_inverter_attribute: str = ""
@classmethod
def create_entity(
cls,
unique_id: str,
zha_device: ZHADevice,
channels: list[ZigbeeChannel],
**kwargs,
) -> ZhaEntity | None:
"""Entity Factory.
Return entity if it is a supported configuration, otherwise return None
"""
channel = channels[0]
if (
cls._zcl_attribute in channel.cluster.unsupported_attributes
or channel.cluster.get(cls._zcl_attribute) is None
):
_LOGGER.debug(
"%s is not supported - skipping %s entity creation",
cls._zcl_attribute,
cls.__name__,
)
return None
return cls(unique_id, zha_device, channels, **kwargs)
def __init__(
self,
unique_id: str,
zha_device: ZHADevice,
channels: list[ZigbeeChannel],
**kwargs,
) -> None:
"""Init this number configuration entity."""
self._channel: ZigbeeChannel = channels[0]
super().__init__(unique_id, zha_device, channels, **kwargs)
async def async_added_to_hass(self) -> None:
"""Run when about to be added to hass."""
await super().async_added_to_hass()
self.async_accept_signal(
self._channel, SIGNAL_ATTR_UPDATED, self.async_set_state
)
@callback
def async_set_state(self, attr_id: int, attr_name: str, value: Any):
"""Handle state update from channel."""
self.async_write_ha_state()
@property
def is_on(self) -> bool:
"""Return if the switch is on based on the statemachine."""
val = bool(self._channel.cluster.get(self._zcl_attribute))
invert = bool(self._channel.cluster.get(self._zcl_inverter_attribute))
return (not val) if invert else val
async def async_turn_on_off(self, state) -> None:
"""Turn the entity on or off."""
try:
invert = bool(self._channel.cluster.get(self._zcl_inverter_attribute))
result = await self._channel.cluster.write_attributes(
{self._zcl_attribute: not state if invert else state}
)
except zigpy.exceptions.ZigbeeException as ex:
self.error("Could not set value: %s", ex)
return
if not isinstance(result, Exception) and all(
record.status == Status.SUCCESS for record in result[0]
):
self.async_write_ha_state()
async def async_turn_on(self, **kwargs) -> None:
"""Turn the entity on."""
await self.async_turn_on_off(True)
async def async_turn_off(self, **kwargs) -> None:
"""Turn the entity off."""
await self.async_turn_on_off(False)
async def async_update(self) -> None:
"""Attempt to retrieve the state of the entity."""
await super().async_update()
_LOGGER.error("Polling current state")
if self._channel:
value = await self._channel.get_attribute_value(
self._zcl_attribute, from_cache=False
)
invert = await self._channel.get_attribute_value(
self._zcl_inverter_attribute, from_cache=False
)
_LOGGER.debug("read value=%s, inverter=%s", value, bool(invert))
@CONFIG_DIAGNOSTIC_MATCH(
channel_names="tuya_manufacturer",
manufacturers={
"_TZE200_b6wax7g0",
},
)
class OnOffWindowDetectionFunctionConfigurationEntity(
ZHASwitchConfigurationEntity, id_suffix="on_off_window_opened_detection"
):
"""Representation of a ZHA on off transition time configuration entity."""
_attr_entity_category = EntityCategory.CONFIG
_zcl_attribute = "window_detection_function"
_zcl_inverter_attribute = "window_detection_function_inverter"