Home Assistant Unofficial Reference 2024.12.1
trace.py
Go to the documentation of this file.
1 """Trace support for automation."""
2 
3 from __future__ import annotations
4 
5 from collections.abc import Generator
6 from contextlib import contextmanager
7 from typing import Any
8 
10  CONF_STORED_TRACES,
11  ActionTrace,
12  async_store_trace,
13 )
14 from homeassistant.core import Context, HomeAssistant
15 from homeassistant.helpers.typing import ConfigType
16 
17 from .const import DOMAIN
18 
19 
20 class AutomationTrace(ActionTrace):
21  """Container for automation trace."""
22 
23  _domain = DOMAIN
24 
25  def __init__(
26  self,
27  item_id: str | None,
28  config: ConfigType | None,
29  blueprint_inputs: ConfigType | None,
30  context: Context,
31  ) -> None:
32  """Container for automation trace."""
33  super().__init__(item_id, config, blueprint_inputs, context)
34  self._trigger_description_trigger_description: str | None = None
35 
36  def set_trigger_description(self, trigger: str) -> None:
37  """Set trigger description."""
38  self._trigger_description_trigger_description = trigger
39 
40  def as_short_dict(self) -> dict[str, Any]:
41  """Return a brief dictionary version of this AutomationTrace."""
42  if self._short_dict:
43  return self._short_dict
44 
45  result = super().as_short_dict()
46  result["trigger"] = self._trigger_description_trigger_description
47  return result
48 
49 
50 @contextmanager
52  hass: HomeAssistant,
53  automation_id: str | None,
54  config: ConfigType | None,
55  blueprint_inputs: ConfigType | None,
56  context: Context,
57  trace_config: ConfigType,
58 ) -> Generator[AutomationTrace]:
59  """Trace action execution of automation with automation_id."""
60  trace = AutomationTrace(automation_id, config, blueprint_inputs, context)
61  async_store_trace(hass, trace, trace_config[CONF_STORED_TRACES])
62 
63  try:
64  yield trace
65  except Exception as ex:
66  if automation_id:
67  trace.set_error(ex)
68  raise
69  finally:
70  if automation_id:
71  trace.finished()
None __init__(self, str|None item_id, ConfigType|None config, ConfigType|None blueprint_inputs, Context context)
Definition: trace.py:31
Generator[AutomationTrace] trace_automation(HomeAssistant hass, str|None automation_id, ConfigType|None config, ConfigType|None blueprint_inputs, Context context, ConfigType trace_config)
Definition: trace.py:58
None async_store_trace(HomeAssistant hass, ActionTrace trace, int stored_traces)
Definition: util.py:83