Home Assistant Unofficial Reference 2024.12.1
diagnostics.py
Go to the documentation of this file.
1 """Diagnostics support for Asuswrt."""
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 (
11  ATTR_CONNECTIONS,
12  ATTR_IDENTIFIERS,
13  CONF_PASSWORD,
14  CONF_UNIQUE_ID,
15  CONF_USERNAME,
16 )
17 from homeassistant.core import HomeAssistant
18 from homeassistant.helpers import device_registry as dr, entity_registry as er
19 
20 from . import AsusWrtConfigEntry
21 
22 TO_REDACT = {CONF_PASSWORD, CONF_UNIQUE_ID, CONF_USERNAME}
23 TO_REDACT_DEV = {ATTR_CONNECTIONS, ATTR_IDENTIFIERS}
24 
25 
27  hass: HomeAssistant, entry: AsusWrtConfigEntry
28 ) -> dict[str, dict[str, Any]]:
29  """Return diagnostics for a config entry."""
30  data = {"entry": async_redact_data(entry.as_dict(), TO_REDACT)}
31 
32  router = entry.runtime_data
33 
34  # Gather information how this AsusWrt device is represented in Home Assistant
35  device_registry = dr.async_get(hass)
36  entity_registry = er.async_get(hass)
37  hass_device = device_registry.async_get_device(
38  identifiers=router.device_info[ATTR_IDENTIFIERS]
39  )
40  if not hass_device:
41  return data
42 
43  data["device"] = {
44  **async_redact_data(attr.asdict(hass_device), TO_REDACT_DEV),
45  "entities": {},
46  "tracked_devices": [],
47  }
48 
49  hass_entities = er.async_entries_for_device(
50  entity_registry,
51  device_id=hass_device.id,
52  include_disabled_entities=True,
53  )
54 
55  for entity_entry in hass_entities:
56  state = hass.states.get(entity_entry.entity_id)
57  state_dict = None
58  if state:
59  state_dict = dict(state.as_dict())
60  # The entity_id is already provided at root level.
61  state_dict.pop("entity_id", None)
62  # The context doesn't provide useful information in this case.
63  state_dict.pop("context", None)
64 
65  data["device"]["entities"][entity_entry.entity_id] = {
67  attr.asdict(
68  entity_entry, filter=lambda attr, value: attr.name != "entity_id"
69  ),
70  TO_REDACT,
71  ),
72  "state": state_dict,
73  }
74 
75  for device in router.devices.values():
76  data["device"]["tracked_devices"].append(
77  {
78  "name": device.name or "Unknown device",
79  "ip_address": device.ip_address,
80  "last_activity": device.last_activity,
81  }
82  )
83 
84  return data
dict[str, dict[str, Any]] async_get_config_entry_diagnostics(HomeAssistant hass, AsusWrtConfigEntry entry)
Definition: diagnostics.py:28
dict async_redact_data(Mapping data, Iterable[Any] to_redact)
Definition: util.py:14