Home Assistant Unofficial Reference 2024.12.1
__init__.py
Go to the documentation of this file.
1 """Support for script and automation tracing and debugging."""
2 
3 from __future__ import annotations
4 
5 import logging
6 
7 import voluptuous as vol
8 
9 from homeassistant.const import EVENT_HOMEASSISTANT_STOP
10 from homeassistant.core import Event, HomeAssistant
11 from homeassistant.exceptions import HomeAssistantError
13 from homeassistant.helpers.json import ExtendedJSONEncoder
14 from homeassistant.helpers.storage import Store
15 from homeassistant.helpers.typing import ConfigType
16 
17 from . import websocket_api
18 from .const import (
19  CONF_STORED_TRACES,
20  DATA_TRACE,
21  DATA_TRACE_STORE,
22  DEFAULT_STORED_TRACES,
23 )
24 from .models import ActionTrace
25 from .util import async_store_trace
26 
27 _LOGGER = logging.getLogger(__name__)
28 
29 DOMAIN = "trace"
30 
31 STORAGE_KEY = "trace.saved_traces"
32 STORAGE_VERSION = 1
33 
34 TRACE_CONFIG_SCHEMA = {
35  vol.Optional(CONF_STORED_TRACES, default=DEFAULT_STORED_TRACES): cv.positive_int
36 }
37 
38 CONFIG_SCHEMA = cv.empty_config_schema(DOMAIN)
39 
40 __all__ = [
41  "CONF_STORED_TRACES",
42  "TRACE_CONFIG_SCHEMA",
43  "ActionTrace",
44  "async_store_trace",
45 ]
46 
47 
48 async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
49  """Initialize the trace integration."""
50  hass.data[DATA_TRACE] = {}
51  websocket_api.async_setup(hass)
52  store = Store[dict[str, list]](
53  hass, STORAGE_VERSION, STORAGE_KEY, encoder=ExtendedJSONEncoder
54  )
55  hass.data[DATA_TRACE_STORE] = store
56 
57  async def _async_store_traces_at_stop(_: Event) -> None:
58  """Save traces to storage."""
59  _LOGGER.debug("Storing traces")
60  try:
61  await store.async_save(
62  {
63  key: list(traces.values())
64  for key, traces in hass.data[DATA_TRACE].items()
65  }
66  )
67  except HomeAssistantError as exc:
68  _LOGGER.error("Error storing traces", exc_info=exc)
69 
70  # Store traces when stopping hass
71  hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_store_traces_at_stop)
72 
73  return True
bool async_setup(HomeAssistant hass, ConfigType config)
Definition: __init__.py:48