Home Assistant Unofficial Reference 2024.12.1
reproduce_state.py
Go to the documentation of this file.
1 """Reproduce an Input select state."""
2 
3 from __future__ import annotations
4 
5 import asyncio
6 from collections.abc import Iterable, Mapping
7 import logging
8 from typing import Any
9 
10 from homeassistant.const import ATTR_ENTITY_ID, ATTR_OPTION
11 from homeassistant.core import Context, HomeAssistant, State
12 
13 from . import ATTR_OPTIONS, DOMAIN, SERVICE_SELECT_OPTION, SERVICE_SET_OPTIONS
14 
15 ATTR_GROUP = [ATTR_OPTION, ATTR_OPTIONS]
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  # Return if we can't find entity
29  if (cur_state := hass.states.get(state.entity_id)) is None:
30  _LOGGER.warning("Unable to find entity %s", state.entity_id)
31  return
32 
33  # Return if we are already at the right state.
34  if cur_state.state == state.state and all(
35  check_attr_equal(cur_state.attributes, state.attributes, attr)
36  for attr in ATTR_GROUP
37  ):
38  return
39 
40  # Set service data
41  service_data = {ATTR_ENTITY_ID: state.entity_id}
42 
43  # If options are specified, call SERVICE_SET_OPTIONS
44  if ATTR_OPTIONS in state.attributes:
45  service = SERVICE_SET_OPTIONS
46  service_data[ATTR_OPTIONS] = state.attributes[ATTR_OPTIONS]
47 
48  await hass.services.async_call(
49  DOMAIN, service, service_data, context=context, blocking=True
50  )
51 
52  # Remove ATTR_OPTIONS from service_data so we can reuse service_data in next call
53  del service_data[ATTR_OPTIONS]
54 
55  # Call SERVICE_SELECT_OPTION
56  service = SERVICE_SELECT_OPTION
57  service_data[ATTR_OPTION] = state.state
58 
59  await hass.services.async_call(
60  DOMAIN, service, service_data, context=context, blocking=True
61  )
62 
63 
65  hass: HomeAssistant,
66  states: Iterable[State],
67  *,
68  context: Context | None = None,
69  reproduce_options: dict[str, Any] | None = None,
70 ) -> None:
71  """Reproduce Input select states."""
72  # Reproduce states in parallel.
73  await asyncio.gather(
74  *(
76  hass, state, context=context, reproduce_options=reproduce_options
77  )
78  for state in states
79  )
80  )
81 
82 
83 def check_attr_equal(attr1: Mapping, attr2: Mapping, attr_str: str) -> bool:
84  """Return true if the given attributes are equal."""
85  return attr1.get(attr_str) == attr2.get(attr_str)
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)
bool check_attr_equal(Mapping attr1, Mapping attr2, str attr_str)