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