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