Home Assistant Unofficial Reference 2024.12.1
reproduce_state.py
Go to the documentation of this file.
1 """Reproduce an Fan 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 (
20  ATTR_DIRECTION,
21  ATTR_OSCILLATING,
22  ATTR_PERCENTAGE,
23  ATTR_PRESET_MODE,
24  DOMAIN,
25  SERVICE_OSCILLATE,
26  SERVICE_SET_DIRECTION,
27  SERVICE_SET_PERCENTAGE,
28  SERVICE_SET_PRESET_MODE,
29 )
30 
31 _LOGGER = logging.getLogger(__name__)
32 
33 VALID_STATES = {STATE_ON, STATE_OFF}
34 
35 # These are used as parameters to fan.turn_on service.
36 SPEED_AND_MODE_ATTRIBUTES = {
37  ATTR_PERCENTAGE: SERVICE_SET_PERCENTAGE,
38  ATTR_PRESET_MODE: SERVICE_SET_PRESET_MODE,
39 }
40 
41 SIMPLE_ATTRIBUTES = { # attribute: service
42  ATTR_DIRECTION: SERVICE_SET_DIRECTION,
43  ATTR_OSCILLATING: SERVICE_OSCILLATE,
44 }
45 
46 
48  hass: HomeAssistant,
49  state: State,
50  *,
51  context: Context | None = None,
52  reproduce_options: dict[str, Any] | None = None,
53 ) -> None:
54  """Reproduce a single state."""
55  if (cur_state := hass.states.get(state.entity_id)) is None:
56  _LOGGER.warning("Unable to find entity %s", state.entity_id)
57  return
58 
59  if state.state not in VALID_STATES:
60  _LOGGER.warning(
61  "Invalid state specified for %s: %s", state.entity_id, state.state
62  )
63  return
64 
65  service_calls: dict[str, dict[str, Any]] = {}
66 
67  if state.state == STATE_ON:
68  # The fan should be on
69  if cur_state.state != STATE_ON:
70  # Turn on the fan with all the speed and modes attributes.
71  # The `turn_on` method will figure out in which mode to
72  # turn the fan on.
73  service_calls[SERVICE_TURN_ON] = {
74  attr: state.attributes.get(attr)
75  for attr in SPEED_AND_MODE_ATTRIBUTES
76  if state.attributes.get(attr) is not None
77  }
78  else:
79  # If the fan is already on, we need to set speed or mode
80  # based on the state.
81  #
82  # Speed and preset mode are mutually exclusive, so one of
83  # them is always going to be stored as None. If we were to
84  # try to set it, it will raise an error. So instead we
85  # only update the one that is non-None.
86  for attr, service in SPEED_AND_MODE_ATTRIBUTES.items():
87  value = state.attributes.get(attr)
88  if value is not None and value != cur_state.attributes.get(attr):
89  service_calls[service] = {attr: value}
90 
91  # The simple attributes are copied directly. They can only be
92  # None if the fan does not support the feature in the first
93  # place, so the equality check ensures we don't call the
94  # services with invalid parameters.
95  for attr, service in SIMPLE_ATTRIBUTES.items():
96  if (value := state.attributes.get(attr)) != cur_state.attributes.get(attr):
97  service_calls[service] = {attr: value}
98  elif state.state == STATE_OFF and cur_state.state != state.state:
99  service_calls[SERVICE_TURN_OFF] = {}
100 
101  for service, data in service_calls.items():
102  await hass.services.async_call(
103  DOMAIN,
104  service,
105  {ATTR_ENTITY_ID: state.entity_id, **data},
106  context=context,
107  blocking=True,
108  )
109 
110 
112  hass: HomeAssistant,
113  states: Iterable[State],
114  *,
115  context: Context | None = None,
116  reproduce_options: dict[str, Any] | None = None,
117 ) -> None:
118  """Reproduce Fan states."""
119  await asyncio.gather(
120  *(
122  hass, state, context=context, reproduce_options=reproduce_options
123  )
124  for state in states
125  )
126  )
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)