Home Assistant Unofficial Reference 2024.12.1
reproduce_state.py
Go to the documentation of this file.
1 """Reproduce an Timer state."""
2 
3 from __future__ import annotations
4 
5 import asyncio
6 from collections.abc import Iterable
7 import logging
8 from typing import Any
9 
10 from homeassistant.const import ATTR_ENTITY_ID
11 from homeassistant.core import Context, HomeAssistant, State
12 
13 from . import (
14  ATTR_DURATION,
15  DOMAIN,
16  SERVICE_CANCEL,
17  SERVICE_PAUSE,
18  SERVICE_START,
19  STATUS_ACTIVE,
20  STATUS_IDLE,
21  STATUS_PAUSED,
22 )
23 
24 _LOGGER = logging.getLogger(__name__)
25 
26 VALID_STATES = {STATUS_IDLE, STATUS_ACTIVE, STATUS_PAUSED}
27 
28 
30  hass: HomeAssistant,
31  state: State,
32  *,
33  context: Context | None = None,
34  reproduce_options: dict[str, Any] | None = None,
35 ) -> None:
36  """Reproduce a single state."""
37  if (cur_state := hass.states.get(state.entity_id)) is None:
38  _LOGGER.warning("Unable to find entity %s", state.entity_id)
39  return
40 
41  if state.state not in VALID_STATES:
42  _LOGGER.warning(
43  "Invalid state specified for %s: %s", state.entity_id, state.state
44  )
45  return
46 
47  # Return if we are already at the right state.
48  if cur_state.state == state.state and cur_state.attributes.get(
49  ATTR_DURATION
50  ) == state.attributes.get(ATTR_DURATION):
51  return
52 
53  service_data = {ATTR_ENTITY_ID: state.entity_id}
54 
55  if state.state == STATUS_ACTIVE:
56  service = SERVICE_START
57  if ATTR_DURATION in state.attributes:
58  service_data[ATTR_DURATION] = state.attributes[ATTR_DURATION]
59  elif state.state == STATUS_PAUSED:
60  service = SERVICE_PAUSE
61  elif state.state == STATUS_IDLE:
62  service = SERVICE_CANCEL
63 
64  await hass.services.async_call(
65  DOMAIN, service, service_data, context=context, blocking=True
66  )
67 
68 
70  hass: HomeAssistant,
71  states: Iterable[State],
72  *,
73  context: Context | None = None,
74  reproduce_options: dict[str, Any] | None = None,
75 ) -> None:
76  """Reproduce Timer states."""
77  await asyncio.gather(
78  *(
80  hass, state, context=context, reproduce_options=reproduce_options
81  )
82  for state in states
83  )
84  )
None async_reproduce_states(HomeAssistant hass, Iterable[State] states, *Context|None context=None, dict[str, Any]|None reproduce_options=None)
None _async_reproduce_state(HomeAssistant hass, State state, *Context|None context=None, dict[str, Any]|None reproduce_options=None)