Restore state of KNX Switch (#51761)

This commit is contained in:
Matthias Alphart 2021-06-15 13:08:19 +02:00 committed by GitHub
parent 333f199bd4
commit c0d311473c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -7,9 +7,10 @@ from xknx import XKNX
from xknx.devices import Switch as XknxSwitch
from homeassistant.components.switch import SwitchEntity
from homeassistant.const import CONF_NAME
from homeassistant.const import CONF_NAME, STATE_ON, STATE_UNAVAILABLE, STATE_UNKNOWN
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from .const import DOMAIN, KNX_ADDRESS
@ -37,7 +38,7 @@ async def async_setup_platform(
async_add_entities(entities)
class KNXSwitch(KnxEntity, SwitchEntity):
class KNXSwitch(KnxEntity, SwitchEntity, RestoreEntity):
"""Representation of a KNX switch."""
def __init__(self, xknx: XKNX, config: ConfigType) -> None:
@ -54,6 +55,15 @@ class KNXSwitch(KnxEntity, SwitchEntity):
)
self._unique_id = f"{self._device.switch.group_address}"
async def async_added_to_hass(self) -> None:
"""Restore last state."""
await super().async_added_to_hass()
if not self._device.switch.readable and (
last_state := await self.async_get_last_state()
):
if last_state.state not in (STATE_UNKNOWN, STATE_UNAVAILABLE):
self._device.switch.value = last_state.state == STATE_ON
@property
def is_on(self) -> bool:
"""Return true if device is on."""