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