Home Assistant Unofficial Reference 2024.12.1
diagnostics.py
Go to the documentation of this file.
1 """Diagnostics support for Nut."""
2 
3 from __future__ import annotations
4 
5 from typing import Any
6 
7 import attr
8 
9 from homeassistant.components.diagnostics import async_redact_data
10 from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
11 from homeassistant.core import HomeAssistant
12 from homeassistant.helpers import device_registry as dr, entity_registry as er
13 
14 from . import NutConfigEntry
15 from .const import DOMAIN
16 
17 TO_REDACT = {CONF_PASSWORD, CONF_USERNAME}
18 
19 
21  hass: HomeAssistant, entry: NutConfigEntry
22 ) -> dict[str, dict[str, Any]]:
23  """Return diagnostics for a config entry."""
24  data = {"entry": async_redact_data(entry.as_dict(), TO_REDACT)}
25  hass_data = entry.runtime_data
26 
27  # Get information from Nut library
28  nut_data = hass_data.data
29  nut_cmd = hass_data.user_available_commands
30  data["nut_data"] = {
31  "ups_list": nut_data.ups_list,
32  "status": nut_data.status,
33  "commands": nut_cmd,
34  }
35 
36  # Gather information how this Nut device is represented in Home Assistant
37  device_registry = dr.async_get(hass)
38  entity_registry = er.async_get(hass)
39  hass_device = device_registry.async_get_device(
40  identifiers={(DOMAIN, hass_data.unique_id)}
41  )
42  if not hass_device:
43  return data
44 
45  data["device"] = {
46  **attr.asdict(hass_device),
47  "entities": {},
48  }
49 
50  hass_entities = er.async_entries_for_device(
51  entity_registry,
52  device_id=hass_device.id,
53  include_disabled_entities=True,
54  )
55 
56  for entity_entry in hass_entities:
57  state = hass.states.get(entity_entry.entity_id)
58  state_dict = None
59  if state:
60  state_dict = dict(state.as_dict())
61  # The entity_id is already provided at root level.
62  state_dict.pop("entity_id", None)
63  # The context doesn't provide useful information in this case.
64  state_dict.pop("context", None)
65 
66  data["device"]["entities"][entity_entry.entity_id] = {
67  **attr.asdict(
68  entity_entry, filter=lambda attr, value: attr.name != "entity_id"
69  ),
70  "state": state_dict,
71  }
72 
73  return data
dict async_redact_data(Mapping data, Iterable[Any] to_redact)
Definition: util.py:14
dict[str, dict[str, Any]] async_get_config_entry_diagnostics(HomeAssistant hass, NutConfigEntry entry)
Definition: diagnostics.py:22