Home Assistant Unofficial Reference 2024.12.1
reproduce_state.py
Go to the documentation of this file.
1 """Reproduce an Counter 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 ATTR_MAXIMUM, ATTR_MINIMUM, ATTR_STEP, DOMAIN, SERVICE_SET_VALUE, VALUE
14 
15 _LOGGER = logging.getLogger(__name__)
16 
17 
19  hass: HomeAssistant,
20  state: State,
21  *,
22  context: Context | None = None,
23  reproduce_options: dict[str, Any] | None = None,
24 ) -> None:
25  """Reproduce a single state."""
26  if (cur_state := hass.states.get(state.entity_id)) is None:
27  _LOGGER.warning("Unable to find entity %s", state.entity_id)
28  return
29 
30  if not state.state.isdigit():
31  _LOGGER.warning(
32  "Invalid state specified for %s: %s", state.entity_id, state.state
33  )
34  return
35 
36  # Return if we are already at the right state.
37  if (
38  cur_state.state == state.state
39  and cur_state.attributes.get(ATTR_MAXIMUM) == state.attributes.get(ATTR_MAXIMUM)
40  and cur_state.attributes.get(ATTR_MINIMUM) == state.attributes.get(ATTR_MINIMUM)
41  and cur_state.attributes.get(ATTR_STEP) == state.attributes.get(ATTR_STEP)
42  ):
43  return
44 
45  service_data = {ATTR_ENTITY_ID: state.entity_id, VALUE: state.state}
46  service = SERVICE_SET_VALUE
47  if ATTR_MAXIMUM in state.attributes:
48  service_data[ATTR_MAXIMUM] = state.attributes[ATTR_MAXIMUM]
49  if ATTR_MINIMUM in state.attributes:
50  service_data[ATTR_MINIMUM] = state.attributes[ATTR_MINIMUM]
51  if ATTR_STEP in state.attributes:
52  service_data[ATTR_STEP] = state.attributes[ATTR_STEP]
53 
54  await hass.services.async_call(
55  DOMAIN, service, service_data, context=context, blocking=True
56  )
57 
58 
60  hass: HomeAssistant,
61  states: Iterable[State],
62  *,
63  context: Context | None = None,
64  reproduce_options: dict[str, Any] | None = None,
65 ) -> None:
66  """Reproduce Counter states."""
67  await asyncio.gather(
68  *(
70  hass, state, context=context, reproduce_options=reproduce_options
71  )
72  for state in states
73  )
74  )
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)