Home Assistant Unofficial Reference 2024.12.1
logbook.py
Go to the documentation of this file.
1 """Describe Shelly 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_CHANNEL,
13  ATTR_CLICK_TYPE,
14  ATTR_DEVICE,
15  BLOCK_INPUTS_EVENTS_TYPES,
16  DOMAIN,
17  EVENT_SHELLY_CLICK,
18  RPC_INPUTS_EVENTS_TYPES,
19 )
20 from .coordinator import (
21  get_block_coordinator_by_device_id,
22  get_rpc_coordinator_by_device_id,
23 )
24 from .utils import get_rpc_entity_name
25 
26 
27 @callback
29  hass: HomeAssistant,
30  async_describe_event: Callable[[str, str, Callable[[Event], dict]], None],
31 ) -> None:
32  """Describe logbook events."""
33 
34  @callback
35  def async_describe_shelly_click_event(event: Event) -> dict[str, str]:
36  """Describe shelly.click logbook event (block device)."""
37  device_id = event.data[ATTR_DEVICE_ID]
38  click_type = event.data[ATTR_CLICK_TYPE]
39  channel = event.data[ATTR_CHANNEL]
40  input_name = f"{event.data[ATTR_DEVICE]} channel {channel}"
41 
42  if click_type in RPC_INPUTS_EVENTS_TYPES:
43  rpc_coordinator = get_rpc_coordinator_by_device_id(hass, device_id)
44  if rpc_coordinator and rpc_coordinator.device.initialized:
45  key = f"input:{channel-1}"
46  input_name = get_rpc_entity_name(rpc_coordinator.device, key)
47 
48  elif click_type in BLOCK_INPUTS_EVENTS_TYPES:
49  block_coordinator = get_block_coordinator_by_device_id(hass, device_id)
50  if block_coordinator and block_coordinator.device.initialized:
51  input_name = f"{block_coordinator.device.name} channel {channel}"
52 
53  return {
54  LOGBOOK_ENTRY_NAME: "Shelly",
55  LOGBOOK_ENTRY_MESSAGE: (
56  f"'{click_type}' click event for {input_name} Input was fired"
57  ),
58  }
59 
60  async_describe_event(DOMAIN, EVENT_SHELLY_CLICK, async_describe_shelly_click_event)
ShellyRpcCoordinator|None get_rpc_coordinator_by_device_id(HomeAssistant hass, str device_id)
Definition: coordinator.py:830
ShellyBlockCoordinator|None get_block_coordinator_by_device_id(HomeAssistant hass, str device_id)
Definition: coordinator.py:810
None async_describe_events(HomeAssistant hass, Callable[[str, str, Callable[[Event], dict]], None] async_describe_event)
Definition: logbook.py:31
str get_rpc_entity_name(RpcDevice device, str key, str|None description=None)
Definition: utils.py:343