Home Assistant Unofficial Reference 2024.12.1
logbook.py
Go to the documentation of this file.
1 """Describe lutron_caseta logbook events."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Callable
6 
7 from homeassistant.components.logbook import LOGBOOK_ENTRY_MESSAGE, LOGBOOK_ENTRY_NAME
8 from homeassistant.const import ATTR_DEVICE_ID
9 from homeassistant.core import Event, HomeAssistant, callback
10 
11 from .const import (
12  ATTR_ACTION,
13  ATTR_AREA_NAME,
14  ATTR_DEVICE_NAME,
15  ATTR_LEAP_BUTTON_NUMBER,
16  ATTR_TYPE,
17  DOMAIN,
18  LUTRON_CASETA_BUTTON_EVENT,
19 )
20 from .device_trigger import (
21  LEAP_TO_DEVICE_TYPE_SUBTYPE_MAP,
22  _reverse_dict,
23  get_lutron_data_by_dr_id,
24 )
25 
26 
27 @callback
29  hass: HomeAssistant,
30  async_describe_event: Callable[[str, str, Callable[[Event], dict[str, str]]], None],
31 ) -> None:
32  """Describe logbook events."""
33 
34  @callback
35  def async_describe_button_event(event: Event) -> dict[str, str]:
36  """Describe lutron_caseta_button_event logbook event."""
37 
38  data = event.data
39  device_type = data[ATTR_TYPE]
40  leap_button_number = data[ATTR_LEAP_BUTTON_NUMBER]
41  dr_device_id = data[ATTR_DEVICE_ID]
42  rev_button_map: dict[int, str] | None = None
43  keypad_button_names_to_leap: dict[int, dict[str, int]] = {}
44  keypad_id: int = -1
45 
46  if lutron_data := get_lutron_data_by_dr_id(hass, dr_device_id):
47  keypad_data = lutron_data.keypad_data
48  keypad = keypad_data.dr_device_id_to_keypad.get(dr_device_id)
49  keypad_id = keypad["lutron_device_id"]
50  keypad_button_names_to_leap = keypad_data.button_names_to_leap
51 
52  if not (rev_button_map := LEAP_TO_DEVICE_TYPE_SUBTYPE_MAP.get(device_type)):
53  if fwd_button_map := keypad_button_names_to_leap.get(keypad_id):
54  rev_button_map = _reverse_dict(fwd_button_map)
55 
56  if rev_button_map is None:
57  return {
58  LOGBOOK_ENTRY_NAME: f"{data[ATTR_AREA_NAME]} {data[ATTR_DEVICE_NAME]}",
59  LOGBOOK_ENTRY_MESSAGE: (
60  f"{data[ATTR_ACTION]} Error retrieving button description"
61  ),
62  }
63 
64  button_description = rev_button_map.get(leap_button_number)
65  return {
66  LOGBOOK_ENTRY_NAME: f"{data[ATTR_AREA_NAME]} {data[ATTR_DEVICE_NAME]}",
67  LOGBOOK_ENTRY_MESSAGE: f"{data[ATTR_ACTION]} {button_description}",
68  }
69 
70  async_describe_event(
71  DOMAIN, LUTRON_CASETA_BUTTON_EVENT, async_describe_button_event
72  )
def get_lutron_data_by_dr_id(HomeAssistant hass, str device_id)
None async_describe_events(HomeAssistant hass, Callable[[str, str, Callable[[Event], dict[str, str]]], None] async_describe_event)
Definition: logbook.py:31