2019-04-03 17:40:03 +02:00
|
|
|
"""Support for exposing a templated binary sensor."""
|
2024-03-08 16:35:23 +01:00
|
|
|
|
2021-04-13 07:58:44 -07:00
|
|
|
from __future__ import annotations
|
|
|
|
|
|
2026-01-22 08:11:49 -05:00
|
|
|
from abc import abstractmethod
|
2022-03-14 20:28:55 +01:00
|
|
|
from dataclasses import dataclass
|
|
|
|
|
from datetime import datetime, timedelta
|
2021-04-29 09:25:34 -07:00
|
|
|
from functools import partial
|
2021-04-22 14:54:28 -07:00
|
|
|
import logging
|
2023-07-23 00:03:44 +02:00
|
|
|
from typing import Any, Self
|
2021-04-22 14:54:28 -07:00
|
|
|
|
2016-09-08 16:26:54 +02:00
|
|
|
import voluptuous as vol
|
2016-08-24 09:16:26 +01:00
|
|
|
|
2016-09-08 16:26:54 +02:00
|
|
|
from homeassistant.components.binary_sensor import (
|
2019-12-08 21:05:08 +01:00
|
|
|
DEVICE_CLASSES_SCHEMA,
|
2021-04-22 14:54:28 -07:00
|
|
|
DOMAIN as BINARY_SENSOR_DOMAIN,
|
2016-09-08 16:26:54 +02:00
|
|
|
ENTITY_ID_FORMAT,
|
2024-06-26 10:54:19 +02:00
|
|
|
PLATFORM_SCHEMA as BINARY_SENSOR_PLATFORM_SCHEMA,
|
2020-04-23 21:57:07 +02:00
|
|
|
BinarySensorEntity,
|
2017-02-10 23:46:15 -05:00
|
|
|
)
|
2023-08-30 17:28:56 +02:00
|
|
|
from homeassistant.config_entries import ConfigEntry
|
2016-09-08 16:26:54 +02:00
|
|
|
from homeassistant.const import (
|
2016-09-27 21:29:55 -07:00
|
|
|
ATTR_ENTITY_ID,
|
2019-12-08 21:05:08 +01:00
|
|
|
ATTR_FRIENDLY_NAME,
|
|
|
|
|
CONF_DEVICE_CLASS,
|
2018-02-05 17:30:56 -05:00
|
|
|
CONF_ENTITY_PICTURE_TEMPLATE,
|
2021-04-13 07:58:44 -07:00
|
|
|
CONF_FRIENDLY_NAME_TEMPLATE,
|
2019-12-08 21:05:08 +01:00
|
|
|
CONF_ICON_TEMPLATE,
|
2021-04-13 07:58:44 -07:00
|
|
|
CONF_NAME,
|
2018-10-29 08:03:10 +01:00
|
|
|
CONF_SENSORS,
|
2021-04-13 07:58:44 -07:00
|
|
|
CONF_STATE,
|
2020-08-02 00:45:55 +02:00
|
|
|
CONF_UNIQUE_ID,
|
2021-04-13 07:58:44 -07:00
|
|
|
CONF_UNIT_OF_MEASUREMENT,
|
2019-12-08 21:05:08 +01:00
|
|
|
CONF_VALUE_TEMPLATE,
|
2022-03-04 00:27:39 +01:00
|
|
|
STATE_ON,
|
|
|
|
|
STATE_UNAVAILABLE,
|
|
|
|
|
STATE_UNKNOWN,
|
2018-10-29 08:03:10 +01:00
|
|
|
)
|
2022-02-10 10:59:54 +01:00
|
|
|
from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback
|
2016-02-23 15:16:18 -08:00
|
|
|
from homeassistant.exceptions import TemplateError
|
2025-07-18 14:38:53 -04:00
|
|
|
from homeassistant.helpers import config_validation as cv, template
|
2025-02-10 21:08:03 +01:00
|
|
|
from homeassistant.helpers.entity_platform import (
|
|
|
|
|
AddConfigEntryEntitiesCallback,
|
|
|
|
|
AddEntitiesCallback,
|
|
|
|
|
)
|
2022-03-14 20:28:55 +01:00
|
|
|
from homeassistant.helpers.event import async_call_later, async_track_point_in_utc_time
|
|
|
|
|
from homeassistant.helpers.restore_state import ExtraStoredData, RestoreEntity
|
2022-01-03 13:13:03 +01:00
|
|
|
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
|
2022-03-14 20:28:55 +01:00
|
|
|
from homeassistant.util import dt as dt_util
|
2019-12-08 21:05:08 +01:00
|
|
|
|
2021-12-13 09:39:13 +01:00
|
|
|
from . import TriggerUpdateCoordinator
|
2025-11-27 06:28:16 -05:00
|
|
|
from .entity import AbstractTemplateEntity
|
2025-07-18 14:38:53 -04:00
|
|
|
from .helpers import (
|
|
|
|
|
async_setup_template_entry,
|
|
|
|
|
async_setup_template_platform,
|
|
|
|
|
async_setup_template_preview,
|
|
|
|
|
)
|
2025-08-27 12:06:03 -04:00
|
|
|
from .schemas import (
|
|
|
|
|
TEMPLATE_ENTITY_ATTRIBUTES_SCHEMA_LEGACY,
|
|
|
|
|
TEMPLATE_ENTITY_AVAILABILITY_SCHEMA_LEGACY,
|
2025-07-18 14:38:53 -04:00
|
|
|
TEMPLATE_ENTITY_COMMON_CONFIG_ENTRY_SCHEMA,
|
2025-08-27 12:06:03 -04:00
|
|
|
make_template_entity_common_modern_attributes_schema,
|
2025-07-18 14:38:53 -04:00
|
|
|
)
|
2025-08-27 12:06:03 -04:00
|
|
|
from .template_entity import TemplateEntity
|
2021-04-22 14:54:28 -07:00
|
|
|
from .trigger_entity import TriggerEntity
|
2016-02-23 15:16:18 -08:00
|
|
|
|
2025-08-27 12:06:03 -04:00
|
|
|
DEFAULT_NAME = "Template Binary Sensor"
|
|
|
|
|
|
2017-09-05 02:01:01 +02:00
|
|
|
CONF_DELAY_ON = "delay_on"
|
|
|
|
|
CONF_DELAY_OFF = "delay_off"
|
2021-04-29 09:25:34 -07:00
|
|
|
CONF_AUTO_OFF = "auto_off"
|
2019-07-31 12:25:30 -07:00
|
|
|
|
2021-04-13 07:58:44 -07:00
|
|
|
LEGACY_FIELDS = {
|
|
|
|
|
CONF_FRIENDLY_NAME_TEMPLATE: CONF_NAME,
|
|
|
|
|
CONF_VALUE_TEMPLATE: CONF_STATE,
|
|
|
|
|
}
|
|
|
|
|
|
2025-07-18 14:38:53 -04:00
|
|
|
BINARY_SENSOR_COMMON_SCHEMA = vol.Schema(
|
2021-04-13 07:58:44 -07:00
|
|
|
{
|
2021-11-10 07:58:22 +01:00
|
|
|
vol.Optional(CONF_AUTO_OFF): vol.Any(cv.positive_time_period, cv.template),
|
|
|
|
|
vol.Optional(CONF_DELAY_OFF): vol.Any(cv.positive_time_period, cv.template),
|
|
|
|
|
vol.Optional(CONF_DELAY_ON): vol.Any(cv.positive_time_period, cv.template),
|
|
|
|
|
vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
|
2021-04-13 07:58:44 -07:00
|
|
|
vol.Required(CONF_STATE): cv.template,
|
2021-11-10 07:58:22 +01:00
|
|
|
vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string,
|
2021-04-13 07:58:44 -07:00
|
|
|
}
|
2025-07-18 14:38:53 -04:00
|
|
|
)
|
2021-04-13 07:58:44 -07:00
|
|
|
|
2025-07-18 14:38:53 -04:00
|
|
|
BINARY_SENSOR_YAML_SCHEMA = BINARY_SENSOR_COMMON_SCHEMA.extend(
|
2025-08-27 12:06:03 -04:00
|
|
|
make_template_entity_common_modern_attributes_schema(
|
|
|
|
|
BINARY_SENSOR_DOMAIN, DEFAULT_NAME
|
|
|
|
|
).schema
|
2024-07-07 11:40:02 -03:00
|
|
|
)
|
|
|
|
|
|
2025-07-18 14:38:53 -04:00
|
|
|
BINARY_SENSOR_CONFIG_ENTRY_SCHEMA = BINARY_SENSOR_COMMON_SCHEMA.extend(
|
|
|
|
|
TEMPLATE_ENTITY_COMMON_CONFIG_ENTRY_SCHEMA.schema
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
BINARY_SENSOR_LEGACY_YAML_SCHEMA = vol.All(
|
2020-09-01 08:53:50 -05:00
|
|
|
cv.deprecated(ATTR_ENTITY_ID),
|
|
|
|
|
vol.Schema(
|
|
|
|
|
{
|
|
|
|
|
vol.Required(CONF_VALUE_TEMPLATE): cv.template,
|
|
|
|
|
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
|
|
|
|
|
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
|
|
|
|
|
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
|
|
|
|
|
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
|
|
|
|
|
vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
|
2020-11-17 18:24:04 +01:00
|
|
|
vol.Optional(CONF_DELAY_ON): vol.Any(cv.positive_time_period, cv.template),
|
|
|
|
|
vol.Optional(CONF_DELAY_OFF): vol.Any(cv.positive_time_period, cv.template),
|
2020-09-01 08:53:50 -05:00
|
|
|
vol.Optional(CONF_UNIQUE_ID): cv.string,
|
|
|
|
|
}
|
2025-08-27 12:06:03 -04:00
|
|
|
)
|
|
|
|
|
.extend(TEMPLATE_ENTITY_ATTRIBUTES_SCHEMA_LEGACY.schema)
|
|
|
|
|
.extend(TEMPLATE_ENTITY_AVAILABILITY_SCHEMA_LEGACY.schema),
|
2016-08-24 09:16:26 +01:00
|
|
|
)
|
2019-07-31 12:25:30 -07:00
|
|
|
|
2021-04-13 07:58:44 -07:00
|
|
|
|
2024-06-26 10:54:19 +02:00
|
|
|
PLATFORM_SCHEMA = BINARY_SENSOR_PLATFORM_SCHEMA.extend(
|
2021-04-13 07:58:44 -07:00
|
|
|
{
|
|
|
|
|
vol.Required(CONF_SENSORS): cv.schema_with_slug_keys(
|
2025-07-18 14:38:53 -04:00
|
|
|
BINARY_SENSOR_LEGACY_YAML_SCHEMA
|
2021-04-13 07:58:44 -07:00
|
|
|
),
|
|
|
|
|
}
|
2016-08-24 09:16:26 +01:00
|
|
|
)
|
2019-07-31 12:25:30 -07:00
|
|
|
|
|
|
|
|
|
2022-01-03 13:13:03 +01:00
|
|
|
async def async_setup_platform(
|
|
|
|
|
hass: HomeAssistant,
|
|
|
|
|
config: ConfigType,
|
|
|
|
|
async_add_entities: AddEntitiesCallback,
|
|
|
|
|
discovery_info: DiscoveryInfoType | None = None,
|
|
|
|
|
) -> None:
|
2020-08-21 18:31:48 -05:00
|
|
|
"""Set up the template binary sensors."""
|
2025-07-15 02:26:34 -04:00
|
|
|
await async_setup_template_platform(
|
2021-04-24 07:14:31 -07:00
|
|
|
hass,
|
2025-07-15 02:26:34 -04:00
|
|
|
BINARY_SENSOR_DOMAIN,
|
|
|
|
|
config,
|
|
|
|
|
StateBinarySensorEntity,
|
|
|
|
|
TriggerBinarySensorEntity,
|
|
|
|
|
async_add_entities,
|
|
|
|
|
discovery_info,
|
|
|
|
|
LEGACY_FIELDS,
|
|
|
|
|
legacy_key=CONF_SENSORS,
|
2021-04-13 07:58:44 -07:00
|
|
|
)
|
2016-02-23 15:16:18 -08:00
|
|
|
|
|
|
|
|
|
2023-08-30 17:28:56 +02:00
|
|
|
async def async_setup_entry(
|
|
|
|
|
hass: HomeAssistant,
|
|
|
|
|
config_entry: ConfigEntry,
|
2025-02-10 21:08:03 +01:00
|
|
|
async_add_entities: AddConfigEntryEntitiesCallback,
|
2023-08-30 17:28:56 +02:00
|
|
|
) -> None:
|
|
|
|
|
"""Initialize config entry."""
|
2025-07-18 14:38:53 -04:00
|
|
|
await async_setup_template_entry(
|
|
|
|
|
hass,
|
|
|
|
|
config_entry,
|
|
|
|
|
async_add_entities,
|
|
|
|
|
StateBinarySensorEntity,
|
|
|
|
|
BINARY_SENSOR_CONFIG_ENTRY_SCHEMA,
|
2023-08-30 17:28:56 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@callback
|
|
|
|
|
def async_create_preview_binary_sensor(
|
|
|
|
|
hass: HomeAssistant, name: str, config: dict[str, Any]
|
2025-07-15 02:26:34 -04:00
|
|
|
) -> StateBinarySensorEntity:
|
2023-08-30 17:28:56 +02:00
|
|
|
"""Create a preview sensor."""
|
2025-07-18 14:38:53 -04:00
|
|
|
return async_setup_template_preview(
|
|
|
|
|
hass, name, config, StateBinarySensorEntity, BINARY_SENSOR_CONFIG_ENTRY_SCHEMA
|
|
|
|
|
)
|
2023-08-30 17:28:56 +02:00
|
|
|
|
|
|
|
|
|
2025-11-27 06:28:16 -05:00
|
|
|
class AbstractTemplateBinarySensor(
|
|
|
|
|
AbstractTemplateEntity, BinarySensorEntity, RestoreEntity
|
|
|
|
|
):
|
|
|
|
|
"""Representation of a template binary sensor features."""
|
|
|
|
|
|
|
|
|
|
_entity_id_format = ENTITY_ID_FORMAT
|
|
|
|
|
|
|
|
|
|
# The super init is not called because TemplateEntity and TriggerEntity will call AbstractTemplateEntity.__init__.
|
|
|
|
|
# This ensures that the __init__ on AbstractTemplateEntity is not called twice.
|
|
|
|
|
def __init__(self, config: dict[str, Any]) -> None: # pylint: disable=super-init-not-called
|
|
|
|
|
"""Initialize the features."""
|
|
|
|
|
|
|
|
|
|
self._attr_device_class = config.get(CONF_DEVICE_CLASS)
|
|
|
|
|
self._template: template.Template = config[CONF_STATE]
|
2026-01-22 08:11:49 -05:00
|
|
|
self._delay_on = None
|
|
|
|
|
self._delay_off = None
|
2025-11-27 06:28:16 -05:00
|
|
|
self._delay_cancel: CALLBACK_TYPE | None = None
|
|
|
|
|
|
2026-01-22 08:11:49 -05:00
|
|
|
self.setup_state_template(
|
|
|
|
|
CONF_STATE,
|
|
|
|
|
"_attr_is_on",
|
|
|
|
|
on_update=self._update_state,
|
|
|
|
|
)
|
|
|
|
|
self._delay_on = None
|
|
|
|
|
try:
|
|
|
|
|
self._delay_on = cv.positive_time_period(config.get(CONF_DELAY_ON))
|
|
|
|
|
except vol.Invalid:
|
|
|
|
|
self.setup_template(CONF_DELAY_ON, "_delay_on", cv.positive_time_period)
|
|
|
|
|
|
|
|
|
|
self._delay_off = None
|
|
|
|
|
try:
|
|
|
|
|
self._delay_off = cv.positive_time_period(config.get(CONF_DELAY_OFF))
|
|
|
|
|
except vol.Invalid:
|
|
|
|
|
self.setup_template(CONF_DELAY_OFF, "_delay_off", cv.positive_time_period)
|
|
|
|
|
|
|
|
|
|
@callback
|
|
|
|
|
@abstractmethod
|
|
|
|
|
def _update_state(self, result: Any) -> None:
|
|
|
|
|
"""Update the state."""
|
|
|
|
|
|
2025-11-27 06:28:16 -05:00
|
|
|
|
|
|
|
|
class StateBinarySensorEntity(TemplateEntity, AbstractTemplateBinarySensor):
|
2016-03-07 20:21:08 +01:00
|
|
|
"""A virtual binary sensor that triggers from another sensor."""
|
2016-02-23 15:16:18 -08:00
|
|
|
|
2022-06-08 15:55:49 +02:00
|
|
|
_attr_should_poll = False
|
|
|
|
|
|
2017-02-10 23:46:15 -05:00
|
|
|
def __init__(
|
|
|
|
|
self,
|
2021-04-13 07:58:44 -07:00
|
|
|
hass: HomeAssistant,
|
2021-11-10 07:58:22 +01:00
|
|
|
config: dict[str, Any],
|
2021-04-13 07:58:44 -07:00
|
|
|
unique_id: str | None,
|
2021-11-10 07:58:22 +01:00
|
|
|
) -> None:
|
2016-03-07 20:21:08 +01:00
|
|
|
"""Initialize the Template binary sensor."""
|
2025-07-15 09:53:01 -04:00
|
|
|
TemplateEntity.__init__(self, hass, config, unique_id)
|
2025-11-27 06:28:16 -05:00
|
|
|
AbstractTemplateBinarySensor.__init__(self, config)
|
2017-03-02 08:50:41 +01:00
|
|
|
|
2022-07-01 19:05:37 +02:00
|
|
|
async def async_added_to_hass(self) -> None:
|
2023-08-30 16:22:52 +02:00
|
|
|
"""Restore state."""
|
2022-03-04 00:27:39 +01:00
|
|
|
if (
|
2025-11-27 06:28:16 -05:00
|
|
|
(
|
2026-01-22 08:11:49 -05:00
|
|
|
CONF_DELAY_ON in self._templates
|
|
|
|
|
or CONF_DELAY_OFF in self._templates
|
|
|
|
|
or self._delay_on is not None
|
|
|
|
|
or self._delay_off is not None
|
2025-11-27 06:28:16 -05:00
|
|
|
)
|
2022-03-04 00:27:39 +01:00
|
|
|
and (last_state := await self.async_get_last_state()) is not None
|
|
|
|
|
and last_state.state not in (STATE_UNKNOWN, STATE_UNAVAILABLE)
|
|
|
|
|
):
|
2024-10-24 16:16:46 +02:00
|
|
|
self._attr_is_on = last_state.state == STATE_ON
|
2023-08-30 16:22:52 +02:00
|
|
|
await super().async_added_to_hass()
|
2022-03-04 00:27:39 +01:00
|
|
|
|
2020-08-20 09:07:58 -05:00
|
|
|
@callback
|
|
|
|
|
def _update_state(self, result):
|
|
|
|
|
super()._update_state(result)
|
2017-03-02 08:50:41 +01:00
|
|
|
|
2020-08-20 09:07:58 -05:00
|
|
|
if self._delay_cancel:
|
|
|
|
|
self._delay_cancel()
|
|
|
|
|
self._delay_cancel = None
|
2016-02-23 15:16:18 -08:00
|
|
|
|
2025-06-30 10:06:05 +02:00
|
|
|
state: bool | None = None
|
|
|
|
|
if result is not None and not isinstance(result, TemplateError):
|
|
|
|
|
state = template.result_as_boolean(result)
|
2020-08-20 09:07:58 -05:00
|
|
|
|
2024-10-24 16:16:46 +02:00
|
|
|
if state == self._attr_is_on:
|
2020-08-20 09:07:58 -05:00
|
|
|
return
|
|
|
|
|
|
|
|
|
|
# state without delay
|
|
|
|
|
if (
|
|
|
|
|
state is None
|
|
|
|
|
or (state and not self._delay_on)
|
|
|
|
|
or (not state and not self._delay_off)
|
|
|
|
|
):
|
2024-10-24 16:16:46 +02:00
|
|
|
self._attr_is_on = state
|
2020-08-20 09:07:58 -05:00
|
|
|
return
|
|
|
|
|
|
|
|
|
|
@callback
|
|
|
|
|
def _set_state(_):
|
|
|
|
|
"""Set state of template binary sensor."""
|
2024-10-24 16:16:46 +02:00
|
|
|
self._attr_is_on = state
|
2020-08-20 09:07:58 -05:00
|
|
|
self.async_write_ha_state()
|
|
|
|
|
|
2021-04-22 14:54:28 -07:00
|
|
|
delay = (self._delay_on if state else self._delay_off).total_seconds()
|
2020-08-20 09:07:58 -05:00
|
|
|
# state with delay. Cancelled if template result changes.
|
|
|
|
|
self._delay_cancel = async_call_later(self.hass, delay, _set_state)
|
2016-02-23 15:16:18 -08:00
|
|
|
|
2021-04-22 14:54:28 -07:00
|
|
|
|
2025-11-27 06:28:16 -05:00
|
|
|
class TriggerBinarySensorEntity(TriggerEntity, AbstractTemplateBinarySensor):
|
2021-04-22 14:54:28 -07:00
|
|
|
"""Sensor entity based on trigger data."""
|
|
|
|
|
|
|
|
|
|
domain = BINARY_SENSOR_DOMAIN
|
|
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
|
self,
|
|
|
|
|
hass: HomeAssistant,
|
|
|
|
|
coordinator: TriggerUpdateCoordinator,
|
|
|
|
|
config: dict,
|
|
|
|
|
) -> None:
|
|
|
|
|
"""Initialize the entity."""
|
2025-11-27 06:28:16 -05:00
|
|
|
TriggerEntity.__init__(self, hass, coordinator, config)
|
|
|
|
|
AbstractTemplateBinarySensor.__init__(self, config)
|
2021-04-22 14:54:28 -07:00
|
|
|
|
2025-06-11 09:08:10 -04:00
|
|
|
self._last_delay_from: bool | None = None
|
|
|
|
|
self._last_delay_to: bool | None = None
|
2022-03-14 20:28:55 +01:00
|
|
|
self._auto_off_cancel: CALLBACK_TYPE | None = None
|
|
|
|
|
self._auto_off_time: datetime | None = None
|
2026-01-22 08:11:49 -05:00
|
|
|
self.setup_template(CONF_AUTO_OFF, "_auto_off_time", cv.positive_time_period)
|
2021-04-22 14:54:28 -07:00
|
|
|
|
2022-03-14 20:28:55 +01:00
|
|
|
async def async_added_to_hass(self) -> None:
|
|
|
|
|
"""Restore last state."""
|
|
|
|
|
await super().async_added_to_hass()
|
|
|
|
|
if (
|
|
|
|
|
(last_state := await self.async_get_last_state()) is not None
|
|
|
|
|
and (extra_data := await self.async_get_last_binary_sensor_data())
|
|
|
|
|
is not None
|
|
|
|
|
and last_state.state not in (STATE_UNKNOWN, STATE_UNAVAILABLE)
|
|
|
|
|
# The trigger might have fired already while we waited for stored data,
|
|
|
|
|
# then we should not restore state
|
2024-10-24 16:16:46 +02:00
|
|
|
and self._attr_is_on is None
|
2022-03-14 20:28:55 +01:00
|
|
|
):
|
2024-10-24 16:16:46 +02:00
|
|
|
self._attr_is_on = last_state.state == STATE_ON
|
2022-04-06 07:58:12 +02:00
|
|
|
self.restore_attributes(last_state)
|
2022-03-14 20:28:55 +01:00
|
|
|
|
|
|
|
|
if CONF_AUTO_OFF not in self._config:
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
if (
|
|
|
|
|
auto_off_time := extra_data.auto_off_time
|
|
|
|
|
) is not None and auto_off_time <= dt_util.utcnow():
|
|
|
|
|
# It's already past the saved auto off time
|
2024-10-24 16:16:46 +02:00
|
|
|
self._attr_is_on = False
|
2022-03-14 20:28:55 +01:00
|
|
|
|
2024-10-24 16:16:46 +02:00
|
|
|
if self._attr_is_on and auto_off_time is not None:
|
2022-03-14 20:28:55 +01:00
|
|
|
self._set_auto_off(auto_off_time)
|
|
|
|
|
|
2021-04-22 14:54:28 -07:00
|
|
|
@callback
|
2026-01-22 08:11:49 -05:00
|
|
|
def _cancel_delays(self):
|
|
|
|
|
if self._delay_cancel:
|
|
|
|
|
self._delay_cancel()
|
|
|
|
|
self._delay_cancel = None
|
2021-04-22 14:54:28 -07:00
|
|
|
|
2026-01-22 08:11:49 -05:00
|
|
|
if self._auto_off_cancel:
|
|
|
|
|
self._auto_off_cancel()
|
|
|
|
|
self._auto_off_cancel = None
|
|
|
|
|
self._auto_off_time = None
|
|
|
|
|
|
|
|
|
|
@callback
|
|
|
|
|
def _update_state(self, result):
|
2025-06-30 10:06:05 +02:00
|
|
|
state: bool | None = None
|
2026-01-22 08:11:49 -05:00
|
|
|
if result is not None:
|
|
|
|
|
state = template.result_as_boolean(result)
|
2025-06-11 09:08:10 -04:00
|
|
|
|
2026-01-22 08:11:49 -05:00
|
|
|
if state:
|
|
|
|
|
delay = self._rendered.get(CONF_DELAY_ON) or self._delay_on
|
|
|
|
|
else:
|
|
|
|
|
delay = self._rendered.get(CONF_DELAY_OFF) or self._delay_off
|
2025-06-11 09:08:10 -04:00
|
|
|
|
|
|
|
|
if (
|
|
|
|
|
self._delay_cancel
|
|
|
|
|
and delay
|
|
|
|
|
and self._attr_is_on == self._last_delay_from
|
|
|
|
|
and state == self._last_delay_to
|
|
|
|
|
):
|
|
|
|
|
return
|
|
|
|
|
|
2026-01-22 08:11:49 -05:00
|
|
|
self._cancel_delays()
|
2021-04-22 14:54:28 -07:00
|
|
|
|
2025-06-30 10:06:05 +02:00
|
|
|
# state without delay.
|
|
|
|
|
if self._attr_is_on == state or delay is None:
|
2021-04-29 09:25:34 -07:00
|
|
|
self._set_state(state)
|
2021-04-22 14:54:28 -07:00
|
|
|
return
|
|
|
|
|
|
|
|
|
|
if not isinstance(delay, timedelta):
|
|
|
|
|
try:
|
|
|
|
|
delay = cv.positive_time_period(delay)
|
|
|
|
|
except vol.Invalid as err:
|
2026-01-22 08:11:49 -05:00
|
|
|
key = CONF_DELAY_ON if state else CONF_DELAY_OFF
|
2021-04-22 14:54:28 -07:00
|
|
|
logging.getLogger(__name__).warning(
|
|
|
|
|
"Error rendering %s template: %s", key, err
|
|
|
|
|
)
|
|
|
|
|
return
|
|
|
|
|
|
2021-04-29 09:25:34 -07:00
|
|
|
# state with delay. Cancelled if new trigger received
|
2025-06-11 09:08:10 -04:00
|
|
|
self._last_delay_from = self._attr_is_on
|
|
|
|
|
self._last_delay_to = state
|
2021-04-29 09:25:34 -07:00
|
|
|
self._delay_cancel = async_call_later(
|
|
|
|
|
self.hass, delay.total_seconds(), partial(self._set_state, state)
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
@callback
|
|
|
|
|
def _set_state(self, state, _=None):
|
|
|
|
|
"""Set up auto off."""
|
2024-10-24 16:16:46 +02:00
|
|
|
self._attr_is_on = state
|
2025-10-10 08:21:11 -04:00
|
|
|
self._delay_cancel = None
|
2021-04-29 09:25:34 -07:00
|
|
|
self.async_write_ha_state()
|
|
|
|
|
|
|
|
|
|
if not state:
|
|
|
|
|
return
|
|
|
|
|
|
2022-03-14 20:28:55 +01:00
|
|
|
auto_off_delay = self._rendered.get(CONF_AUTO_OFF) or self._config.get(
|
2021-04-29 09:25:34 -07:00
|
|
|
CONF_AUTO_OFF
|
|
|
|
|
)
|
|
|
|
|
|
2022-03-14 20:28:55 +01:00
|
|
|
if auto_off_delay is None:
|
2021-04-29 09:25:34 -07:00
|
|
|
return
|
|
|
|
|
|
2022-03-14 20:28:55 +01:00
|
|
|
if not isinstance(auto_off_delay, timedelta):
|
2021-04-29 09:25:34 -07:00
|
|
|
try:
|
2022-03-14 20:28:55 +01:00
|
|
|
auto_off_delay = cv.positive_time_period(auto_off_delay)
|
2021-04-29 09:25:34 -07:00
|
|
|
except vol.Invalid as err:
|
|
|
|
|
logging.getLogger(__name__).warning(
|
|
|
|
|
"Error rendering %s template: %s", CONF_AUTO_OFF, err
|
|
|
|
|
)
|
|
|
|
|
return
|
|
|
|
|
|
2022-03-14 20:28:55 +01:00
|
|
|
auto_off_time = dt_util.utcnow() + auto_off_delay
|
|
|
|
|
self._set_auto_off(auto_off_time)
|
|
|
|
|
|
2026-01-22 08:11:49 -05:00
|
|
|
def _render_availability_template(self, variables):
|
|
|
|
|
available = super()._render_availability_template(variables)
|
|
|
|
|
if not available:
|
|
|
|
|
# Cancel any delay_on, delay_off, or auto_off when
|
|
|
|
|
# the entity goes unavailable
|
|
|
|
|
self._cancel_delays()
|
|
|
|
|
return available
|
|
|
|
|
|
2022-03-14 20:28:55 +01:00
|
|
|
def _set_auto_off(self, auto_off_time: datetime) -> None:
|
2021-04-22 14:54:28 -07:00
|
|
|
@callback
|
2021-04-29 09:25:34 -07:00
|
|
|
def _auto_off(_):
|
2022-03-14 20:28:55 +01:00
|
|
|
"""Reset state of template binary sensor."""
|
2024-10-24 16:16:46 +02:00
|
|
|
self._attr_is_on = False
|
2021-04-22 14:54:28 -07:00
|
|
|
self.async_write_ha_state()
|
|
|
|
|
|
2022-03-14 20:28:55 +01:00
|
|
|
self._auto_off_time = auto_off_time
|
|
|
|
|
self._auto_off_cancel = async_track_point_in_utc_time(
|
|
|
|
|
self.hass, _auto_off, self._auto_off_time
|
2021-04-22 14:54:28 -07:00
|
|
|
)
|
2022-03-14 20:28:55 +01:00
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def extra_restore_state_data(self) -> AutoOffExtraStoredData:
|
|
|
|
|
"""Return specific state data to be restored."""
|
|
|
|
|
return AutoOffExtraStoredData(self._auto_off_time)
|
|
|
|
|
|
|
|
|
|
async def async_get_last_binary_sensor_data(
|
|
|
|
|
self,
|
|
|
|
|
) -> AutoOffExtraStoredData | None:
|
|
|
|
|
"""Restore auto_off_time."""
|
|
|
|
|
if (restored_last_extra_data := await self.async_get_last_extra_data()) is None:
|
|
|
|
|
return None
|
|
|
|
|
return AutoOffExtraStoredData.from_dict(restored_last_extra_data.as_dict())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
|
class AutoOffExtraStoredData(ExtraStoredData):
|
|
|
|
|
"""Object to hold extra stored data."""
|
|
|
|
|
|
|
|
|
|
auto_off_time: datetime | None
|
|
|
|
|
|
|
|
|
|
def as_dict(self) -> dict[str, Any]:
|
|
|
|
|
"""Return a dict representation of additional data."""
|
2024-05-24 15:05:53 +02:00
|
|
|
auto_off_time: datetime | dict[str, str] | None = self.auto_off_time
|
2022-03-14 20:28:55 +01:00
|
|
|
if isinstance(auto_off_time, datetime):
|
|
|
|
|
auto_off_time = {
|
|
|
|
|
"__type": str(type(auto_off_time)),
|
|
|
|
|
"isoformat": auto_off_time.isoformat(),
|
|
|
|
|
}
|
|
|
|
|
return {
|
|
|
|
|
"auto_off_time": auto_off_time,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@classmethod
|
2023-02-07 05:30:22 +01:00
|
|
|
def from_dict(cls, restored: dict[str, Any]) -> Self | None:
|
2022-03-14 20:28:55 +01:00
|
|
|
"""Initialize a stored binary sensor state from a dict."""
|
|
|
|
|
try:
|
|
|
|
|
auto_off_time = restored["auto_off_time"]
|
|
|
|
|
except KeyError:
|
|
|
|
|
return None
|
|
|
|
|
try:
|
|
|
|
|
type_ = auto_off_time["__type"]
|
|
|
|
|
if type_ == "<class 'datetime.datetime'>":
|
|
|
|
|
auto_off_time = dt_util.parse_datetime(auto_off_time["isoformat"])
|
|
|
|
|
except TypeError:
|
|
|
|
|
# native_value is not a dict
|
|
|
|
|
pass
|
|
|
|
|
except KeyError:
|
|
|
|
|
# native_value is a dict, but does not have all values
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
return cls(auto_off_time)
|