Home Assistant Unofficial Reference 2024.12.1
fan.py
Go to the documentation of this file.
1 """Platform allowing several fans to be grouped into one fan."""
2 
3 from __future__ import annotations
4 
5 from functools import reduce
6 import logging
7 from operator import ior
8 from typing import Any
9 
10 import voluptuous as vol
11 
12 from homeassistant.components.fan import (
13  ATTR_DIRECTION,
14  ATTR_OSCILLATING,
15  ATTR_PERCENTAGE,
16  ATTR_PERCENTAGE_STEP,
17  DOMAIN as FAN_DOMAIN,
18  PLATFORM_SCHEMA as FAN_PLATFORM_SCHEMA,
19  SERVICE_OSCILLATE,
20  SERVICE_SET_DIRECTION,
21  SERVICE_SET_PERCENTAGE,
22  SERVICE_TURN_OFF,
23  SERVICE_TURN_ON,
24  FanEntity,
25  FanEntityFeature,
26 )
27 from homeassistant.config_entries import ConfigEntry
28 from homeassistant.const import (
29  ATTR_ENTITY_ID,
30  ATTR_SUPPORTED_FEATURES,
31  CONF_ENTITIES,
32  CONF_NAME,
33  CONF_UNIQUE_ID,
34  STATE_ON,
35  STATE_UNAVAILABLE,
36  STATE_UNKNOWN,
37 )
38 from homeassistant.core import HomeAssistant, State, callback
39 from homeassistant.helpers import config_validation as cv, entity_registry as er
40 from homeassistant.helpers.entity_platform import AddEntitiesCallback
41 from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
42 
43 from .entity import GroupEntity
44 from .util import attribute_equal, most_frequent_attribute, reduce_attribute
45 
46 SUPPORTED_FLAGS = {
47  FanEntityFeature.SET_SPEED,
48  FanEntityFeature.DIRECTION,
49  FanEntityFeature.OSCILLATE,
50  FanEntityFeature.TURN_OFF,
51  FanEntityFeature.TURN_ON,
52 }
53 
54 DEFAULT_NAME = "Fan Group"
55 
56 # No limit on parallel updates to enable a group calling another group
57 PARALLEL_UPDATES = 0
58 
59 PLATFORM_SCHEMA = FAN_PLATFORM_SCHEMA.extend(
60  {
61  vol.Required(CONF_ENTITIES): cv.entities_domain(FAN_DOMAIN),
62  vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
63  vol.Optional(CONF_UNIQUE_ID): cv.string,
64  }
65 )
66 
67 _LOGGER = logging.getLogger(__name__)
68 
69 
71  hass: HomeAssistant,
72  config: ConfigType,
73  async_add_entities: AddEntitiesCallback,
74  discovery_info: DiscoveryInfoType | None = None,
75 ) -> None:
76  """Set up the Fan Group platform."""
78  [FanGroup(config.get(CONF_UNIQUE_ID), config[CONF_NAME], config[CONF_ENTITIES])]
79  )
80 
81 
83  hass: HomeAssistant,
84  config_entry: ConfigEntry,
85  async_add_entities: AddEntitiesCallback,
86 ) -> None:
87  """Initialize Fan Group config entry."""
88  registry = er.async_get(hass)
89  entities = er.async_validate_entity_ids(
90  registry, config_entry.options[CONF_ENTITIES]
91  )
92 
93  async_add_entities([FanGroup(config_entry.entry_id, config_entry.title, entities)])
94 
95 
96 @callback
98  hass: HomeAssistant, name: str, validated_config: dict[str, Any]
99 ) -> FanGroup:
100  """Create a preview sensor."""
101  return FanGroup(
102  None,
103  name,
104  validated_config[CONF_ENTITIES],
105  )
106 
107 
109  """Representation of a FanGroup."""
110 
111  _attr_available: bool = False
112  _enable_turn_on_off_backwards_compatibility = False
113 
114  def __init__(self, unique_id: str | None, name: str, entities: list[str]) -> None:
115  """Initialize a FanGroup entity."""
116  self._entity_ids_entity_ids = entities
117  self._fans: dict[int, set[str]] = {flag: set() for flag in SUPPORTED_FLAGS}
118  self._percentage_percentage = None
119  self._oscillating_oscillating = None
120  self._direction_direction = None
121  self._speed_count_speed_count = 100
122  self._is_on_is_on: bool | None = False
123  self._attr_name_attr_name = name
124  self._attr_extra_state_attributes_attr_extra_state_attributes = {ATTR_ENTITY_ID: entities}
125  self._attr_unique_id_attr_unique_id = unique_id
126 
127  @property
128  def speed_count(self) -> int:
129  """Return the number of speeds the fan supports."""
130  return self._speed_count_speed_count
131 
132  @property
133  def is_on(self) -> bool | None:
134  """Return true if the entity is on."""
135  return self._is_on_is_on
136 
137  @property
138  def percentage(self) -> int | None:
139  """Return the current speed as a percentage."""
140  return self._percentage_percentage
141 
142  @property
143  def current_direction(self) -> str | None:
144  """Return the current direction of the fan."""
145  return self._direction_direction
146 
147  @property
148  def oscillating(self) -> bool | None:
149  """Return whether or not the fan is currently oscillating."""
150  return self._oscillating_oscillating
151 
152  @callback
154  self,
155  entity_id: str,
156  new_state: State | None,
157  ) -> None:
158  """Update dictionaries with supported features."""
159  if not new_state:
160  for values in self._fans.values():
161  values.discard(entity_id)
162  else:
163  features = new_state.attributes.get(ATTR_SUPPORTED_FEATURES, 0)
164  for feature in SUPPORTED_FLAGS:
165  if features & feature:
166  self._fans[feature].add(entity_id)
167  else:
168  self._fans[feature].discard(entity_id)
169 
170  async def async_set_percentage(self, percentage: int) -> None:
171  """Set the speed of the fan, as a percentage."""
172  if percentage == 0:
173  await self.async_turn_offasync_turn_offasync_turn_off()
174  await self._async_call_supported_entities_async_call_supported_entities(
175  SERVICE_SET_PERCENTAGE,
176  FanEntityFeature.SET_SPEED,
177  {ATTR_PERCENTAGE: percentage},
178  )
179 
180  async def async_oscillate(self, oscillating: bool) -> None:
181  """Oscillate the fan."""
182  await self._async_call_supported_entities_async_call_supported_entities(
183  SERVICE_OSCILLATE,
184  FanEntityFeature.OSCILLATE,
185  {ATTR_OSCILLATING: oscillating},
186  )
187 
188  async def async_set_direction(self, direction: str) -> None:
189  """Set the direction of the fan."""
190  await self._async_call_supported_entities_async_call_supported_entities(
191  SERVICE_SET_DIRECTION,
192  FanEntityFeature.DIRECTION,
193  {ATTR_DIRECTION: direction},
194  )
195 
196  async def async_turn_on(
197  self,
198  percentage: int | None = None,
199  preset_mode: str | None = None,
200  **kwargs: Any,
201  ) -> None:
202  """Turn on the fan."""
203  if percentage is not None:
204  await self.async_set_percentageasync_set_percentageasync_set_percentage(percentage)
205  return
206  await self._async_call_supported_entities_async_call_supported_entities(
207  SERVICE_TURN_ON, FanEntityFeature.TURN_ON, {}
208  )
209 
210  async def async_turn_off(self, **kwargs: Any) -> None:
211  """Turn the fans off."""
212  await self._async_call_supported_entities_async_call_supported_entities(
213  SERVICE_TURN_OFF, FanEntityFeature.TURN_OFF, {}
214  )
215 
217  self, service: str, support_flag: int, data: dict[str, Any]
218  ) -> None:
219  """Call a service with all entities."""
220  await self.hasshass.services.async_call(
221  FAN_DOMAIN,
222  service,
223  {**data, ATTR_ENTITY_ID: self._fans[support_flag]},
224  blocking=True,
225  context=self._context_context,
226  )
227 
228  async def _async_call_all_entities(self, service: str) -> None:
229  """Call a service with all entities."""
230  await self.hasshass.services.async_call(
231  FAN_DOMAIN,
232  service,
233  {ATTR_ENTITY_ID: self._entity_ids_entity_ids},
234  blocking=True,
235  context=self._context_context,
236  )
237 
238  def _async_states_by_support_flag(self, flag: int) -> list[State]:
239  """Return all the entity states for a supported flag."""
240  states: list[State] = list(
241  filter(None, [self.hasshass.states.get(x) for x in self._fans[flag]])
242  )
243  return states
244 
245  def _set_attr_most_frequent(self, attr: str, flag: int, entity_attr: str) -> None:
246  """Set an attribute based on most frequent supported entities attributes."""
247  states = self._async_states_by_support_flag_async_states_by_support_flag(flag)
248  setattr(self, attr, most_frequent_attribute(states, entity_attr))
249 
250  @callback
251  def async_update_group_state(self) -> None:
252  """Update state and attributes."""
253 
254  states = [
255  state
256  for entity_id in self._entity_ids_entity_ids
257  if (state := self.hasshass.states.get(entity_id)) is not None
258  ]
259 
260  # Set group as unavailable if all members are unavailable or missing
261  self._attr_available_attr_available = any(state.state != STATE_UNAVAILABLE for state in states)
262 
263  valid_state = any(
264  state.state not in (STATE_UNKNOWN, STATE_UNAVAILABLE) for state in states
265  )
266  if not valid_state:
267  # Set as unknown if all members are unknown or unavailable
268  self._is_on_is_on = None
269  else:
270  # Set as ON if any member is ON
271  self._is_on_is_on = any(state.state == STATE_ON for state in states)
272 
273  percentage_states = self._async_states_by_support_flag_async_states_by_support_flag(
274  FanEntityFeature.SET_SPEED
275  )
276  self._percentage_percentage = reduce_attribute(percentage_states, ATTR_PERCENTAGE)
277  if (
278  percentage_states
279  and percentage_states[0].attributes.get(ATTR_PERCENTAGE_STEP)
280  and attribute_equal(percentage_states, ATTR_PERCENTAGE_STEP)
281  ):
282  self._speed_count_speed_count = (
283  round(100 / percentage_states[0].attributes[ATTR_PERCENTAGE_STEP])
284  or 100
285  )
286  else:
287  self._speed_count_speed_count = 100
288 
289  self._set_attr_most_frequent_set_attr_most_frequent(
290  "_oscillating", FanEntityFeature.OSCILLATE, ATTR_OSCILLATING
291  )
292  self._set_attr_most_frequent_set_attr_most_frequent(
293  "_direction", FanEntityFeature.DIRECTION, ATTR_DIRECTION
294  )
295 
296  self._attr_supported_features_attr_supported_features = FanEntityFeature(
297  reduce(
298  ior, [feature for feature in SUPPORTED_FLAGS if self._fans[feature]], 0
299  )
300  )
None async_set_percentage(self, int percentage)
Definition: __init__.py:340
list[State] _async_states_by_support_flag(self, int flag)
Definition: fan.py:238
None _set_attr_most_frequent(self, str attr, int flag, str entity_attr)
Definition: fan.py:245
None async_turn_on(self, int|None percentage=None, str|None preset_mode=None, **Any kwargs)
Definition: fan.py:201
None _async_call_supported_entities(self, str service, int support_flag, dict[str, Any] data)
Definition: fan.py:218
None async_set_direction(self, str direction)
Definition: fan.py:188
None async_update_supported_features(self, str entity_id, State|None new_state)
Definition: fan.py:157
None async_set_percentage(self, int percentage)
Definition: fan.py:170
None async_turn_off(self, **Any kwargs)
Definition: fan.py:210
None _async_call_all_entities(self, str service)
Definition: fan.py:228
None async_oscillate(self, bool oscillating)
Definition: fan.py:180
None __init__(self, str|None unique_id, str name, list[str] entities)
Definition: fan.py:114
None async_turn_off(self, **Any kwargs)
Definition: entity.py:1709
bool add(self, _T matcher)
Definition: match.py:185
None async_setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback async_add_entities, DiscoveryInfoType|None discovery_info=None)
Definition: fan.py:75
FanGroup async_create_preview_fan(HomeAssistant hass, str name, dict[str, Any] validated_config)
Definition: fan.py:99
None async_setup_entry(HomeAssistant hass, ConfigEntry config_entry, AddEntitiesCallback async_add_entities)
Definition: fan.py:86
bool attribute_equal(list[State] states, str key)
Definition: util.py:35
Any|None most_frequent_attribute(list[State] states, str key)
Definition: util.py:43
Any reduce_attribute(list[State] states, str key, Any|None default=None, Callable[..., Any] reduce=mean_int)
Definition: util.py:72