Home Assistant Unofficial Reference 2024.12.1
group.py
Go to the documentation of this file.
1 """Helper for groups."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Iterable
6 from typing import Any
7 
8 from homeassistant.const import ATTR_ENTITY_ID, ENTITY_MATCH_ALL, ENTITY_MATCH_NONE
9 from homeassistant.core import HomeAssistant
10 
11 ENTITY_PREFIX = "group."
12 
13 
14 def expand_entity_ids(hass: HomeAssistant, entity_ids: Iterable[Any]) -> list[str]:
15  """Return entity_ids with group entity ids replaced by their members.
16 
17  Async friendly.
18  """
19  found_ids: list[str] = []
20  for entity_id in entity_ids:
21  if not isinstance(entity_id, str) or entity_id in (
22  ENTITY_MATCH_NONE,
23  ENTITY_MATCH_ALL,
24  ):
25  continue
26 
27  entity_id = entity_id.lower()
28  # If entity_id points at a group, expand it
29  if entity_id.startswith(ENTITY_PREFIX):
30  child_entities = get_entity_ids(hass, entity_id)
31  if entity_id in child_entities:
32  child_entities = list(child_entities)
33  child_entities.remove(entity_id)
34  found_ids.extend(
35  ent_id
36  for ent_id in expand_entity_ids(hass, child_entities)
37  if ent_id not in found_ids
38  )
39  elif entity_id not in found_ids:
40  found_ids.append(entity_id)
41 
42  return found_ids
43 
44 
46  hass: HomeAssistant, entity_id: str, domain_filter: str | None = None
47 ) -> list[str]:
48  """Get members of this group.
49 
50  Async friendly.
51  """
52  group = hass.states.get(entity_id)
53  if not group or ATTR_ENTITY_ID not in group.attributes:
54  return []
55  entity_ids: list[str] = group.attributes[ATTR_ENTITY_ID]
56  if not domain_filter:
57  return entity_ids
58  domain_filter = f"{domain_filter.lower()}."
59  return [ent_id for ent_id in entity_ids if ent_id.startswith(domain_filter)]
list[str] get_entity_ids(HomeAssistant hass, str entity_id, str|None domain_filter=None)
Definition: group.py:47
list[str] expand_entity_ids(HomeAssistant hass, Iterable[Any] entity_ids)
Definition: group.py:14