Home Assistant Unofficial Reference 2024.12.1
entity_loader.py
Go to the documentation of this file.
1 """Axis network device entity loader.
2 
3 Central point to load entities for the different platforms.
4 """
5 
6 from __future__ import annotations
7 
8 from typing import TYPE_CHECKING
9 
10 from axis.models.event import Event, EventOperation, EventTopic
11 
12 from homeassistant.core import callback
13 from homeassistant.helpers.entity_platform import AddEntitiesCallback
14 
15 from ..entity import AxisEventDescription, AxisEventEntity
16 
17 if TYPE_CHECKING:
18  from .hub import AxisHub
19 
20 
22  """Axis network device integration handling platforms for entity registration."""
23 
24  def __init__(self, hub: AxisHub) -> None:
25  """Initialize the Axis entity loader."""
26  self.hubhub = hub
27 
28  self.registered_events: set[tuple[str, EventTopic, str]] = set()
29  self.topic_to_entity: dict[
30  EventTopic,
31  list[
32  tuple[
33  AddEntitiesCallback,
34  type[AxisEventEntity],
35  AxisEventDescription,
36  ]
37  ],
38  ] = {}
39 
40  @callback
42  self,
43  async_add_entities: AddEntitiesCallback,
44  entity_class: type[AxisEventEntity],
45  descriptions: tuple[AxisEventDescription, ...],
46  ) -> None:
47  """Register Axis entity platforms."""
48  topics: tuple[EventTopic, ...]
49  for description in descriptions:
50  if isinstance(description.event_topic, EventTopic):
51  topics = (description.event_topic,)
52  else:
53  topics = description.event_topic
54  for topic in topics:
55  self.topic_to_entity.setdefault(topic, []).append(
56  (async_add_entities, entity_class, description)
57  )
58 
59  @callback
60  def _create_entities_from_event(self, event: Event) -> None:
61  """Create Axis entities from event."""
62  event_id = (event.topic, event.topic_base, event.id)
63  if event_id in self.registered_events:
64  # Device has restarted and all events are initialized anew
65  return
66  self.registered_events.add(event_id)
67  for (
68  async_add_entities,
69  entity_class,
70  description,
71  ) in self.topic_to_entity[event.topic_base]:
72  if not description.supported_fn(self.hubhub, event):
73  continue
74  async_add_entities([entity_class(self.hubhub, description, event)])
75 
76  @callback
77  def initialize_platforms(self) -> None:
78  """Prepare event listener that can populate platform entities."""
79  self.hubhub.api.event.subscribe(
80  self._create_entities_from_event_create_entities_from_event,
81  topic_filter=tuple(self.topic_to_entity.keys()),
82  operation_filter=EventOperation.INITIALIZED,
83  )
None register_platform(self, AddEntitiesCallback async_add_entities, type[AxisEventEntity] entity_class, tuple[AxisEventDescription,...] descriptions)
bool add(self, _T matcher)
Definition: match.py:185