Home Assistant Unofficial Reference 2024.12.1
reproduce_state.py
Go to the documentation of this file.
1 """Reproduce an Input datetime 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 from homeassistant.util import dt as dt_util
13 
14 from . import ATTR_DATE, ATTR_DATETIME, ATTR_TIME, CONF_HAS_DATE, CONF_HAS_TIME, DOMAIN
15 
16 _LOGGER = logging.getLogger(__name__)
17 
18 
19 def is_valid_datetime(string: str) -> bool:
20  """Test if string dt is a valid datetime."""
21  try:
22  return dt_util.parse_datetime(string) is not None
23  except ValueError:
24  return False
25 
26 
27 def is_valid_date(string: str) -> bool:
28  """Test if string dt is a valid date."""
29  return dt_util.parse_date(string) is not None
30 
31 
32 def is_valid_time(string: str) -> bool:
33  """Test if string dt is a valid time."""
34  return dt_util.parse_time(string) is not None
35 
36 
38  hass: HomeAssistant,
39  state: State,
40  *,
41  context: Context | None = None,
42  reproduce_options: dict[str, Any] | None = None,
43 ) -> None:
44  """Reproduce a single state."""
45  if (cur_state := hass.states.get(state.entity_id)) is None:
46  _LOGGER.warning("Unable to find entity %s", state.entity_id)
47  return
48 
49  has_time = cur_state.attributes.get(CONF_HAS_TIME)
50  has_date = cur_state.attributes.get(CONF_HAS_DATE)
51 
52  if not (
53  (is_valid_datetime(state.state) and has_date and has_time)
54  or (is_valid_date(state.state) and has_date and not has_time)
55  or (is_valid_time(state.state) and has_time and not has_date)
56  ):
57  _LOGGER.warning(
58  "Invalid state specified for %s: %s", state.entity_id, state.state
59  )
60  return
61 
62  # Return if we are already at the right state.
63  if cur_state.state == state.state:
64  return
65 
66  service_data = {ATTR_ENTITY_ID: state.entity_id}
67 
68  if has_time and has_date:
69  service_data[ATTR_DATETIME] = state.state
70  elif has_time:
71  service_data[ATTR_TIME] = state.state
72  elif has_date:
73  service_data[ATTR_DATE] = state.state
74 
75  await hass.services.async_call(
76  DOMAIN, "set_datetime", service_data, context=context, blocking=True
77  )
78 
79 
81  hass: HomeAssistant,
82  states: Iterable[State],
83  *,
84  context: Context | None = None,
85  reproduce_options: dict[str, Any] | None = None,
86 ) -> None:
87  """Reproduce Input datetime states."""
88  await asyncio.gather(
89  *(
91  hass, state, context=context, reproduce_options=reproduce_options
92  )
93  for state in states
94  )
95  )
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)