mirror of
https://github.com/home-assistant/core.git
synced 2026-12-03 04:08:19 -04:00
Move timer entity to entity module (#186362)
This commit is contained in:
@@ -1,10 +1,8 @@
|
||||
"""Support for Timers."""
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
import logging
|
||||
from typing import Any, Self, override
|
||||
from typing import Any, override
|
||||
|
||||
import probatio
|
||||
|
||||
@@ -17,19 +15,18 @@ from homeassistant.const import ( # noqa: F401
|
||||
SERVICE_RELOAD,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.exceptions import ServiceValidationError
|
||||
from homeassistant.helpers import collection, config_validation as cv
|
||||
from homeassistant.helpers.entity_component import EntityComponent
|
||||
from homeassistant.helpers.event import async_track_point_in_utc_time
|
||||
from homeassistant.helpers.restore_state import RestoreEntity
|
||||
from homeassistant.helpers.storage import Store
|
||||
from homeassistant.helpers.typing import ConfigType, VolDictType
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from .const import ( # noqa: F401
|
||||
ATTR_DURATION,
|
||||
CONF_DURATION,
|
||||
CONF_RESTORE,
|
||||
DATA_TIMER,
|
||||
DEFAULT_DURATION,
|
||||
DEFAULT_RESTORE,
|
||||
DOMAIN,
|
||||
SERVICE_CANCEL,
|
||||
SERVICE_CHANGE,
|
||||
@@ -38,34 +35,16 @@ from .const import ( # noqa: F401
|
||||
SERVICE_START,
|
||||
TimerEntityStateAttribute,
|
||||
)
|
||||
from .entity import Timer, _format_timedelta
|
||||
from .services import async_setup_services
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
ENTITY_ID_FORMAT = DOMAIN + ".{}"
|
||||
|
||||
DEFAULT_RESTORE = False
|
||||
|
||||
ATTR_REMAINING = "remaining"
|
||||
ATTR_FINISHES_AT = "finishes_at"
|
||||
ATTR_RESTORE = "restore"
|
||||
ATTR_FINISHED_AT = "finished_at"
|
||||
ATTR_LAST_TRANSITION = "last_transition"
|
||||
|
||||
CONF_DURATION = "duration"
|
||||
CONF_RESTORE = "restore"
|
||||
|
||||
STATUS_IDLE = "idle"
|
||||
STATUS_ACTIVE = "active"
|
||||
STATUS_PAUSED = "paused"
|
||||
|
||||
EVENT_TIMER_FINISHED = "timer.finished"
|
||||
EVENT_TIMER_CANCELLED = "timer.cancelled"
|
||||
EVENT_TIMER_CHANGED = "timer.changed"
|
||||
EVENT_TIMER_STARTED = "timer.started"
|
||||
EVENT_TIMER_RESTARTED = "timer.restarted"
|
||||
EVENT_TIMER_PAUSED = "timer.paused"
|
||||
|
||||
|
||||
STORAGE_KEY = DOMAIN
|
||||
STORAGE_VERSION = 1
|
||||
@@ -78,13 +57,6 @@ STORAGE_FIELDS: VolDictType = {
|
||||
}
|
||||
|
||||
|
||||
def _format_timedelta(delta: timedelta) -> str:
|
||||
total_seconds = delta.total_seconds()
|
||||
hours, remainder = divmod(total_seconds, 3600)
|
||||
minutes, seconds = divmod(remainder, 60)
|
||||
return f"{int(hours)}:{int(minutes):02}:{int(seconds):02}"
|
||||
|
||||
|
||||
def _none_to_empty_dict[_T](value: _T | None) -> _T | dict[Any, Any]:
|
||||
if value is None:
|
||||
return {}
|
||||
@@ -183,285 +155,3 @@ class TimerStorageCollection(collection.DictStorageCollection):
|
||||
if CONF_DURATION in update_data:
|
||||
data[CONF_DURATION] = _format_timedelta(data[CONF_DURATION])
|
||||
return data # type: ignore[no-any-return]
|
||||
|
||||
|
||||
class Timer(collection.CollectionEntity, RestoreEntity):
|
||||
"""Representation of a timer."""
|
||||
|
||||
editable: bool
|
||||
|
||||
def __init__(self, config: ConfigType) -> None:
|
||||
"""Initialize a timer."""
|
||||
self._config: dict = config
|
||||
self._last_transition: str | None = None
|
||||
self._state: str = STATUS_IDLE
|
||||
self._configured_duration = cv.time_period_str(config[CONF_DURATION])
|
||||
self._running_duration: timedelta = self._configured_duration
|
||||
self._remaining: timedelta | None = None
|
||||
self._end: datetime | None = None
|
||||
self._listener: Callable[[], None] | None = None
|
||||
self._restore: bool = self._config.get(CONF_RESTORE, DEFAULT_RESTORE)
|
||||
|
||||
self._attr_should_poll = False
|
||||
self._attr_force_update = True
|
||||
|
||||
@classmethod
|
||||
@override
|
||||
def from_storage(cls, config: ConfigType) -> Self:
|
||||
"""Return entity instance initialized from storage."""
|
||||
timer = cls(config)
|
||||
timer.editable = True
|
||||
return timer
|
||||
|
||||
@classmethod
|
||||
@override
|
||||
def from_yaml(cls, config: ConfigType) -> Self:
|
||||
"""Return entity instance initialized from yaml."""
|
||||
timer = cls(config)
|
||||
timer.entity_id = ENTITY_ID_FORMAT.format(config[CONF_ID])
|
||||
timer.editable = False
|
||||
return timer
|
||||
|
||||
@property
|
||||
@override
|
||||
def name(self) -> str | None:
|
||||
"""Return name of the timer."""
|
||||
return self._config.get(CONF_NAME)
|
||||
|
||||
@property
|
||||
@override
|
||||
def icon(self) -> str | None:
|
||||
"""Return the icon to be used for this entity."""
|
||||
return self._config.get(CONF_ICON)
|
||||
|
||||
@property
|
||||
@override
|
||||
def state(self) -> str:
|
||||
"""Return the current value of the timer."""
|
||||
return self._state
|
||||
|
||||
@property
|
||||
@override
|
||||
def extra_state_attributes(self) -> dict[str, Any]:
|
||||
"""Return the state attributes."""
|
||||
attrs: dict[str, Any] = {
|
||||
TimerEntityStateAttribute.DURATION: _format_timedelta(
|
||||
self._running_duration
|
||||
),
|
||||
TimerEntityStateAttribute.EDITABLE: self.editable,
|
||||
TimerEntityStateAttribute.LAST_TRANSITION: self._last_transition,
|
||||
}
|
||||
if self._end is not None:
|
||||
attrs[TimerEntityStateAttribute.FINISHES_AT] = self._end.isoformat()
|
||||
if self._remaining is not None:
|
||||
attrs[TimerEntityStateAttribute.REMAINING] = _format_timedelta(
|
||||
self._remaining
|
||||
)
|
||||
if self._restore:
|
||||
attrs[TimerEntityStateAttribute.RESTORE] = self._restore
|
||||
|
||||
return attrs
|
||||
|
||||
@property
|
||||
@override
|
||||
def unique_id(self) -> str | None:
|
||||
"""Return unique id for the entity."""
|
||||
return self._config[CONF_ID] # type: ignore[no-any-return]
|
||||
|
||||
@override
|
||||
async def async_added_to_hass(self) -> None:
|
||||
"""Call when entity is about to be added to Home Assistant."""
|
||||
# If we don't need to restore a previous state or no previous state exists,
|
||||
# start at idle
|
||||
if not self._restore or (state := await self.async_get_last_state()) is None:
|
||||
self._state = STATUS_IDLE
|
||||
return
|
||||
|
||||
# Begin restoring state
|
||||
self._state = state.state
|
||||
self._last_transition = state.attributes.get(
|
||||
TimerEntityStateAttribute.LAST_TRANSITION
|
||||
)
|
||||
|
||||
# Nothing more to do if the timer is idle
|
||||
if self._state == STATUS_IDLE:
|
||||
return
|
||||
|
||||
self._running_duration = cv.time_period(
|
||||
state.attributes[TimerEntityStateAttribute.DURATION]
|
||||
)
|
||||
# If the timer was paused, we restore the remaining time
|
||||
if self._state == STATUS_PAUSED:
|
||||
self._remaining = cv.time_period(
|
||||
state.attributes[TimerEntityStateAttribute.REMAINING]
|
||||
)
|
||||
return
|
||||
# If we get here, the timer must have been active so we need to decide what
|
||||
# to do based on end time and the current time
|
||||
end = cv.datetime(state.attributes[TimerEntityStateAttribute.FINISHES_AT])
|
||||
# If there is time remaining in the timer, restore the remaining time then
|
||||
# start the timer
|
||||
if (remaining := end - dt_util.utcnow().replace(microsecond=0)) > timedelta(0):
|
||||
self._remaining = remaining
|
||||
self._state = STATUS_PAUSED
|
||||
self.async_start()
|
||||
# If the timer ended before now, finish the timer. The event will indicate
|
||||
# when the timer was expected to fire.
|
||||
else:
|
||||
self._end = end
|
||||
self.async_finish()
|
||||
|
||||
@callback
|
||||
def async_start(self, duration: timedelta | None = None) -> None:
|
||||
"""Start a timer."""
|
||||
if self._listener:
|
||||
self._listener()
|
||||
self._listener = None
|
||||
|
||||
event = EVENT_TIMER_STARTED
|
||||
if self._state in (STATUS_ACTIVE, STATUS_PAUSED):
|
||||
event = EVENT_TIMER_RESTARTED
|
||||
|
||||
self._state = STATUS_ACTIVE
|
||||
start = dt_util.utcnow().replace(microsecond=0)
|
||||
|
||||
# Set remaining and running duration unless resuming or restarting
|
||||
if duration:
|
||||
self._remaining = self._running_duration = duration
|
||||
elif not self._remaining:
|
||||
self._remaining = self._running_duration
|
||||
|
||||
self._end = start + self._remaining
|
||||
|
||||
self._listener = async_track_point_in_utc_time(
|
||||
self.hass, self._async_finished, self._end
|
||||
)
|
||||
|
||||
self._fire_event_and_write_state(event)
|
||||
|
||||
@callback
|
||||
def async_change(self, duration: timedelta) -> None:
|
||||
"""Change duration of a running timer."""
|
||||
if self._listener is None or self._end is None:
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="timer_not_running",
|
||||
translation_placeholders={"entity_id": self.entity_id},
|
||||
)
|
||||
# Check against new remaining time before checking boundaries
|
||||
new_remaining = (self._end + duration) - dt_util.utcnow().replace(microsecond=0)
|
||||
if self._remaining and new_remaining > self._running_duration:
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="change_beyond_duration",
|
||||
translation_placeholders={"entity_id": self.entity_id},
|
||||
)
|
||||
if self._remaining and (self._remaining + duration) < timedelta():
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="change_negative_remaining",
|
||||
translation_placeholders={"entity_id": self.entity_id},
|
||||
)
|
||||
|
||||
self._listener()
|
||||
self._end += duration
|
||||
self._remaining = new_remaining
|
||||
self._listener = async_track_point_in_utc_time(
|
||||
self.hass, self._async_finished, self._end
|
||||
)
|
||||
# We don't use _fire_event_and_write_state here because we don't want to
|
||||
# update last_transition
|
||||
self.async_write_ha_state()
|
||||
self.hass.bus.async_fire(EVENT_TIMER_CHANGED, {ATTR_ENTITY_ID: self.entity_id})
|
||||
|
||||
@callback
|
||||
def async_pause(self) -> None:
|
||||
"""Pause a timer."""
|
||||
if self._listener is None or self._end is None:
|
||||
return
|
||||
|
||||
self._listener()
|
||||
self._listener = None
|
||||
self._remaining = self._end - dt_util.utcnow().replace(microsecond=0)
|
||||
self._state = STATUS_PAUSED
|
||||
self._end = None
|
||||
self._fire_event_and_write_state(EVENT_TIMER_PAUSED)
|
||||
|
||||
@callback
|
||||
def async_cancel(self) -> None:
|
||||
"""Cancel a timer."""
|
||||
if self._state == STATUS_IDLE:
|
||||
return
|
||||
|
||||
if self._listener:
|
||||
self._listener()
|
||||
self._listener = None
|
||||
self._state = STATUS_IDLE
|
||||
self._end = None
|
||||
self._remaining = None
|
||||
self._running_duration = self._configured_duration
|
||||
self._fire_event_and_write_state(EVENT_TIMER_CANCELLED)
|
||||
|
||||
@callback
|
||||
def async_finish(self) -> None:
|
||||
"""Reset and updates the states, fire finished event."""
|
||||
if self._state == STATUS_IDLE:
|
||||
return
|
||||
|
||||
if self._listener:
|
||||
self._listener()
|
||||
self._listener = None
|
||||
end = self._end
|
||||
if end is None:
|
||||
end = dt_util.utcnow().replace(microsecond=0)
|
||||
self._state = STATUS_IDLE
|
||||
self._end = None
|
||||
self._remaining = None
|
||||
self._running_duration = self._configured_duration
|
||||
self._fire_event_and_write_state(
|
||||
EVENT_TIMER_FINISHED, extra_attrs={ATTR_FINISHED_AT: end.isoformat()}
|
||||
)
|
||||
|
||||
@callback
|
||||
def _async_finished(self, time: datetime) -> None:
|
||||
"""Reset and updates the states, fire finished event."""
|
||||
if self._state != STATUS_ACTIVE or self._end is None:
|
||||
return
|
||||
|
||||
self._listener = None
|
||||
self._state = STATUS_IDLE
|
||||
end = self._end
|
||||
self._end = None
|
||||
self._remaining = None
|
||||
self._running_duration = self._configured_duration
|
||||
self._fire_event_and_write_state(
|
||||
EVENT_TIMER_FINISHED, extra_attrs={ATTR_FINISHED_AT: end.isoformat()}
|
||||
)
|
||||
|
||||
@override
|
||||
async def async_will_remove_from_hass(self) -> None:
|
||||
"""Cancel the running timer when the entity is removed."""
|
||||
if self._listener:
|
||||
self._listener()
|
||||
self._listener = None
|
||||
|
||||
@override
|
||||
async def async_update_config(self, config: ConfigType) -> None:
|
||||
"""Handle when the config is updated."""
|
||||
self._config = config
|
||||
self._configured_duration = cv.time_period_str(config[CONF_DURATION])
|
||||
if self._state == STATUS_IDLE:
|
||||
self._running_duration = self._configured_duration
|
||||
self._restore = config.get(CONF_RESTORE, DEFAULT_RESTORE)
|
||||
self.async_write_ha_state()
|
||||
|
||||
def _fire_event_and_write_state(
|
||||
self, event: str, *, extra_attrs: dict[str, Any] | None = None
|
||||
) -> None:
|
||||
"""Fire the event and write state."""
|
||||
self._last_transition = event.partition(".")[2]
|
||||
self.async_write_ha_state()
|
||||
event_data = {ATTR_ENTITY_ID: self.entity_id}
|
||||
if extra_attrs:
|
||||
event_data.update(extra_attrs)
|
||||
self.hass.bus.async_fire(event, event_data)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.condition import Condition, make_entity_state_condition
|
||||
|
||||
from . import DOMAIN, STATUS_ACTIVE, STATUS_IDLE, STATUS_PAUSED
|
||||
from .const import DOMAIN, STATUS_ACTIVE, STATUS_IDLE, STATUS_PAUSED
|
||||
|
||||
CONDITIONS: dict[str, type[Condition]] = {
|
||||
"is_active": make_entity_state_condition(DOMAIN, STATUS_ACTIVE),
|
||||
|
||||
@@ -10,11 +10,29 @@ if TYPE_CHECKING:
|
||||
|
||||
DOMAIN: Final = "timer"
|
||||
|
||||
ENTITY_ID_FORMAT = DOMAIN + ".{}"
|
||||
|
||||
DATA_TIMER: HassKey[TimerData] = HassKey(DOMAIN)
|
||||
|
||||
DEFAULT_DURATION: Final = 0
|
||||
DEFAULT_RESTORE = False
|
||||
|
||||
ATTR_DURATION: Final = "duration"
|
||||
ATTR_FINISHED_AT = "finished_at"
|
||||
|
||||
CONF_DURATION = "duration"
|
||||
CONF_RESTORE = "restore"
|
||||
|
||||
STATUS_IDLE = "idle"
|
||||
STATUS_ACTIVE = "active"
|
||||
STATUS_PAUSED = "paused"
|
||||
|
||||
EVENT_TIMER_FINISHED = "timer.finished"
|
||||
EVENT_TIMER_CANCELLED = "timer.cancelled"
|
||||
EVENT_TIMER_CHANGED = "timer.changed"
|
||||
EVENT_TIMER_STARTED = "timer.started"
|
||||
EVENT_TIMER_RESTARTED = "timer.restarted"
|
||||
EVENT_TIMER_PAUSED = "timer.paused"
|
||||
|
||||
SERVICE_START: Final = "start"
|
||||
SERVICE_PAUSE: Final = "pause"
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
"""Entities for the Timer integration."""
|
||||
|
||||
from collections.abc import Callable
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Self, override
|
||||
|
||||
from homeassistant.const import ATTR_ENTITY_ID, CONF_ICON, CONF_ID, CONF_NAME
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.exceptions import ServiceValidationError
|
||||
from homeassistant.helpers import collection, config_validation as cv
|
||||
from homeassistant.helpers.event import async_track_point_in_utc_time
|
||||
from homeassistant.helpers.restore_state import RestoreEntity
|
||||
from homeassistant.helpers.typing import ConfigType
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from .const import (
|
||||
ATTR_FINISHED_AT,
|
||||
CONF_DURATION,
|
||||
CONF_RESTORE,
|
||||
DEFAULT_RESTORE,
|
||||
DOMAIN,
|
||||
ENTITY_ID_FORMAT,
|
||||
EVENT_TIMER_CANCELLED,
|
||||
EVENT_TIMER_CHANGED,
|
||||
EVENT_TIMER_FINISHED,
|
||||
EVENT_TIMER_PAUSED,
|
||||
EVENT_TIMER_RESTARTED,
|
||||
EVENT_TIMER_STARTED,
|
||||
STATUS_ACTIVE,
|
||||
STATUS_IDLE,
|
||||
STATUS_PAUSED,
|
||||
TimerEntityStateAttribute,
|
||||
)
|
||||
|
||||
|
||||
def _format_timedelta(delta: timedelta) -> str:
|
||||
total_seconds = delta.total_seconds()
|
||||
hours, remainder = divmod(total_seconds, 3600)
|
||||
minutes, seconds = divmod(remainder, 60)
|
||||
return f"{int(hours)}:{int(minutes):02}:{int(seconds):02}"
|
||||
|
||||
|
||||
class Timer(collection.CollectionEntity, RestoreEntity):
|
||||
"""Representation of a timer."""
|
||||
|
||||
editable: bool
|
||||
|
||||
def __init__(self, config: ConfigType) -> None:
|
||||
"""Initialize a timer."""
|
||||
self._config: dict = config
|
||||
self._last_transition: str | None = None
|
||||
self._state: str = STATUS_IDLE
|
||||
self._configured_duration = cv.time_period_str(config[CONF_DURATION])
|
||||
self._running_duration: timedelta = self._configured_duration
|
||||
self._remaining: timedelta | None = None
|
||||
self._end: datetime | None = None
|
||||
self._listener: Callable[[], None] | None = None
|
||||
self._restore: bool = self._config.get(CONF_RESTORE, DEFAULT_RESTORE)
|
||||
|
||||
self._attr_should_poll = False
|
||||
self._attr_force_update = True
|
||||
|
||||
@classmethod
|
||||
@override
|
||||
def from_storage(cls, config: ConfigType) -> Self:
|
||||
"""Return entity instance initialized from storage."""
|
||||
timer = cls(config)
|
||||
timer.editable = True
|
||||
return timer
|
||||
|
||||
@classmethod
|
||||
@override
|
||||
def from_yaml(cls, config: ConfigType) -> Self:
|
||||
"""Return entity instance initialized from yaml."""
|
||||
timer = cls(config)
|
||||
timer.entity_id = ENTITY_ID_FORMAT.format(config[CONF_ID])
|
||||
timer.editable = False
|
||||
return timer
|
||||
|
||||
@property
|
||||
@override
|
||||
def name(self) -> str | None:
|
||||
"""Return name of the timer."""
|
||||
return self._config.get(CONF_NAME)
|
||||
|
||||
@property
|
||||
@override
|
||||
def icon(self) -> str | None:
|
||||
"""Return the icon to be used for this entity."""
|
||||
return self._config.get(CONF_ICON)
|
||||
|
||||
@property
|
||||
@override
|
||||
def state(self) -> str:
|
||||
"""Return the current value of the timer."""
|
||||
return self._state
|
||||
|
||||
@property
|
||||
@override
|
||||
def extra_state_attributes(self) -> dict[str, Any]:
|
||||
"""Return the state attributes."""
|
||||
attrs: dict[str, Any] = {
|
||||
TimerEntityStateAttribute.DURATION: _format_timedelta(
|
||||
self._running_duration
|
||||
),
|
||||
TimerEntityStateAttribute.EDITABLE: self.editable,
|
||||
TimerEntityStateAttribute.LAST_TRANSITION: self._last_transition,
|
||||
}
|
||||
if self._end is not None:
|
||||
attrs[TimerEntityStateAttribute.FINISHES_AT] = self._end.isoformat()
|
||||
if self._remaining is not None:
|
||||
attrs[TimerEntityStateAttribute.REMAINING] = _format_timedelta(
|
||||
self._remaining
|
||||
)
|
||||
if self._restore:
|
||||
attrs[TimerEntityStateAttribute.RESTORE] = self._restore
|
||||
|
||||
return attrs
|
||||
|
||||
@property
|
||||
@override
|
||||
def unique_id(self) -> str | None:
|
||||
"""Return unique id for the entity."""
|
||||
return self._config[CONF_ID] # type: ignore[no-any-return]
|
||||
|
||||
@override
|
||||
async def async_added_to_hass(self) -> None:
|
||||
"""Call when entity is about to be added to Home Assistant."""
|
||||
# If we don't need to restore a previous state or no previous state exists,
|
||||
# start at idle
|
||||
if not self._restore or (state := await self.async_get_last_state()) is None:
|
||||
self._state = STATUS_IDLE
|
||||
return
|
||||
|
||||
# Begin restoring state
|
||||
self._state = state.state
|
||||
self._last_transition = state.attributes.get(
|
||||
TimerEntityStateAttribute.LAST_TRANSITION
|
||||
)
|
||||
|
||||
# Nothing more to do if the timer is idle
|
||||
if self._state == STATUS_IDLE:
|
||||
return
|
||||
|
||||
self._running_duration = cv.time_period(
|
||||
state.attributes[TimerEntityStateAttribute.DURATION]
|
||||
)
|
||||
# If the timer was paused, we restore the remaining time
|
||||
if self._state == STATUS_PAUSED:
|
||||
self._remaining = cv.time_period(
|
||||
state.attributes[TimerEntityStateAttribute.REMAINING]
|
||||
)
|
||||
return
|
||||
# If we get here, the timer must have been active so we need to decide what
|
||||
# to do based on end time and the current time
|
||||
end = cv.datetime(state.attributes[TimerEntityStateAttribute.FINISHES_AT])
|
||||
# If there is time remaining in the timer, restore the remaining time then
|
||||
# start the timer
|
||||
if (remaining := end - dt_util.utcnow().replace(microsecond=0)) > timedelta(0):
|
||||
self._remaining = remaining
|
||||
self._state = STATUS_PAUSED
|
||||
self.async_start()
|
||||
# If the timer ended before now, finish the timer. The event will indicate
|
||||
# when the timer was expected to fire.
|
||||
else:
|
||||
self._end = end
|
||||
self.async_finish()
|
||||
|
||||
@callback
|
||||
def async_start(self, duration: timedelta | None = None) -> None:
|
||||
"""Start a timer."""
|
||||
if self._listener:
|
||||
self._listener()
|
||||
self._listener = None
|
||||
|
||||
event = EVENT_TIMER_STARTED
|
||||
if self._state in (STATUS_ACTIVE, STATUS_PAUSED):
|
||||
event = EVENT_TIMER_RESTARTED
|
||||
|
||||
self._state = STATUS_ACTIVE
|
||||
start = dt_util.utcnow().replace(microsecond=0)
|
||||
|
||||
# Set remaining and running duration unless resuming or restarting
|
||||
if duration:
|
||||
self._remaining = self._running_duration = duration
|
||||
elif not self._remaining:
|
||||
self._remaining = self._running_duration
|
||||
|
||||
self._end = start + self._remaining
|
||||
|
||||
self._listener = async_track_point_in_utc_time(
|
||||
self.hass, self._async_finished, self._end
|
||||
)
|
||||
|
||||
self._fire_event_and_write_state(event)
|
||||
|
||||
@callback
|
||||
def async_change(self, duration: timedelta) -> None:
|
||||
"""Change duration of a running timer."""
|
||||
if self._listener is None or self._end is None:
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="timer_not_running",
|
||||
translation_placeholders={"entity_id": self.entity_id},
|
||||
)
|
||||
# Check against new remaining time before checking boundaries
|
||||
new_remaining = (self._end + duration) - dt_util.utcnow().replace(microsecond=0)
|
||||
if self._remaining and new_remaining > self._running_duration:
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="change_beyond_duration",
|
||||
translation_placeholders={"entity_id": self.entity_id},
|
||||
)
|
||||
if self._remaining and (self._remaining + duration) < timedelta():
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="change_negative_remaining",
|
||||
translation_placeholders={"entity_id": self.entity_id},
|
||||
)
|
||||
|
||||
self._listener()
|
||||
self._end += duration
|
||||
self._remaining = new_remaining
|
||||
self._listener = async_track_point_in_utc_time(
|
||||
self.hass, self._async_finished, self._end
|
||||
)
|
||||
# We don't use _fire_event_and_write_state here because we don't want to
|
||||
# update last_transition
|
||||
self.async_write_ha_state()
|
||||
self.hass.bus.async_fire(EVENT_TIMER_CHANGED, {ATTR_ENTITY_ID: self.entity_id})
|
||||
|
||||
@callback
|
||||
def async_pause(self) -> None:
|
||||
"""Pause a timer."""
|
||||
if self._listener is None or self._end is None:
|
||||
return
|
||||
|
||||
self._listener()
|
||||
self._listener = None
|
||||
self._remaining = self._end - dt_util.utcnow().replace(microsecond=0)
|
||||
self._state = STATUS_PAUSED
|
||||
self._end = None
|
||||
self._fire_event_and_write_state(EVENT_TIMER_PAUSED)
|
||||
|
||||
@callback
|
||||
def async_cancel(self) -> None:
|
||||
"""Cancel a timer."""
|
||||
if self._state == STATUS_IDLE:
|
||||
return
|
||||
|
||||
if self._listener:
|
||||
self._listener()
|
||||
self._listener = None
|
||||
self._state = STATUS_IDLE
|
||||
self._end = None
|
||||
self._remaining = None
|
||||
self._running_duration = self._configured_duration
|
||||
self._fire_event_and_write_state(EVENT_TIMER_CANCELLED)
|
||||
|
||||
@callback
|
||||
def async_finish(self) -> None:
|
||||
"""Reset and updates the states, fire finished event."""
|
||||
if self._state == STATUS_IDLE:
|
||||
return
|
||||
|
||||
if self._listener:
|
||||
self._listener()
|
||||
self._listener = None
|
||||
end = self._end
|
||||
if end is None:
|
||||
end = dt_util.utcnow().replace(microsecond=0)
|
||||
self._state = STATUS_IDLE
|
||||
self._end = None
|
||||
self._remaining = None
|
||||
self._running_duration = self._configured_duration
|
||||
self._fire_event_and_write_state(
|
||||
EVENT_TIMER_FINISHED, extra_attrs={ATTR_FINISHED_AT: end.isoformat()}
|
||||
)
|
||||
|
||||
@callback
|
||||
def _async_finished(self, time: datetime) -> None:
|
||||
"""Reset and updates the states, fire finished event."""
|
||||
if self._state != STATUS_ACTIVE or self._end is None:
|
||||
return
|
||||
|
||||
self._listener = None
|
||||
self._state = STATUS_IDLE
|
||||
end = self._end
|
||||
self._end = None
|
||||
self._remaining = None
|
||||
self._running_duration = self._configured_duration
|
||||
self._fire_event_and_write_state(
|
||||
EVENT_TIMER_FINISHED, extra_attrs={ATTR_FINISHED_AT: end.isoformat()}
|
||||
)
|
||||
|
||||
@override
|
||||
async def async_will_remove_from_hass(self) -> None:
|
||||
"""Cancel the running timer when the entity is removed."""
|
||||
if self._listener:
|
||||
self._listener()
|
||||
self._listener = None
|
||||
|
||||
@override
|
||||
async def async_update_config(self, config: ConfigType) -> None:
|
||||
"""Handle when the config is updated."""
|
||||
self._config = config
|
||||
self._configured_duration = cv.time_period_str(config[CONF_DURATION])
|
||||
if self._state == STATUS_IDLE:
|
||||
self._running_duration = self._configured_duration
|
||||
self._restore = config.get(CONF_RESTORE, DEFAULT_RESTORE)
|
||||
self.async_write_ha_state()
|
||||
|
||||
def _fire_event_and_write_state(
|
||||
self, event: str, *, extra_attrs: dict[str, Any] | None = None
|
||||
) -> None:
|
||||
"""Fire the event and write state."""
|
||||
self._last_transition = event.partition(".")[2]
|
||||
self.async_write_ha_state()
|
||||
event_data = {ATTR_ENTITY_ID: self.entity_id}
|
||||
if extra_attrs:
|
||||
event_data.update(extra_attrs)
|
||||
self.hass.bus.async_fire(event, event_data)
|
||||
@@ -8,7 +8,7 @@ from typing import Any
|
||||
from homeassistant.const import ATTR_ENTITY_ID
|
||||
from homeassistant.core import Context, HomeAssistant, State
|
||||
|
||||
from . import (
|
||||
from .const import (
|
||||
ATTR_DURATION,
|
||||
DOMAIN,
|
||||
SERVICE_CANCEL,
|
||||
|
||||
@@ -26,8 +26,7 @@ from homeassistant.helpers.trigger import (
|
||||
from homeassistant.helpers.typing import ConfigType
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from . import DOMAIN, STATUS_ACTIVE
|
||||
from .const import TimerEntityStateAttribute
|
||||
from .const import DOMAIN, STATUS_ACTIVE, TimerEntityStateAttribute
|
||||
|
||||
CONF_REMAINING = "remaining"
|
||||
|
||||
|
||||
@@ -4,8 +4,12 @@ from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.timer import STATUS_ACTIVE, STATUS_IDLE, STATUS_PAUSED
|
||||
from homeassistant.components.timer.condition import CONDITIONS
|
||||
from homeassistant.components.timer.const import (
|
||||
STATUS_ACTIVE,
|
||||
STATUS_IDLE,
|
||||
STATUS_PAUSED,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
from tests.components.common import (
|
||||
|
||||
@@ -22,21 +22,23 @@ from homeassistant.components.timer import (
|
||||
CONF_RESTORE,
|
||||
DEFAULT_DURATION,
|
||||
DOMAIN,
|
||||
SERVICE_CANCEL,
|
||||
SERVICE_CHANGE,
|
||||
SERVICE_FINISH,
|
||||
SERVICE_PAUSE,
|
||||
SERVICE_START,
|
||||
Timer,
|
||||
)
|
||||
from homeassistant.components.timer.const import (
|
||||
EVENT_TIMER_CANCELLED,
|
||||
EVENT_TIMER_CHANGED,
|
||||
EVENT_TIMER_FINISHED,
|
||||
EVENT_TIMER_PAUSED,
|
||||
EVENT_TIMER_RESTARTED,
|
||||
EVENT_TIMER_STARTED,
|
||||
SERVICE_CANCEL,
|
||||
SERVICE_CHANGE,
|
||||
SERVICE_FINISH,
|
||||
SERVICE_PAUSE,
|
||||
SERVICE_START,
|
||||
STATUS_ACTIVE,
|
||||
STATUS_IDLE,
|
||||
STATUS_PAUSED,
|
||||
Timer,
|
||||
)
|
||||
from homeassistant.const import (
|
||||
ATTR_EDITABLE,
|
||||
@@ -1376,7 +1378,7 @@ async def test_restore_active_resume(
|
||||
|
||||
# In patch make sure we ignore microseconds
|
||||
with patch(
|
||||
"homeassistant.components.timer.dt_util.utcnow",
|
||||
"homeassistant.components.timer.entity.dt_util.utcnow",
|
||||
return_value=simulated_utc_now.replace(microsecond=999),
|
||||
):
|
||||
await entity.async_added_to_hass()
|
||||
@@ -1434,7 +1436,8 @@ async def test_restore_active_finished_outside_grace(
|
||||
entity.entity_id = "timer.test"
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.timer.dt_util.utcnow", return_value=simulated_utc_now
|
||||
"homeassistant.components.timer.entity.dt_util.utcnow",
|
||||
return_value=simulated_utc_now,
|
||||
):
|
||||
await entity.async_added_to_hass()
|
||||
await hass.async_block_till_done()
|
||||
|
||||
@@ -8,6 +8,8 @@ from homeassistant.components.timer import (
|
||||
SERVICE_CANCEL,
|
||||
SERVICE_PAUSE,
|
||||
SERVICE_START,
|
||||
)
|
||||
from homeassistant.components.timer.const import (
|
||||
STATUS_ACTIVE,
|
||||
STATUS_IDLE,
|
||||
STATUS_PAUSED,
|
||||
|
||||
@@ -12,6 +12,8 @@ from homeassistant.components.timer import (
|
||||
ATTR_FINISHES_AT,
|
||||
ATTR_LAST_TRANSITION,
|
||||
DOMAIN,
|
||||
)
|
||||
from homeassistant.components.timer.const import (
|
||||
STATUS_ACTIVE,
|
||||
STATUS_IDLE,
|
||||
STATUS_PAUSED,
|
||||
|
||||
Reference in New Issue
Block a user