Home Assistant Unofficial Reference 2024.12.1
state.py
Go to the documentation of this file.
1 """Helpers that help with state related things."""
2 
3 from __future__ import annotations
4 
5 import asyncio
6 from collections import defaultdict
7 from collections.abc import Iterable
8 import logging
9 from types import ModuleType
10 from typing import Any
11 
12 from homeassistant.components.lock import LockState
13 from homeassistant.components.sun import STATE_ABOVE_HORIZON, STATE_BELOW_HORIZON
14 from homeassistant.const import (
15  STATE_CLOSED,
16  STATE_HOME,
17  STATE_NOT_HOME,
18  STATE_OFF,
19  STATE_ON,
20  STATE_OPEN,
21  STATE_UNKNOWN,
22 )
23 from homeassistant.core import Context, HomeAssistant, State
24 from homeassistant.loader import IntegrationNotFound, async_get_integration, bind_hass
25 
26 _LOGGER = logging.getLogger(__name__)
27 
28 
29 @bind_hass
31  hass: HomeAssistant,
32  states: State | Iterable[State],
33  *,
34  context: Context | None = None,
35  reproduce_options: dict[str, Any] | None = None,
36 ) -> None:
37  """Reproduce a list of states on multiple domains."""
38  if isinstance(states, State):
39  states = [states]
40 
41  to_call: dict[str, list[State]] = defaultdict(list)
42 
43  for state in states:
44  to_call[state.domain].append(state)
45 
46  async def worker(domain: str, states_by_domain: list[State]) -> None:
47  try:
48  integration = await async_get_integration(hass, domain)
49  except IntegrationNotFound:
50  _LOGGER.warning(
51  "Trying to reproduce state for unknown integration: %s", domain
52  )
53  return
54 
55  try:
56  platform: ModuleType = await integration.async_get_platform(
57  "reproduce_state"
58  )
59  except ImportError:
60  _LOGGER.warning("Integration %s does not support reproduce state", domain)
61  return
62 
63  await platform.async_reproduce_states(
64  hass, states_by_domain, context=context, reproduce_options=reproduce_options
65  )
66 
67  if to_call:
68  # run all domains in parallel
69  await asyncio.gather(
70  *(worker(domain, data) for domain, data in to_call.items())
71  )
72 
73 
74 def state_as_number(state: State) -> float:
75  """Try to coerce our state to a number.
76 
77  Raises ValueError if this is not possible.
78  """
79  if state.state in (
80  STATE_ON,
81  LockState.LOCKED,
82  STATE_ABOVE_HORIZON,
83  STATE_OPEN,
84  STATE_HOME,
85  ):
86  return 1
87  if state.state in (
88  STATE_OFF,
89  LockState.UNLOCKED,
90  STATE_UNKNOWN,
91  STATE_BELOW_HORIZON,
92  STATE_CLOSED,
93  STATE_NOT_HOME,
94  ):
95  return 0
96 
97  return float(state.state)
None async_reproduce_state(HomeAssistant hass, State|Iterable[State] states, *Context|None context=None, dict[str, Any]|None reproduce_options=None)
Definition: state.py:36
float state_as_number(State state)
Definition: state.py:74
Integration async_get_integration(HomeAssistant hass, str domain)
Definition: loader.py:1354