Home Assistant Unofficial Reference 2024.12.1
logbook.py
Go to the documentation of this file.
1 """Describe mobile_app logbook events."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable
6 from typing import Any
7 
9  LOGBOOK_ENTRY_ENTITY_ID,
10  LOGBOOK_ENTRY_ICON,
11  LOGBOOK_ENTRY_MESSAGE,
12  LOGBOOK_ENTRY_NAME,
13 )
14 from homeassistant.const import ATTR_FRIENDLY_NAME, ATTR_ICON
15 from homeassistant.core import Event, HomeAssistant, callback
16 from homeassistant.util.event_type import EventType
17 
18 from .const import DOMAIN
19 
20 IOS_EVENT_ZONE_ENTERED = "ios.zone_entered"
21 IOS_EVENT_ZONE_EXITED = "ios.zone_exited"
22 
23 ATTR_ZONE = "zone"
24 ATTR_SOURCE_DEVICE_NAME = "sourceDeviceName"
25 ATTR_SOURCE_DEVICE_ID = "sourceDeviceID"
26 EVENT_TO_DESCRIPTION: dict[EventType[Any] | str, str] = {
27  IOS_EVENT_ZONE_ENTERED: "entered zone",
28  IOS_EVENT_ZONE_EXITED: "exited zone",
29 }
30 
31 
32 @callback
34  hass: HomeAssistant,
35  async_describe_event: Callable[[str, str, Callable[[Event], dict[str, str]]], None],
36 ) -> None:
37  """Describe logbook events."""
38 
39  @callback
40  def async_describe_zone_event(event: Event) -> dict[str, str]:
41  """Describe mobile_app logbook event."""
42  data = event.data
43  event_description = EVENT_TO_DESCRIPTION[event.event_type]
44  zone_entity_id = data.get(ATTR_ZONE)
45  source_device_name = data.get(
46  ATTR_SOURCE_DEVICE_NAME, data.get(ATTR_SOURCE_DEVICE_ID)
47  )
48  zone_name = None
49  zone_icon = None
50  if zone_entity_id and (zone_state := hass.states.get(zone_entity_id)):
51  zone_name = zone_state.attributes.get(ATTR_FRIENDLY_NAME)
52  zone_icon = zone_state.attributes.get(ATTR_ICON)
53  description = {
54  LOGBOOK_ENTRY_NAME: source_device_name,
55  LOGBOOK_ENTRY_MESSAGE: f"{event_description} {zone_name or zone_entity_id}",
56  LOGBOOK_ENTRY_ICON: zone_icon or "mdi:crosshairs-gps",
57  }
58  if zone_entity_id:
59  description[LOGBOOK_ENTRY_ENTITY_ID] = zone_entity_id
60  return description
61 
62  async_describe_event(DOMAIN, IOS_EVENT_ZONE_ENTERED, async_describe_zone_event)
63  async_describe_event(DOMAIN, IOS_EVENT_ZONE_EXITED, async_describe_zone_event)
None async_describe_events(HomeAssistant hass, Callable[[str, str, Callable[[Event], dict[str, str]]], None] async_describe_event)
Definition: logbook.py:36