From c0d311473cfa7c7524dba04dba01cf0920f6feb7 Mon Sep 17 00:00:00 2001 From: Matthias Alphart Date: Tue, 15 Jun 2021 13:08:19 +0200 Subject: [PATCH] Restore state of KNX Switch (#51761) --- homeassistant/components/knx/switch.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/knx/switch.py b/homeassistant/components/knx/switch.py index c6fbb32b15d..b30313a047a 100644 --- a/homeassistant/components/knx/switch.py +++ b/homeassistant/components/knx/switch.py @@ -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."""