Home Assistant Unofficial Reference 2024.12.1
reproduce_state.py
Go to the documentation of this file.
1 """Reproduce an Input number 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 import voluptuous as vol
11 
12 from homeassistant.const import ATTR_ENTITY_ID
13 from homeassistant.core import Context, HomeAssistant, State
14 
15 from . import ATTR_VALUE, DOMAIN, SERVICE_SET_VALUE
16 
17 _LOGGER = logging.getLogger(__name__)
18 
19 
21  hass: HomeAssistant,
22  state: State,
23  *,
24  context: Context | None = None,
25  reproduce_options: dict[str, Any] | None = None,
26 ) -> None:
27  """Reproduce a single state."""
28  if (cur_state := hass.states.get(state.entity_id)) is None:
29  _LOGGER.warning("Unable to find entity %s", state.entity_id)
30  return
31 
32  try:
33  float(state.state)
34  except ValueError:
35  _LOGGER.warning(
36  "Invalid state specified for %s: %s", state.entity_id, state.state
37  )
38  return
39 
40  # Return if we are already at the right state.
41  if cur_state.state == state.state:
42  return
43 
44  service = SERVICE_SET_VALUE
45  service_data = {ATTR_ENTITY_ID: state.entity_id, ATTR_VALUE: state.state}
46 
47  try:
48  await hass.services.async_call(
49  DOMAIN, service, service_data, context=context, blocking=True
50  )
51  except vol.Invalid as err:
52  # If value out of range.
53  _LOGGER.warning("Unable to reproduce state for %s: %s", state.entity_id, err)
54 
55 
57  hass: HomeAssistant,
58  states: Iterable[State],
59  *,
60  context: Context | None = None,
61  reproduce_options: dict[str, Any] | None = None,
62 ) -> None:
63  """Reproduce Input number states."""
64  # Reproduce states in parallel.
65  await asyncio.gather(
66  *(
68  hass, state, context=context, reproduce_options=reproduce_options
69  )
70  for state in states
71  )
72  )
None _async_reproduce_state(HomeAssistant hass, State state, *Context|None context=None, dict[str, Any]|None reproduce_options=None)
None async_reproduce_states(HomeAssistant hass, Iterable[State] states, *Context|None context=None, dict[str, Any]|None reproduce_options=None)