Add timer_list integration (#183648)

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Paulus Schoutsen <balloob@gmail.com>
This commit is contained in:
Michael Hansen
2026-11-19 17:20:23 -05:00
committed by GitHub
co-authored by Claude Opus 5 Paulus Schoutsen
parent d82644099d
commit cb43b01938
23 changed files with 2189 additions and 0 deletions
+1
View File
@@ -57,6 +57,7 @@ base_platforms: &base_platforms
- homeassistant/components/switch/**
- homeassistant/components/text/**
- homeassistant/components/time/**
- homeassistant/components/timer_list/**
- homeassistant/components/todo/**
- homeassistant/components/tts/**
- homeassistant/components/update/**
+1
View File
@@ -651,6 +651,7 @@ homeassistant.components.tilt_ble.*
homeassistant.components.time.*
homeassistant.components.time_date.*
homeassistant.components.timer.*
homeassistant.components.timer_list.*
homeassistant.components.tod.*
homeassistant.components.todo.*
homeassistant.components.tolo.*
Generated
+2
View File
@@ -2020,6 +2020,8 @@ AGENTS.md @home-assistant/core
/tests/components/time/ @home-assistant/core
/homeassistant/components/time_date/ @fabaff
/tests/components/time_date/ @fabaff
/homeassistant/components/timer_list/ @home-assistant/core @synesthesiam
/tests/components/timer_list/ @home-assistant/core @synesthesiam
/homeassistant/components/tmb/ @alemuro
/homeassistant/components/todo/ @home-assistant/core
/tests/components/todo/ @home-assistant/core
@@ -0,0 +1,100 @@
"""The Timer list integration.
A timer list entity holds many independent countdown timers (its *items*),
mirroring how a to-do list holds many to-do items. The entity state is the
number of active timers. The platform provides the abstract entity, the shared
data model, and the generic services/websocket API; storing timers and
scheduling their completion is left to concrete implementations.
"""
import logging
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import STATE_UNAVAILABLE
from homeassistant.core import (
DOMAIN as HOMEASSISTANT_DOMAIN,
Event,
EventStateChangedData,
HomeAssistant,
callback,
)
from homeassistant.exceptions import ConfigEntryError
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.typing import ConfigType
from .const import (
DATA_COMPONENT,
DOMAIN,
TimerListEntityFeature,
TimerListEventType,
TimerListServices,
TimerStatus,
)
from .entity import TimerItem, TimerListEntity, TimerListEvent
from .services import async_setup_services
from .websocket_api import async_setup as async_setup_websocket_api
__all__ = [
"DOMAIN",
"ENTITY_ID_FORMAT",
"PLATFORM_SCHEMA",
"PLATFORM_SCHEMA_BASE",
"TimerItem",
"TimerListEntity",
"TimerListEntityFeature",
"TimerListEvent",
"TimerListEventType",
"TimerListServices",
"TimerStatus",
]
_LOGGER = logging.getLogger(__name__)
ENTITY_ID_FORMAT = DOMAIN + ".{}"
PLATFORM_SCHEMA = cv.PLATFORM_SCHEMA
PLATFORM_SCHEMA_BASE = cv.PLATFORM_SCHEMA_BASE
@callback
def entity_became_available(event: Event[EventStateChangedData]) -> bool:
"""Return True if a state change means the entity is newly usable.
A config entry reload builds a new entity object but leaves its registry
entry alone, so this transition is the only signal that subscriptions held
against the old object are now dangling.
"""
new_state = event.data["new_state"]
old_state = event.data["old_state"]
if new_state is None or new_state.state == STATE_UNAVAILABLE:
return False
return old_state is None or old_state.state == STATE_UNAVAILABLE
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the Timer list component."""
component = hass.data[DATA_COMPONENT] = EntityComponent[TimerListEntity](
_LOGGER, DOMAIN, hass
)
async_setup_websocket_api(hass)
async_setup_services(hass)
await component.async_setup(config)
return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Set up a config entry."""
if not await hass.data[DATA_COMPONENT].async_setup_entry(entry):
raise ConfigEntryError(
translation_domain=HOMEASSISTANT_DOMAIN,
translation_key="platform_setup_failed",
translation_placeholders={"platform": entry.domain, "domain": DOMAIN},
)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Unload a config entry."""
await hass.data[DATA_COMPONENT].async_unload_entry(entry)
@@ -0,0 +1,74 @@
"""Constants for the Timer list integration."""
from enum import IntFlag, StrEnum
from typing import TYPE_CHECKING
from homeassistant.util.hass_dict import HassKey
if TYPE_CHECKING:
from homeassistant.helpers.entity_component import EntityComponent
from .entity import TimerListEntity
DOMAIN = "timer_list"
DATA_COMPONENT: HassKey[EntityComponent[TimerListEntity]] = HassKey(DOMAIN)
ATTR_TIMER_ID = "timer_id"
ATTR_DURATION = "duration"
ATTR_CREATED_DURATION = "created_duration"
ATTR_TOTAL_DURATION = "total_duration"
ATTR_DELTA = "delta"
ATTR_FINISHES_AT = "finishes_at"
ATTR_CREATED_AT = "created_at"
ATTR_ENDED_AT = "ended_at"
ATTR_REMAINING = "remaining"
ATTR_PAUSED_REMAINING = "paused_remaining"
ATTR_STATUS = "status"
ATTR_TIMER = "timer"
ATTR_TIMERS = "timers"
class TimerListServices(StrEnum):
"""Services for the Timer list integration."""
CREATE_TIMER = "create_timer"
PAUSE_TIMER = "pause_timer"
UNPAUSE_TIMER = "unpause_timer"
CANCEL_TIMER = "cancel_timer"
FINISH_TIMER = "finish_timer"
ADD_TIME = "add_time"
SUBTRACT_TIME = "subtract_time"
REMOVE_TIMER = "remove_timer"
GET_TIMERS = "get_timers"
class TimerStatus(StrEnum):
"""Status of a single timer in a timer list."""
ACTIVE = "active"
PAUSED = "paused"
FINISHED = "finished"
CANCELLED = "cancelled"
class TimerListEventType(StrEnum):
"""Type of change pushed to timer list subscribers."""
CREATED = "created"
PAUSED = "paused"
UNPAUSED = "unpaused"
TIME_CHANGED = "time_changed"
FINISHED = "finished"
CANCELLED = "cancelled"
REMOVED = "removed"
class TimerListEntityFeature(IntFlag):
"""Supported features of a timer list entity."""
CREATE_TIMER = 1
PAUSE_TIMER = 2
CANCEL_TIMER = 4
ADD_TIME = 8
REMOVE_TIMER = 16
FINISH_TIMER = 32
@@ -0,0 +1,252 @@
"""Entities for timer lists."""
from collections.abc import Callable
import copy
import dataclasses
from datetime import datetime, timedelta
from typing import Any, final, override
from homeassistant.const import ATTR_NAME
from homeassistant.core import CALLBACK_TYPE, callback
from homeassistant.helpers.entity import Entity
from .const import (
ATTR_CREATED_AT,
ATTR_CREATED_DURATION,
ATTR_ENDED_AT,
ATTR_FINISHES_AT,
ATTR_PAUSED_REMAINING,
ATTR_REMAINING,
ATTR_STATUS,
ATTR_TIMER_ID,
ATTR_TOTAL_DURATION,
TimerListEventType,
TimerStatus,
)
@dataclasses.dataclass
class TimerItem:
"""A single timer within a timer list."""
timer_id: str
"""Generated unique id of the timer."""
name: str | None
"""Optional user-provided name."""
status: TimerStatus
"""Current status of the timer."""
created_duration: timedelta
"""Duration the timer was created with. Never changes.
This is what voice commands disambiguate on, so "the 5 minute timer" keeps
referring to the same timer after time is added to it. For how long the
timer currently runs for, use ``total_duration``.
"""
created_at: datetime
"""When the timer was created, in UTC. Never changes."""
total_duration: timedelta = timedelta(0)
"""Longest the timer has ever had left to run, i.e. the denominator for a
progress display. Raised (never lowered) as time is added, and never less
than ``created_duration``."""
finishes_at: datetime | None = None
"""Absolute time the timer will finish, in UTC. ``None`` unless active."""
paused_remaining: timedelta | None = None
"""Time left frozen at the moment of pausing. ``None`` unless paused."""
ended_at: datetime | None = None
"""When the timer finished or was cancelled, in UTC. ``None`` until then."""
def __post_init__(self) -> None:
"""Start the progress total at the created duration."""
self.total_duration = max(self.total_duration, self.created_duration)
def remaining_at(self, now: datetime) -> timedelta:
"""Return the time left on the timer relative to ``now``."""
if self.status == TimerStatus.ACTIVE and self.finishes_at is not None:
return max(timedelta(0), self.finishes_at - now)
if self.status == TimerStatus.PAUSED and self.paused_remaining is not None:
return self.paused_remaining
return timedelta(0)
def as_dict(self, now: datetime) -> dict[str, Any]:
"""Serialize the timer at the supplied time."""
return {
ATTR_TIMER_ID: self.timer_id,
ATTR_NAME: self.name,
ATTR_STATUS: self.status.value,
ATTR_CREATED_DURATION: self.created_duration.total_seconds(),
ATTR_TOTAL_DURATION: self.total_duration.total_seconds(),
ATTR_CREATED_AT: self.created_at.isoformat(),
ATTR_FINISHES_AT: self.finishes_at.isoformat()
if self.finishes_at
else None,
ATTR_PAUSED_REMAINING: (
self.paused_remaining.total_seconds()
if self.paused_remaining is not None
else None
),
ATTR_ENDED_AT: self.ended_at.isoformat() if self.ended_at else None,
ATTR_REMAINING: self.remaining_at(now).total_seconds(),
}
@dataclasses.dataclass(frozen=True)
class TimerListEvent:
"""A change to a timer, pushed to subscribers and triggers."""
event_type: TimerListEventType
item: TimerItem
delta: timedelta | None = None
"""Signed amount of time added, for ``TIME_CHANGED``. ``None`` otherwise."""
class TimerListEntity(Entity):
"""An entity that holds a list of independent countdown timers.
This base class only provides the event/listener plumbing shared by the
websocket API and triggers. Concrete implementations are responsible for
storing timers and scheduling their completion.
Subclasses own the timers, wherever they live: in memory, on a device, or
behind a remote API. A subclass always keeps a local copy of them, because
``timers`` and ``state`` are read synchronously and cannot wait on a remote.
Every action method takes a timer id and must, unless noted otherwise:
- raise ``ServiceValidationError`` with this integration's
``timer_not_found`` translation key for an unknown id, so every backend
reports one identically;
- do nothing at all if the timer is already ``finished`` or ``cancelled``,
or is otherwise in a state the action does not apply to, rather than
raising or emitting an event;
- emit exactly one event via ``_notify`` when it does change something.
Voice intents call these methods directly and do not check
``supported_features``, so an action may be invoked on an entity that does
not advertise it.
"""
_attr_should_poll = False
def __init__(self) -> None:
"""Initialize the timer list."""
self._update_listeners: list[Callable[[TimerListEvent], None]] = []
@property
@override
def state(self) -> int:
"""Return the number of active timers."""
return sum(timer.status == TimerStatus.ACTIVE for timer in self.timers)
@property
def timers(self) -> list[TimerItem]:
"""Return the timers in the list.
Includes archived (``finished`` and ``cancelled``) timers, which the
websocket API and ``get_timers`` report. Voice commands only ever
consider active and paused timers.
"""
raise NotImplementedError
async def async_create_timer(self, *, name: str | None, duration: timedelta) -> str:
"""Create a new timer, returning its id.
The timer starts counting down immediately; there is no created-but-not
-running state. Emits ``CREATED``.
"""
raise NotImplementedError
async def async_pause_timer(self, timer_id: str) -> None:
"""Pause an active timer, emitting ``PAUSED``.
Does nothing if the timer is not currently ``active``. The time left
must be frozen in ``paused_remaining`` so it survives the pause.
"""
raise NotImplementedError
async def async_unpause_timer(self, timer_id: str) -> None:
"""Resume a paused timer, emitting ``UNPAUSED``.
Does nothing if the timer is not currently ``paused``.
"""
raise NotImplementedError
async def async_cancel_timer(self, timer_id: str) -> None:
"""Cancel a timer without finishing it, emitting ``CANCELLED``.
The timer stays in the list as ``cancelled`` with ``ended_at`` set. No
``FINISHED`` event is emitted, so satellites stay silent.
"""
raise NotImplementedError
async def async_finish_timer(self, timer_id: str) -> None:
"""Finish a timer early, as if its remaining time had elapsed.
Emits ``FINISHED``, so satellites ring, and leaves the timer in the
list as ``finished`` with ``ended_at`` set. Applies to paused timers
too. ``FINISHED`` therefore does not imply the full duration elapsed.
"""
raise NotImplementedError
async def async_add_time(self, timer_id: str, duration: timedelta) -> None:
"""Add (or, with a negative duration, subtract) time on a timer.
Emits ``TIME_CHANGED`` carrying ``duration`` as the event's signed
``delta``. ``created_duration`` must not change, and ``total_duration``
must be raised so it stays at least the new remaining time. Subtracting
more than is left finishes the timer instead, emitting ``FINISHED``,
whether it was active or paused. A zero ``duration`` changes nothing
and emits no event.
"""
raise NotImplementedError
async def async_remove_timer(self, timer_id: str) -> None:
"""Remove a timer from the list regardless of its status.
Emits ``REMOVED``. Implementations may also emit it unprompted when
evicting old archived timers, so subscribers must tolerate it for a
timer they did not ask to remove.
"""
raise NotImplementedError
@final
@callback
def async_subscribe_updates(
self, listener: Callable[[TimerListEvent], None]
) -> CALLBACK_TYPE:
"""Subscribe to timer change events.
Only future changes are pushed; the current set of timers is not
replayed on subscribe.
"""
self._update_listeners.append(listener)
@callback
def unsubscribe() -> None:
self._update_listeners.remove(listener)
return unsubscribe
@final
@callback
def _notify(
self,
event_type: TimerListEventType,
timer: TimerItem,
delta: timedelta | None = None,
) -> None:
"""Push a change event to subscribers and write entity state."""
event = TimerListEvent(
event_type=event_type, item=copy.copy(timer), delta=delta
)
self.async_write_ha_state()
for listener in list(self._update_listeners):
listener(event)
@@ -0,0 +1,56 @@
{
"entity_component": {
"_": {
"default": "mdi:timer-outline"
}
},
"services": {
"add_time": {
"service": "mdi:timer-plus-outline"
},
"cancel_timer": {
"service": "mdi:timer-cancel-outline"
},
"create_timer": {
"service": "mdi:timer-plus-outline"
},
"finish_timer": {
"service": "mdi:timer-check-outline"
},
"get_timers": {
"service": "mdi:timer-outline"
},
"pause_timer": {
"service": "mdi:timer-pause-outline"
},
"remove_timer": {
"service": "mdi:timer-remove-outline"
},
"subtract_time": {
"service": "mdi:timer-minus-outline"
},
"unpause_timer": {
"service": "mdi:timer-play-outline"
}
},
"triggers": {
"timer_cancelled": {
"trigger": "mdi:timer-cancel-outline"
},
"timer_created": {
"trigger": "mdi:timer-play-outline"
},
"timer_finished": {
"trigger": "mdi:timer-check-outline"
},
"timer_paused": {
"trigger": "mdi:timer-pause-outline"
},
"timer_time_changed": {
"trigger": "mdi:timer-edit-outline"
},
"timer_unpaused": {
"trigger": "mdi:timer-play-outline"
}
}
}
@@ -0,0 +1,9 @@
{
"domain": "timer_list",
"name": "Timer list",
"codeowners": ["@home-assistant/core", "@synesthesiam"],
"dependencies": ["websocket_api"],
"documentation": "https://www.home-assistant.io/integrations/timer_list",
"integration_type": "entity",
"quality_scale": "internal"
}
@@ -0,0 +1,133 @@
"""Actions for timer lists."""
from typing import Any
import probatio
from homeassistant.const import ATTR_NAME
from homeassistant.core import HomeAssistant, ServiceCall, SupportsResponse, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.util import dt as dt_util
from .const import (
ATTR_DURATION,
ATTR_STATUS,
ATTR_TIMER_ID,
ATTR_TIMERS,
DATA_COMPONENT,
TimerListEntityFeature,
TimerListServices,
TimerStatus,
)
from .entity import TimerListEntity
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Set up timer list actions."""
component = hass.data[DATA_COMPONENT]
component.async_register_entity_service(
TimerListServices.CREATE_TIMER,
{
probatio.Optional(ATTR_NAME): cv.string,
probatio.Required(ATTR_DURATION): cv.positive_time_period,
},
_async_create_timer,
required_features=[TimerListEntityFeature.CREATE_TIMER],
supports_response=SupportsResponse.OPTIONAL,
)
component.async_register_entity_service(
TimerListServices.PAUSE_TIMER,
{probatio.Required(ATTR_TIMER_ID): cv.string},
"async_pause_timer",
required_features=[TimerListEntityFeature.PAUSE_TIMER],
)
component.async_register_entity_service(
TimerListServices.UNPAUSE_TIMER,
{probatio.Required(ATTR_TIMER_ID): cv.string},
"async_unpause_timer",
required_features=[TimerListEntityFeature.PAUSE_TIMER],
)
component.async_register_entity_service(
TimerListServices.CANCEL_TIMER,
{probatio.Required(ATTR_TIMER_ID): cv.string},
"async_cancel_timer",
required_features=[TimerListEntityFeature.CANCEL_TIMER],
)
component.async_register_entity_service(
TimerListServices.FINISH_TIMER,
{probatio.Required(ATTR_TIMER_ID): cv.string},
"async_finish_timer",
required_features=[TimerListEntityFeature.FINISH_TIMER],
)
component.async_register_entity_service(
TimerListServices.ADD_TIME,
{
probatio.Required(ATTR_TIMER_ID): cv.string,
probatio.Required(ATTR_DURATION): cv.positive_time_period,
},
_async_add_time,
required_features=[TimerListEntityFeature.ADD_TIME],
)
component.async_register_entity_service(
TimerListServices.SUBTRACT_TIME,
{
probatio.Required(ATTR_TIMER_ID): cv.string,
probatio.Required(ATTR_DURATION): cv.positive_time_period,
},
_async_subtract_time,
required_features=[TimerListEntityFeature.ADD_TIME],
)
component.async_register_entity_service(
TimerListServices.REMOVE_TIMER,
{probatio.Required(ATTR_TIMER_ID): cv.string},
"async_remove_timer",
required_features=[TimerListEntityFeature.REMOVE_TIMER],
)
component.async_register_entity_service(
TimerListServices.GET_TIMERS,
{
probatio.Optional(ATTR_STATUS): probatio.All(
probatio.EnsureList(), [probatio.Coerce(TimerStatus)]
)
},
_async_get_timers,
supports_response=SupportsResponse.ONLY,
)
async def _async_create_timer(
entity: TimerListEntity, call: ServiceCall
) -> dict[str, Any]:
"""Handle the create_timer service."""
timer_id = await entity.async_create_timer(
name=call.data.get(ATTR_NAME),
duration=call.data[ATTR_DURATION],
)
return {ATTR_TIMER_ID: timer_id}
async def _async_add_time(entity: TimerListEntity, call: ServiceCall) -> None:
"""Handle the add_time service."""
await entity.async_add_time(call.data[ATTR_TIMER_ID], call.data[ATTR_DURATION])
async def _async_subtract_time(entity: TimerListEntity, call: ServiceCall) -> None:
"""Handle the subtract_time service."""
await entity.async_add_time(call.data[ATTR_TIMER_ID], -call.data[ATTR_DURATION])
async def _async_get_timers(
entity: TimerListEntity, call: ServiceCall
) -> dict[str, Any]:
"""Handle the get_timers service."""
now = dt_util.utcnow()
statuses: list[TimerStatus] | None = call.data.get(ATTR_STATUS)
return {
ATTR_TIMERS: [
timer.as_dict(now)
for timer in entity.timers
if not statuses or timer.status in statuses
]
}
@@ -0,0 +1,126 @@
create_timer:
target:
entity:
domain: timer_list
supported_features:
- timer_list.TimerListEntityFeature.CREATE_TIMER
fields:
name:
example: "Pasta"
selector:
text:
duration:
required: true
example: "00:05:00"
selector:
duration:
pause_timer:
target:
entity:
domain: timer_list
supported_features:
- timer_list.TimerListEntityFeature.PAUSE_TIMER
fields:
timer_id:
required: true
example: "01HZ8ABCDEF0123456789ABCDE"
selector:
text:
unpause_timer:
target:
entity:
domain: timer_list
supported_features:
- timer_list.TimerListEntityFeature.PAUSE_TIMER
fields:
timer_id:
required: true
example: "01HZ8ABCDEF0123456789ABCDE"
selector:
text:
cancel_timer:
target:
entity:
domain: timer_list
supported_features:
- timer_list.TimerListEntityFeature.CANCEL_TIMER
fields:
timer_id:
required: true
example: "01HZ8ABCDEF0123456789ABCDE"
selector:
text:
finish_timer:
target:
entity:
domain: timer_list
supported_features:
- timer_list.TimerListEntityFeature.FINISH_TIMER
fields:
timer_id:
required: true
example: "01HZ8ABCDEF0123456789ABCDE"
selector:
text:
add_time:
target:
entity:
domain: timer_list
supported_features:
- timer_list.TimerListEntityFeature.ADD_TIME
fields:
timer_id:
required: true
example: "01HZ8ABCDEF0123456789ABCDE"
selector:
text:
duration:
required: true
example: "00:01:00"
selector:
duration:
subtract_time:
target:
entity:
domain: timer_list
supported_features:
- timer_list.TimerListEntityFeature.ADD_TIME
fields:
timer_id:
required: true
example: "01HZ8ABCDEF0123456789ABCDE"
selector:
text:
duration:
required: true
example: "00:01:00"
selector:
duration:
remove_timer:
target:
entity:
domain: timer_list
supported_features:
- timer_list.TimerListEntityFeature.REMOVE_TIMER
fields:
timer_id:
required: true
example: "01HZ8ABCDEF0123456789ABCDE"
selector:
text:
get_timers:
target:
entity:
domain: timer_list
fields:
status:
example: "active"
selector:
select:
translation_key: status
multiple: true
options:
- active
- paused
- finished
- cancelled
@@ -0,0 +1,153 @@
{
"entity_component": {
"_": {
"name": "[%key:component::timer_list::title%]"
}
},
"exceptions": {
"timer_not_found": {
"message": "Unable to find timer with id: {timer_id}"
}
},
"selector": {
"status": {
"options": {
"active": "Active",
"cancelled": "Cancelled",
"finished": "Finished",
"paused": "Paused"
}
}
},
"services": {
"add_time": {
"description": "Adds time to a timer.",
"fields": {
"duration": {
"description": "How much time to add to the timer.",
"name": "Duration"
},
"timer_id": {
"description": "The id of the timer to add time to.",
"name": "Timer ID"
}
},
"name": "Add time"
},
"cancel_timer": {
"description": "Cancels a timer without finishing it.",
"fields": {
"timer_id": {
"description": "The id of the timer to cancel.",
"name": "Timer ID"
}
},
"name": "Cancel timer"
},
"create_timer": {
"description": "Creates a new timer on a timer list and starts it counting down.",
"fields": {
"duration": {
"description": "How long the timer should run for.",
"name": "Duration"
},
"name": {
"description": "Optional name for the timer.",
"name": "Name"
}
},
"name": "Create timer"
},
"finish_timer": {
"description": "Finishes a timer early, as if its remaining time had elapsed.",
"fields": {
"timer_id": {
"description": "The id of the timer to finish.",
"name": "Timer ID"
}
},
"name": "Finish timer"
},
"get_timers": {
"description": "Gets the timers on a timer list.",
"fields": {
"status": {
"description": "Only return timers with the specified statuses.",
"name": "Status"
}
},
"name": "Get timers"
},
"pause_timer": {
"description": "Pauses an active timer.",
"fields": {
"timer_id": {
"description": "The id of the timer to pause.",
"name": "Timer ID"
}
},
"name": "Pause timer"
},
"remove_timer": {
"description": "Removes a timer from a timer list.",
"fields": {
"timer_id": {
"description": "The id of the timer to remove.",
"name": "Timer ID"
}
},
"name": "Remove timer"
},
"subtract_time": {
"description": "Subtracts time from a timer.",
"fields": {
"duration": {
"description": "How much time to subtract from the timer.",
"name": "Duration"
},
"timer_id": {
"description": "The id of the timer to subtract time from.",
"name": "Timer ID"
}
},
"name": "Subtract time"
},
"unpause_timer": {
"description": "Resumes a paused timer.",
"fields": {
"timer_id": {
"description": "The id of the timer to resume.",
"name": "Timer ID"
}
},
"name": "Resume timer"
}
},
"title": "Timer list",
"triggers": {
"timer_cancelled": {
"description": "Triggers when a timer is cancelled on a timer list.",
"name": "Timer cancelled"
},
"timer_created": {
"description": "Triggers when a timer is created on a timer list.",
"name": "Timer created"
},
"timer_finished": {
"description": "Triggers when a timer finishes on a timer list.",
"name": "Timer finished"
},
"timer_paused": {
"description": "Triggers when a timer is paused on a timer list.",
"name": "Timer paused"
},
"timer_time_changed": {
"description": "Triggers when time is added to or subtracted from a timer on a timer list.",
"name": "Timer time changed"
},
"timer_unpaused": {
"description": "Triggers when a timer is resumed on a timer list.",
"name": "Timer resumed"
}
}
}
@@ -0,0 +1,211 @@
"""Provides triggers for timer lists."""
from collections.abc import Callable
from functools import partial
from typing import TYPE_CHECKING, Any, cast, override
import probatio
from homeassistant.const import ATTR_ENTITY_ID, CONF_OPTIONS, CONF_TARGET
from homeassistant.core import (
CALLBACK_TYPE,
Event,
EventStateChangedData,
HomeAssistant,
callback,
split_entity_id,
)
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.event import async_track_state_change_event
from homeassistant.helpers.target import TargetEntityChangeTracker, TargetSelection
from homeassistant.helpers.trigger import (
Trigger,
TriggerActionRunner,
TriggerConfig,
TriggerNotTriggeredReporter,
)
from homeassistant.helpers.typing import ConfigType
from homeassistant.util import dt as dt_util
from . import entity_became_available
from .const import ATTR_DELTA, ATTR_TIMER, DATA_COMPONENT, DOMAIN, TimerListEventType
from .entity import TimerListEvent
TRIGGER_SCHEMA = probatio.Schema(
{
probatio.Required(CONF_TARGET): cv.TARGET_FIELDS,
probatio.Required(CONF_OPTIONS, default={}): {},
}
)
class TimerEventListener(TargetEntityChangeTracker):
"""Subscribe to timer change events for the targeted timer list entities."""
def __init__(
self,
hass: HomeAssistant,
target_selection: TargetSelection,
listener: Callable[[str, TimerListEvent], None],
) -> None:
"""Initialize the listener."""
def entity_filter(entities: set[str]) -> set[str]:
return {
entity_id
for entity_id in entities
if split_entity_id(entity_id)[0] == DOMAIN
}
super().__init__(hass, target_selection, entity_filter)
self._listener = listener
self._unsubscribe_listeners: list[CALLBACK_TYPE] = []
self._state_change_unsub: CALLBACK_TYPE | None = None
@override
@callback
def _handle_entities_update(self, tracked_entities: set[str]) -> None:
"""Resubscribe when the set of tracked entities changes."""
for unsub in self._unsubscribe_listeners:
unsub()
self._unsubscribe_listeners = []
component = self._hass.data[DATA_COMPONENT]
for entity_id in tracked_entities:
if (entity := component.get_entity(entity_id)) is None:
continue
self._unsubscribe_listeners.append(
entity.async_subscribe_updates(partial(self._listener, entity_id))
)
if self._state_change_unsub:
self._state_change_unsub()
self._state_change_unsub = None
if tracked_entities:
self._state_change_unsub = async_track_state_change_event(
self._hass, tracked_entities, self._async_entity_state_changed
)
@callback
def _async_entity_state_changed(self, event: Event[EventStateChangedData]) -> None:
"""Resubscribe when a targeted entity becomes available.
Covers a list added after this trigger, whose registry entry exists
before the component can resolve the entity, and a reloaded config
entry, which swaps in a new entity object while leaving the registry
entry alone: nothing else would tell us the subscriptions above now
point at a discarded object.
"""
if entity_became_available(event):
self._handle_target_update()
@override
@callback
def _unsubscribe(self) -> None:
"""Unsubscribe from all events."""
super()._unsubscribe()
for unsub in self._unsubscribe_listeners:
unsub()
self._unsubscribe_listeners = []
if self._state_change_unsub:
self._state_change_unsub()
self._state_change_unsub = None
class TimerEventTrigger(Trigger):
"""Trigger that fires on a specific timer change event type."""
_event_type: TimerListEventType
@override
@classmethod
async def async_validate_config(
cls, hass: HomeAssistant, config: ConfigType
) -> ConfigType:
"""Validate config."""
return cast(ConfigType, TRIGGER_SCHEMA(config))
def __init__(self, hass: HomeAssistant, config: TriggerConfig) -> None:
"""Initialize the trigger."""
super().__init__(hass, config)
if TYPE_CHECKING:
assert config.target is not None
self._target = config.target
@override
async def async_attach_runner(
self,
run_action: TriggerActionRunner,
did_not_trigger: TriggerNotTriggeredReporter | None = None,
) -> CALLBACK_TYPE:
"""Attach the trigger to an action runner."""
target_selection = TargetSelection(self._target)
if not target_selection.has_any_target:
raise HomeAssistantError(f"No target defined in {self._target}")
@callback
def handle_event(entity_id: str, event: TimerListEvent) -> None:
if event.event_type != self._event_type:
return
variables: dict[str, Any] = {
ATTR_ENTITY_ID: entity_id,
ATTR_TIMER: event.item.as_dict(dt_util.utcnow()),
}
if event.delta is not None:
variables[ATTR_DELTA] = event.delta.total_seconds()
run_action(variables, f"timer {self._event_type.value} on {entity_id}")
listener = TimerEventListener(self._hass, target_selection, handle_event)
return await listener.async_setup()
class TimerCreatedTrigger(TimerEventTrigger):
"""Trigger when a timer is created."""
_event_type = TimerListEventType.CREATED
class TimerPausedTrigger(TimerEventTrigger):
"""Trigger when a timer is paused."""
_event_type = TimerListEventType.PAUSED
class TimerUnpausedTrigger(TimerEventTrigger):
"""Trigger when a timer is resumed."""
_event_type = TimerListEventType.UNPAUSED
class TimerTimeChangedTrigger(TimerEventTrigger):
"""Trigger when time is added to or subtracted from a timer."""
_event_type = TimerListEventType.TIME_CHANGED
class TimerFinishedTrigger(TimerEventTrigger):
"""Trigger when a timer finishes."""
_event_type = TimerListEventType.FINISHED
class TimerCancelledTrigger(TimerEventTrigger):
"""Trigger when a timer is cancelled."""
_event_type = TimerListEventType.CANCELLED
TRIGGERS: dict[str, type[Trigger]] = {
"timer_created": TimerCreatedTrigger,
"timer_paused": TimerPausedTrigger,
"timer_unpaused": TimerUnpausedTrigger,
"timer_time_changed": TimerTimeChangedTrigger,
"timer_finished": TimerFinishedTrigger,
"timer_cancelled": TimerCancelledTrigger,
}
async def async_get_triggers(hass: HomeAssistant) -> dict[str, type[Trigger]]:
"""Return the triggers for timer lists."""
return TRIGGERS
@@ -0,0 +1,11 @@
.trigger_common: &trigger_common
target:
entity:
domain: timer_list
timer_created: *trigger_common
timer_paused: *trigger_common
timer_unpaused: *trigger_common
timer_time_changed: *trigger_common
timer_finished: *trigger_common
timer_cancelled: *trigger_common
@@ -0,0 +1,110 @@
"""WebSocket commands for timer lists."""
from typing import Any
import probatio
from homeassistant.auth.permissions.const import POLICY_READ
from homeassistant.components import websocket_api
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import Unauthorized
from homeassistant.helpers import config_validation as cv
from homeassistant.util import dt as dt_util
from .const import ATTR_DELTA, ATTR_TIMERS, DATA_COMPONENT, DOMAIN
from .entity import TimerListEvent
@callback
def async_setup(hass: HomeAssistant) -> None:
"""Register timer list WebSocket commands."""
websocket_api.async_register_command(hass, websocket_handle_subscribe)
websocket_api.async_register_command(hass, websocket_handle_list)
@websocket_api.websocket_command(
{
probatio.Required("type"): "timer_list/item/subscribe",
probatio.Required("entity_id"): cv.entity_domain(DOMAIN),
}
)
@websocket_api.async_response
async def websocket_handle_subscribe(
hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any]
) -> None:
"""Subscribe to timer changes for a timer list, with an initial snapshot."""
entity_id: str = msg["entity_id"]
if not connection.user.permissions.check_entity(entity_id, POLICY_READ):
raise Unauthorized(entity_id=entity_id)
if not (entity := hass.data[DATA_COMPONENT].get_entity(entity_id)):
connection.send_error(
msg["id"],
websocket_api.ERR_NOT_FOUND,
f"Timer list entity not found: {entity_id}",
)
return
if not entity.available:
connection.send_error(
msg["id"],
websocket_api.ERR_HOME_ASSISTANT_ERROR,
f"Timer list entity is unavailable: {entity_id}",
)
return
@callback
def forward_event(event: TimerListEvent) -> None:
"""Forward a timer change event to the websocket connection."""
message: dict[str, Any] = {
"type": "change",
"event_type": event.event_type.value,
"timer": event.item.as_dict(dt_util.utcnow()),
}
if event.delta is not None:
message[ATTR_DELTA] = event.delta.total_seconds()
connection.send_message(websocket_api.event_message(msg["id"], message))
connection.subscriptions[msg["id"]] = entity.async_subscribe_updates(forward_event)
connection.send_result(msg["id"])
now = dt_util.utcnow()
connection.send_message(
websocket_api.event_message(
msg["id"],
{
"type": "timers",
ATTR_TIMERS: [timer.as_dict(now) for timer in entity.timers],
},
)
)
@websocket_api.websocket_command(
{
probatio.Required("type"): "timer_list/item/list",
probatio.Required("entity_id"): cv.entity_domain(DOMAIN),
}
)
@websocket_api.async_response
async def websocket_handle_list(
hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any]
) -> None:
"""Return the current timers for a timer list."""
entity_id: str = msg["entity_id"]
if not connection.user.permissions.check_entity(entity_id, POLICY_READ):
raise Unauthorized(entity_id=entity_id)
if not (entity := hass.data[DATA_COMPONENT].get_entity(entity_id)):
connection.send_error(
msg["id"],
websocket_api.ERR_NOT_FOUND,
f"Timer list entity not found: {entity_id}",
)
return
now = dt_util.utcnow()
connection.send_result(
msg["id"],
{ATTR_TIMERS: [timer.as_dict(now) for timer in entity.timers]},
)
+1
View File
@@ -46,6 +46,7 @@ class EntityPlatforms(StrEnum):
SWITCH = "switch"
TEXT = "text"
TIME = "time"
TIMER_LIST = "timer_list"
TODO = "todo"
TTS = "tts"
UPDATE = "update"
Generated
+10
View File
@@ -6264,6 +6264,16 @@ disallow_untyped_defs = true
warn_return_any = true
warn_unreachable = true
[mypy-homeassistant.components.timer_list.*]
check_untyped_defs = true
disallow_incomplete_defs = true
disallow_subclassing_any = true
disallow_untyped_calls = true
disallow_untyped_decorators = true
disallow_untyped_defs = true
warn_return_any = true
warn_unreachable = true
[mypy-homeassistant.components.tod.*]
check_untyped_defs = true
disallow_incomplete_defs = true
@@ -81,6 +81,7 @@ _MODULES: dict[str, set[str]] = {
Platform.SWITCH: {"SwitchEntity", "SwitchEntityDescription"},
Platform.TEXT: {"TextEntity", "TextEntityDescription"},
Platform.TIME: {"TimeEntity", "TimeEntityDescription"},
Platform.TIMER_LIST: {"TimerListEntity"},
Platform.TODO: {"TodoListEntity"},
Platform.TTS: {"TextToSpeechEntity"},
Platform.UPDATE: {"UpdateEntity", "UpdateEntityDescription"},
@@ -47,6 +47,7 @@ class Platform(StrEnum):
SWITCH = "switch"
TEXT = "text"
TIME = "time"
TIMER_LIST = "timer_list"
TODO = "todo"
TTS = "tts"
UPDATE = "update"
+167
View File
@@ -0,0 +1,167 @@
"""Tests for the Timer list integration."""
from datetime import timedelta
from pytest_homeassistant.common import MockConfigEntry, MockPlatform, mock_platform
from homeassistant.components.timer_list import DOMAIN, TimerItem, TimerListEntity
from homeassistant.components.timer_list.const import (
TimerListEntityFeature,
TimerListEventType,
TimerStatus,
)
from homeassistant.config_entries import ConfigEntry, ConfigFlow
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.util import dt as dt_util, ulid as ulid_util
TEST_DOMAIN = "test"
_ARCHIVE_EVENTS = {
TimerStatus.FINISHED: TimerListEventType.FINISHED,
TimerStatus.CANCELLED: TimerListEventType.CANCELLED,
}
class MockFlow(ConfigFlow):
"""Test flow."""
class MockTimerListEntity(TimerListEntity):
"""A minimal timer list, standing in for a real provider.
Implements just enough of the entity contract to drive the platform's
services, websocket API and triggers. It deliberately does not schedule
anything: where timers are stored and when they elapse belongs to a
concrete implementation, so these tests stay about the base platform.
"""
_attr_supported_features = (
TimerListEntityFeature.CREATE_TIMER
| TimerListEntityFeature.PAUSE_TIMER
| TimerListEntityFeature.CANCEL_TIMER
| TimerListEntityFeature.FINISH_TIMER
| TimerListEntityFeature.ADD_TIME
| TimerListEntityFeature.REMOVE_TIMER
)
def __init__(self, name: str = "Timers") -> None:
"""Initialize entity."""
super().__init__()
self._attr_name = name
self._attr_unique_id = ulid_util.ulid_now()
self._timers: dict[str, TimerItem] = {}
@property
def timers(self) -> list[TimerItem]:
"""Return the timers in the list."""
return list(self._timers.values())
def _get_timer(self, timer_id: str) -> TimerItem:
"""Return a timer by id or raise if it does not exist."""
if (timer := self._timers.get(timer_id)) is None:
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="timer_not_found",
translation_placeholders={"timer_id": timer_id},
)
return timer
async def async_create_timer(self, *, name: str | None, duration: timedelta) -> str:
"""Create a new timer, returning its id."""
now = dt_util.utcnow()
timer = TimerItem(
timer_id=ulid_util.ulid_now(),
name=name,
status=TimerStatus.ACTIVE,
created_duration=duration,
created_at=now,
finishes_at=now + duration,
)
self._timers[timer.timer_id] = timer
self._notify(TimerListEventType.CREATED, timer)
return timer.timer_id
async def async_pause_timer(self, timer_id: str) -> None:
"""Pause an active timer."""
timer = self._get_timer(timer_id)
timer.paused_remaining = timer.remaining_at(dt_util.utcnow())
timer.finishes_at = None
timer.status = TimerStatus.PAUSED
self._notify(TimerListEventType.PAUSED, timer)
async def async_unpause_timer(self, timer_id: str) -> None:
"""Resume a paused timer."""
timer = self._get_timer(timer_id)
timer.finishes_at = dt_util.utcnow() + (timer.paused_remaining or timedelta(0))
timer.paused_remaining = None
timer.status = TimerStatus.ACTIVE
self._notify(TimerListEventType.UNPAUSED, timer)
async def async_cancel_timer(self, timer_id: str) -> None:
"""Cancel a timer, archiving it in the ``cancelled`` state."""
self._archive(self._get_timer(timer_id), TimerStatus.CANCELLED)
async def async_finish_timer(self, timer_id: str) -> None:
"""Finish a timer, archiving it in the ``finished`` state."""
self._archive(self._get_timer(timer_id), TimerStatus.FINISHED)
async def async_add_time(self, timer_id: str, duration: timedelta) -> None:
"""Add (or, with a negative duration, subtract) time on a timer."""
timer = self._get_timer(timer_id)
if timer.status not in (TimerStatus.ACTIVE, TimerStatus.PAUSED) or not duration:
return
now = dt_util.utcnow()
remaining = timer.remaining_at(now) + duration
if remaining <= timedelta(0):
self._archive(timer, TimerStatus.FINISHED)
return
if timer.status == TimerStatus.PAUSED:
timer.paused_remaining = remaining
else:
timer.finishes_at = now + remaining
timer.total_duration = max(timer.total_duration, remaining)
self._notify(TimerListEventType.TIME_CHANGED, timer, delta=duration)
async def async_remove_timer(self, timer_id: str) -> None:
"""Remove a timer from the list regardless of its status."""
timer = self._get_timer(timer_id)
del self._timers[timer_id]
self._notify(TimerListEventType.REMOVED, timer)
def _archive(self, timer: TimerItem, status: TimerStatus) -> None:
"""Move a timer to a terminal status and notify subscribers."""
timer.status = status
timer.finishes_at = None
timer.paused_remaining = None
timer.ended_at = dt_util.utcnow()
self._notify(_ARCHIVE_EVENTS[status], timer)
async def create_mock_platform(
hass: HomeAssistant,
entities: list[TimerListEntity],
) -> MockConfigEntry:
"""Create a timer_list platform with the specified entities."""
async def async_setup_entry_platform(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up test timer_list platform via config entry."""
async_add_entities(entities)
mock_platform(
hass,
f"{TEST_DOMAIN}.{DOMAIN}",
MockPlatform(async_setup_entry=async_setup_entry_platform),
)
config_entry = MockConfigEntry(domain=TEST_DOMAIN)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
return config_entry
+65
View File
@@ -0,0 +1,65 @@
"""Fixtures for the Timer list component tests."""
from collections.abc import Generator
import pytest
from pytest_homeassistant.common import (
MockModule,
mock_config_flow,
mock_integration,
mock_platform,
)
from homeassistant.components.timer_list import TimerListEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from . import TEST_DOMAIN, MockFlow, MockTimerListEntity, create_mock_platform
@pytest.fixture(autouse=True)
def config_flow_fixture(hass: HomeAssistant) -> Generator[None]:
"""Mock config flow."""
mock_platform(hass, f"{TEST_DOMAIN}.config_flow")
with mock_config_flow(TEST_DOMAIN, MockFlow):
yield
@pytest.fixture(autouse=True)
def mock_setup_integration(hass: HomeAssistant) -> None:
"""Fixture to set up a mock integration."""
async def async_setup_entry_init(
hass: HomeAssistant, config_entry: ConfigEntry
) -> None:
"""Set up test config entry."""
await hass.config_entries.async_forward_entry_setups(
config_entry, [Platform.TIMER_LIST]
)
async def async_unload_entry_init(
hass: HomeAssistant, config_entry: ConfigEntry
) -> None:
await hass.config_entries.async_unload_platforms(
config_entry, [Platform.TIMER_LIST]
)
mock_integration(
hass,
MockModule(
TEST_DOMAIN,
async_setup_entry=async_setup_entry_init,
async_unload_entry=async_unload_entry_init,
),
)
@pytest.fixture(name="test_entity")
async def mock_test_entity(hass: HomeAssistant) -> TimerListEntity:
"""Fixture that creates a test timer list entity."""
entity = MockTimerListEntity()
entity.entity_id = "timer_list.timers"
await create_mock_platform(hass, [entity])
return entity
+330
View File
@@ -0,0 +1,330 @@
"""Tests for the Timer list integration."""
from typing import Any
import pytest
from pytest_homeassistant.common import MockUser
from pytest_homeassistant.typing import WebSocketGenerator
from homeassistant.components.timer_list.const import DOMAIN, TimerListEntityFeature
from homeassistant.const import ATTR_NAME, TargetKey
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from . import MockTimerListEntity, create_mock_platform
TEST_ENTITY_ID = "timer_list.timers"
async def _create_timer(
hass: HomeAssistant,
*,
duration: int = 60,
name: str | None = None,
) -> str:
"""Create a timer and return its id."""
data: dict[str, Any] = {"duration": {"seconds": duration}}
if name is not None:
data[ATTR_NAME] = name
result = await hass.services.async_call(
DOMAIN,
"create_timer",
data,
target={TargetKey.ENTITY_ID: TEST_ENTITY_ID},
blocking=True,
return_response=True,
)
return result[TEST_ENTITY_ID]["timer_id"]
async def _get_timers(
hass: HomeAssistant, status: str | list[str] | None = None
) -> list[dict[str, Any]]:
"""Return the timers via the get_timers service."""
data: dict[str, Any] = {}
if status is not None:
data["status"] = status
result = await hass.services.async_call(
DOMAIN,
"get_timers",
data,
target={TargetKey.ENTITY_ID: TEST_ENTITY_ID},
blocking=True,
return_response=True,
)
return result[TEST_ENTITY_ID]["timers"]
async def _call(hass: HomeAssistant, service: str, **fields: Any) -> None:
"""Call an entity service targeting the test entity."""
await hass.services.async_call(
DOMAIN,
service,
fields,
target={TargetKey.ENTITY_ID: TEST_ENTITY_ID},
blocking=True,
)
@pytest.mark.usefixtures("test_entity")
async def test_create_timer_sets_state_and_returns_id(hass: HomeAssistant) -> None:
"""Test creating timers updates the state and returns an id."""
assert hass.states.get(TEST_ENTITY_ID).state == "0"
timer_id = await _create_timer(hass, name="Pasta")
assert timer_id
assert hass.states.get(TEST_ENTITY_ID).state == "1"
await _create_timer(hass)
assert hass.states.get(TEST_ENTITY_ID).state == "2"
timers = await _get_timers(hass)
assert len(timers) == 2
assert {timer["status"] for timer in timers} == {"active"}
assert timers[0]["name"] == "Pasta"
@pytest.mark.usefixtures("test_entity")
async def test_get_timers_status_filter(hass: HomeAssistant) -> None:
"""Test the get_timers status filter."""
await _create_timer(hass)
paused_id = await _create_timer(hass)
await _call(hass, "pause_timer", timer_id=paused_id)
assert len(await _get_timers(hass, status=["active"])) == 1
assert len(await _get_timers(hass, status=["paused"])) == 1
assert len(await _get_timers(hass, status=["active", "paused"])) == 2
# A bare status is accepted too, not just a list
assert len(await _get_timers(hass, status="active")) == 1
@pytest.mark.usefixtures("test_entity")
async def test_pause_and_unpause(hass: HomeAssistant) -> None:
"""Test pausing and resuming a timer."""
timer_id = await _create_timer(hass)
await _call(hass, "pause_timer", timer_id=timer_id)
assert hass.states.get(TEST_ENTITY_ID).state == "0"
timers = await _get_timers(hass)
assert timers[0]["status"] == "paused"
assert timers[0]["finishes_at"] is None
assert timers[0]["paused_remaining"] == timers[0]["remaining"]
assert timers[0]["paused_remaining"] > 0
await _call(hass, "unpause_timer", timer_id=timer_id)
assert hass.states.get(TEST_ENTITY_ID).state == "1"
timers = await _get_timers(hass)
assert timers[0]["status"] == "active"
assert timers[0]["finishes_at"] is not None
assert timers[0]["paused_remaining"] is None
@pytest.mark.usefixtures("test_entity")
async def test_cancel_timer_archives_timer(hass: HomeAssistant) -> None:
"""Test cancelling a timer retains it as cancelled."""
timer_id = await _create_timer(hass)
await _call(hass, "cancel_timer", timer_id=timer_id)
assert hass.states.get(TEST_ENTITY_ID).state == "0"
timers = await _get_timers(hass)
assert len(timers) == 1
assert timers[0]["status"] == "cancelled"
@pytest.mark.usefixtures("test_entity")
async def test_finish_timer_archives_as_finished(hass: HomeAssistant) -> None:
"""Test the finish_timer action reaches the entity."""
timer_id = await _create_timer(hass, duration=3600)
await _call(hass, "finish_timer", timer_id=timer_id)
assert hass.states.get(TEST_ENTITY_ID).state == "0"
timers = await _get_timers(hass)
assert len(timers) == 1
assert timers[0]["status"] == "finished"
assert timers[0]["ended_at"] is not None
assert timers[0]["finishes_at"] is None
assert timers[0]["remaining"] == 0
@pytest.mark.usefixtures("test_entity")
async def test_remove_timer(hass: HomeAssistant) -> None:
"""Test removing a single timer regardless of status."""
timer_id = await _create_timer(hass)
await _call(hass, "remove_timer", timer_id=timer_id)
assert hass.states.get(TEST_ENTITY_ID).state == "0"
assert await _get_timers(hass) == []
@pytest.mark.usefixtures("test_entity")
async def test_timer_not_found(hass: HomeAssistant) -> None:
"""Test acting on an unknown timer id raises."""
with pytest.raises(ServiceValidationError):
await _call(hass, "pause_timer", timer_id="does-not-exist")
@pytest.mark.parametrize(
"service",
[
pytest.param("finish_timer", id="finish_timer"),
pytest.param("remove_timer", id="remove_timer"),
],
)
async def test_unsupported_service_raises(hass: HomeAssistant, service: str) -> None:
"""Test services are rejected when the entity does not support them."""
entity = MockTimerListEntity()
entity.entity_id = TEST_ENTITY_ID
entity._attr_supported_features = TimerListEntityFeature.CREATE_TIMER
await create_mock_platform(hass, [entity])
timer_id = await _create_timer(hass)
with pytest.raises(HomeAssistantError):
await _call(hass, service, timer_id=timer_id)
@pytest.mark.usefixtures("test_entity")
@pytest.mark.freeze_time
async def test_websocket_subscribe(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test subscribing to timer changes with an initial snapshot."""
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{"type": "timer_list/item/subscribe", "entity_id": TEST_ENTITY_ID}
)
msg = await client.receive_json()
assert msg["success"]
msg = await client.receive_json()
assert msg["event"] == {"type": "timers", "timers": []}
timer_id = await _create_timer(hass, name="Pasta")
msg = await client.receive_json()
assert msg["event"]["type"] == "change"
assert msg["event"]["event_type"] == "created"
assert msg["event"]["timer"]["timer_id"] == timer_id
assert msg["event"]["timer"]["name"] == "Pasta"
await _call(hass, "pause_timer", timer_id=timer_id)
msg = await client.receive_json()
assert msg["event"]["event_type"] == "paused"
assert "delta" not in msg["event"]
paused_remaining = msg["event"]["timer"]["paused_remaining"]
assert paused_remaining == msg["event"]["timer"]["remaining"]
await _call(hass, "subtract_time", timer_id=timer_id, duration={"seconds": 5})
msg = await client.receive_json()
assert msg["event"]["event_type"] == "time_changed"
assert msg["event"]["delta"] == -5.0
assert msg["event"]["timer"]["finishes_at"] is None
assert msg["event"]["timer"]["paused_remaining"] == paused_remaining - 5
assert msg["event"]["timer"]["remaining"] == paused_remaining - 5
await _call(hass, "add_time", timer_id=timer_id, duration={"seconds": 30})
msg = await client.receive_json()
assert msg["event"]["event_type"] == "time_changed"
assert msg["event"]["delta"] == 30.0
assert msg["event"]["timer"]["finishes_at"] is None
assert msg["event"]["timer"]["paused_remaining"] == paused_remaining + 25
assert msg["event"]["timer"]["remaining"] == paused_remaining + 25
assert msg["event"]["timer"]["created_duration"] == 60
assert msg["event"]["timer"]["total_duration"] == paused_remaining + 25
await _call(hass, "cancel_timer", timer_id=timer_id)
msg = await client.receive_json()
assert msg["event"]["event_type"] == "cancelled"
@pytest.mark.usefixtures("test_entity")
async def test_websocket_list(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test the one-shot websocket list command."""
await _create_timer(hass, name="Pasta")
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{"type": "timer_list/item/list", "entity_id": TEST_ENTITY_ID}
)
msg = await client.receive_json()
assert msg["success"]
assert len(msg["result"]["timers"]) == 1
assert msg["result"]["timers"][0]["name"] == "Pasta"
assert msg["result"]["timers"][0]["paused_remaining"] is None
@pytest.mark.usefixtures("test_entity")
@pytest.mark.parametrize(
"command",
[
pytest.param("timer_list/item/subscribe", id="subscribe"),
pytest.param("timer_list/item/list", id="list"),
],
)
async def test_websocket_unknown_entity(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
command: str,
) -> None:
"""Test addressing an entity that does not exist."""
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": command, "entity_id": "timer_list.unknown"})
msg = await client.receive_json()
assert not msg["success"]
assert msg["error"]["code"] == "not_found"
@pytest.mark.usefixtures("test_entity")
@pytest.mark.parametrize(
"command",
[
pytest.param("timer_list/item/subscribe", id="subscribe"),
pytest.param("timer_list/item/list", id="list"),
],
)
async def test_websocket_requires_read_permission(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
hass_admin_user: MockUser,
command: str,
) -> None:
"""Test a user without read access cannot see another entity's timers."""
await _create_timer(hass, name="Pasta")
hass_admin_user.mock_policy({"entities": {"entity_ids": {TEST_ENTITY_ID: False}}})
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": command, "entity_id": TEST_ENTITY_ID})
msg = await client.receive_json()
assert not msg["success"]
assert msg["error"]["code"] == "unauthorized"
async def test_websocket_subscribe_unavailable_entity(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test an unavailable timer list rejects subscriptions."""
entity = MockTimerListEntity()
entity.entity_id = TEST_ENTITY_ID
entity._attr_available = False
await create_mock_platform(hass, [entity])
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{"type": "timer_list/item/subscribe", "entity_id": TEST_ENTITY_ID}
)
msg = await client.receive_json()
assert not msg["success"]
assert msg["error"]["code"] == "home_assistant_error"
assert msg["error"]["message"] == (
f"Timer list entity is unavailable: {TEST_ENTITY_ID}"
)
await client.send_json_auto_id({"type": "unsubscribe_events", "subscription": 1})
msg = await client.receive_json()
assert not msg["success"]
assert msg["error"]["code"] == "not_found"
+373
View File
@@ -0,0 +1,373 @@
"""Tests for the Timer list triggers."""
import pytest
from pytest_homeassistant.common import (
MockConfigEntry,
MockPlatform,
async_mock_service,
mock_platform,
)
from pytest_homeassistant.components.common import assert_trigger_options_supported
from homeassistant.components import automation
from homeassistant.components.timer_list.const import DOMAIN
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
ATTR_ENTITY_ID,
CONF_ENTITY_ID,
CONF_PLATFORM,
CONF_TARGET,
SERVICE_TURN_OFF,
TargetKey,
)
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.setup import async_setup_component
from . import TEST_DOMAIN, MockTimerListEntity, create_mock_platform
TEST_ENTITY_ID = "timer_list.timers"
@pytest.fixture
def service_calls(hass: HomeAssistant) -> list[ServiceCall]:
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation")
@pytest.fixture(autouse=True)
async def setup_entity(hass: HomeAssistant) -> None:
"""Create a timer list entity via the mock platform."""
entity = MockTimerListEntity()
entity.entity_id = TEST_ENTITY_ID
entity._attr_unique_id = "timers"
await create_mock_platform(hass, [entity])
async def _setup_automation(
hass: HomeAssistant,
trigger_type: str,
extra_data: dict[str, str] | None = None,
entity_id: str = TEST_ENTITY_ID,
) -> None:
"""Set up an automation for the given timer list trigger."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"triggers": [
{
CONF_PLATFORM: f"{DOMAIN}.{trigger_type}",
CONF_TARGET: {CONF_ENTITY_ID: entity_id},
}
],
"action": {
"service": "test.automation",
"data": {
"entity_id": "{{ trigger.entity_id }}",
"timer_id": "{{ trigger.timer.timer_id }}",
"status": "{{ trigger.timer.status }}",
**(extra_data or {}),
},
},
}
},
)
await hass.async_block_till_done()
async def _create_timer(hass: HomeAssistant) -> str:
"""Create a timer and return its id."""
result = await hass.services.async_call(
DOMAIN,
"create_timer",
{"duration": {"seconds": 60}},
target={TargetKey.ENTITY_ID: TEST_ENTITY_ID},
blocking=True,
return_response=True,
)
return result[TEST_ENTITY_ID]["timer_id"]
async def _call_timer_service(hass: HomeAssistant, service: str, timer_id: str) -> None:
"""Call an entity action for a single timer."""
await hass.services.async_call(
DOMAIN,
service,
{"timer_id": timer_id},
target={TargetKey.ENTITY_ID: TEST_ENTITY_ID},
blocking=True,
)
async def test_timer_finished_trigger(
hass: HomeAssistant,
service_calls: list[ServiceCall],
) -> None:
"""Test the timer_finished trigger fires when a timer finishes."""
await _setup_automation(
hass,
"timer_finished",
extra_data={"active_count": "{{ states('timer_list.timers') | int }}"},
)
timer_id = await _create_timer(hass)
assert len(service_calls) == 0
await _call_timer_service(hass, "finish_timer", timer_id)
assert len(service_calls) == 1
assert service_calls[0].data == {
"entity_id": TEST_ENTITY_ID,
"timer_id": timer_id,
"status": "finished",
"active_count": 0,
}
async def test_timer_created_trigger(
hass: HomeAssistant, service_calls: list[ServiceCall]
) -> None:
"""Test the timer_created trigger fires when a timer is created."""
await _setup_automation(
hass,
"timer_created",
extra_data={"active_count": "{{ states('timer_list.timers') | int }}"},
)
timer_id = await _create_timer(hass)
await hass.async_block_till_done()
assert len(service_calls) == 1
assert service_calls[0].data["timer_id"] == timer_id
assert service_calls[0].data["status"] == "active"
assert service_calls[0].data["active_count"] == 1
async def test_timer_cancelled_trigger(
hass: HomeAssistant, service_calls: list[ServiceCall]
) -> None:
"""Test the timer_cancelled trigger fires and ignores other events."""
await _setup_automation(hass, "timer_cancelled")
timer_id = await _create_timer(hass)
await hass.async_block_till_done()
assert len(service_calls) == 0
await hass.services.async_call(
DOMAIN,
"cancel_timer",
{"timer_id": timer_id},
target={TargetKey.ENTITY_ID: TEST_ENTITY_ID},
blocking=True,
)
assert len(service_calls) == 1
assert service_calls[0].data["status"] == "cancelled"
async def test_timer_paused_trigger(
hass: HomeAssistant, service_calls: list[ServiceCall]
) -> None:
"""Test pausing a timer fires the paused trigger."""
await _setup_automation(
hass,
"timer_paused",
extra_data={
"paused_remaining": "{{ trigger.timer.paused_remaining }}",
"remaining": "{{ trigger.timer.remaining }}",
},
)
timer_id = await _create_timer(hass)
await _call_timer_service(hass, "pause_timer", timer_id)
assert len(service_calls) == 1
assert service_calls[0].data["timer_id"] == timer_id
assert service_calls[0].data["status"] == "paused"
assert service_calls[0].data["paused_remaining"] > 0
assert (
service_calls[0].data["paused_remaining"] == service_calls[0].data["remaining"]
)
async def test_timer_unpaused_trigger(
hass: HomeAssistant, service_calls: list[ServiceCall]
) -> None:
"""Test resuming a timer fires the unpaused trigger, not the paused one."""
await _setup_automation(hass, "timer_unpaused")
timer_id = await _create_timer(hass)
await _call_timer_service(hass, "pause_timer", timer_id)
await _call_timer_service(hass, "unpause_timer", timer_id)
assert len(service_calls) == 1
assert service_calls[0].data["timer_id"] == timer_id
assert service_calls[0].data["status"] == "active"
@pytest.mark.parametrize(
("service", "expected_delta"),
[
pytest.param("add_time", 30.0, id="add_time"),
pytest.param("subtract_time", -30.0, id="subtract_time"),
],
)
async def test_timer_time_changed_trigger_reports_delta(
hass: HomeAssistant,
service_calls: list[ServiceCall],
service: str,
expected_delta: float,
) -> None:
"""Test the time_changed trigger reports the signed amount of time added."""
await _setup_automation(
hass, "timer_time_changed", extra_data={"delta": "{{ trigger.delta }}"}
)
timer_id = await _create_timer(hass)
await hass.async_block_till_done()
assert len(service_calls) == 0
await hass.services.async_call(
DOMAIN,
service,
{"timer_id": timer_id, "duration": {"seconds": 30}},
target={TargetKey.ENTITY_ID: TEST_ENTITY_ID},
blocking=True,
)
assert len(service_calls) == 1
assert service_calls[0].data["timer_id"] == timer_id
assert service_calls[0].data["delta"] == expected_delta
async def test_trigger_picks_up_entity_added_after_setup(
hass: HomeAssistant, service_calls: list[ServiceCall]
) -> None:
"""Test a timer list created after the automation still fires the trigger."""
late_entity_id = "timer_list.late"
await _setup_automation(hass, "timer_created", entity_id=late_entity_id)
entity = MockTimerListEntity(name="Late")
entity.entity_id = late_entity_id
await create_mock_platform(hass, [entity])
await hass.services.async_call(
DOMAIN,
"create_timer",
{"duration": {"seconds": 60}},
target={TargetKey.ENTITY_ID: late_entity_id},
blocking=True,
)
assert len(service_calls) == 1
assert service_calls[0].data["entity_id"] == late_entity_id
async def test_trigger_options_supported(hass: HomeAssistant) -> None:
"""Test the timer list triggers do not advertise behavior or duration."""
for trigger_type in (
"timer_created",
"timer_paused",
"timer_unpaused",
"timer_time_changed",
"timer_finished",
"timer_cancelled",
):
await assert_trigger_options_supported(
hass,
f"{DOMAIN}.{trigger_type}",
None,
supports_behavior=False,
supports_duration=False,
)
async def test_trigger_unsubscribes_when_automation_turned_off(
hass: HomeAssistant, service_calls: list[ServiceCall]
) -> None:
"""Test turning the automation off releases the timer list subscription."""
await _setup_automation(hass, "timer_created")
await hass.services.async_call(
automation.DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "automation.automation_0"},
blocking=True,
)
await _create_timer(hass)
await hass.async_block_till_done()
assert len(service_calls) == 0
async def test_trigger_without_target_fails_to_attach(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test a trigger targeting nothing is rejected rather than silently idle."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"triggers": [
{
CONF_PLATFORM: f"{DOMAIN}.timer_created",
CONF_TARGET: {},
}
],
"action": {"service": "test.automation"},
}
},
)
await hass.async_block_till_done()
assert "No target defined" in caplog.text
async def test_trigger_follows_entity_replaced_by_reload(
hass: HomeAssistant, service_calls: list[ServiceCall]
) -> None:
"""Test the trigger resubscribes to the entity object a reload creates.
A config entry reload builds a new entity object but leaves its registry
entry untouched, so the target set never changes and nothing else would
tell the trigger its subscription points at a discarded object.
"""
reloaded_entity_id = "timer_list.reloaded"
await _setup_automation(hass, "timer_created", entity_id=reloaded_entity_id)
async def async_setup_entry_platform(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Build a fresh entity per setup, as a real integration does."""
entity = MockTimerListEntity(name="Reloaded")
entity.entity_id = reloaded_entity_id
entity._attr_unique_id = "reloaded"
async_add_entities([entity])
mock_platform(
hass,
f"{TEST_DOMAIN}.{DOMAIN}",
MockPlatform(async_setup_entry=async_setup_entry_platform),
)
config_entry = MockConfigEntry(domain=TEST_DOMAIN)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert await hass.config_entries.async_reload(config_entry.entry_id)
await hass.async_block_till_done()
await hass.services.async_call(
DOMAIN,
"create_timer",
{"duration": {"seconds": 60}},
target={TargetKey.ENTITY_ID: reloaded_entity_id},
blocking=True,
)
await hass.async_block_till_done()
assert len(service_calls) == 1
assert service_calls[0].data["entity_id"] == reloaded_entity_id
+2
View File
@@ -97,6 +97,7 @@
'text',
'time',
'timer',
'timer_list',
'trace',
'tts',
'update',
@@ -210,6 +211,7 @@
'text',
'time',
'timer',
'timer_list',
'trace',
'tts',
'update',