Home Assistant Unofficial Reference 2024.12.1
diagnostics.py
Go to the documentation of this file.
1 """Diagnostics support for Tuya."""
2 
3 from __future__ import annotations
4 
5 from contextlib import suppress
6 import json
7 from typing import Any, cast
8 
9 from tuya_sharing import CustomerDevice
10 
11 from homeassistant.components.diagnostics import REDACTED
12 from homeassistant.core import HomeAssistant, callback
13 from homeassistant.helpers import device_registry as dr, entity_registry as er
14 from homeassistant.helpers.device_registry import DeviceEntry
15 from homeassistant.util import dt as dt_util
16 
17 from . import TuyaConfigEntry
18 from .const import DOMAIN, DPCode
19 
20 
22  hass: HomeAssistant, entry: TuyaConfigEntry
23 ) -> dict[str, Any]:
24  """Return diagnostics for a config entry."""
25  return _async_get_diagnostics(hass, entry)
26 
27 
29  hass: HomeAssistant, entry: TuyaConfigEntry, device: DeviceEntry
30 ) -> dict[str, Any]:
31  """Return diagnostics for a device entry."""
32  return _async_get_diagnostics(hass, entry, device)
33 
34 
35 @callback
37  hass: HomeAssistant,
38  entry: TuyaConfigEntry,
39  device: DeviceEntry | None = None,
40 ) -> dict[str, Any]:
41  """Return diagnostics for a config entry."""
42  hass_data = entry.runtime_data
43 
44  mqtt_connected = None
45  if hass_data.manager.mq.client:
46  mqtt_connected = hass_data.manager.mq.client.is_connected()
47 
48  data = {
49  "endpoint": hass_data.manager.customer_api.endpoint,
50  "terminal_id": hass_data.manager.terminal_id,
51  "mqtt_connected": mqtt_connected,
52  "disabled_by": entry.disabled_by,
53  "disabled_polling": entry.pref_disable_polling,
54  }
55 
56  if device:
57  tuya_device_id = next(iter(device.identifiers))[1]
58  data |= _async_device_as_dict(
59  hass, hass_data.manager.device_map[tuya_device_id]
60  )
61  else:
62  data.update(
63  devices=[
64  _async_device_as_dict(hass, device)
65  for device in hass_data.manager.device_map.values()
66  ]
67  )
68 
69  return data
70 
71 
72 @callback
74  hass: HomeAssistant, device: CustomerDevice
75 ) -> dict[str, Any]:
76  """Represent a Tuya device as a dictionary."""
77 
78  # Base device information, without sensitive information.
79  data = {
80  "id": device.id,
81  "name": device.name,
82  "category": device.category,
83  "product_id": device.product_id,
84  "product_name": device.product_name,
85  "online": device.online,
86  "sub": device.sub,
87  "time_zone": device.time_zone,
88  "active_time": dt_util.utc_from_timestamp(device.active_time).isoformat(),
89  "create_time": dt_util.utc_from_timestamp(device.create_time).isoformat(),
90  "update_time": dt_util.utc_from_timestamp(device.update_time).isoformat(),
91  "function": {},
92  "status_range": {},
93  "status": {},
94  "home_assistant": {},
95  "set_up": device.set_up,
96  "support_local": device.support_local,
97  }
98 
99  # Gather Tuya states
100  for dpcode, value in device.status.items():
101  # These statuses may contain sensitive information, redact these..
102  if dpcode in {DPCode.ALARM_MESSAGE, DPCode.MOVEMENT_DETECT_PIC}:
103  data["status"][dpcode] = REDACTED
104  continue
105 
106  with suppress(ValueError, TypeError):
107  value = json.loads(value)
108  data["status"][dpcode] = value
109 
110  # Gather Tuya functions
111  for function in device.function.values():
112  value = function.values
113  with suppress(ValueError, TypeError, AttributeError):
114  value = json.loads(cast(str, function.values))
115 
116  data["function"][function.code] = {
117  "type": function.type,
118  "value": value,
119  }
120 
121  # Gather Tuya status ranges
122  for status_range in device.status_range.values():
123  value = status_range.values
124  with suppress(ValueError, TypeError, AttributeError):
125  value = json.loads(status_range.values)
126 
127  data["status_range"][status_range.code] = {
128  "type": status_range.type,
129  "value": value,
130  }
131 
132  # Gather information how this Tuya device is represented in Home Assistant
133  device_registry = dr.async_get(hass)
134  entity_registry = er.async_get(hass)
135  hass_device = device_registry.async_get_device(identifiers={(DOMAIN, device.id)})
136  if hass_device:
137  data["home_assistant"] = {
138  "name": hass_device.name,
139  "name_by_user": hass_device.name_by_user,
140  "disabled": hass_device.disabled,
141  "disabled_by": hass_device.disabled_by,
142  "entities": [],
143  }
144 
145  hass_entities = er.async_entries_for_device(
146  entity_registry,
147  device_id=hass_device.id,
148  include_disabled_entities=True,
149  )
150 
151  for entity_entry in hass_entities:
152  state = hass.states.get(entity_entry.entity_id)
153  state_dict: dict[str, Any] | None = None
154  if state:
155  state_dict = dict(state.as_dict())
156 
157  # Redact the `entity_picture` attribute as it contains a token.
158  if "entity_picture" in state_dict["attributes"]:
159  state_dict["attributes"] = {
160  **state_dict["attributes"],
161  "entity_picture": REDACTED,
162  }
163 
164  # The context doesn't provide useful information in this case.
165  state_dict.pop("context", None)
166 
167  data["home_assistant"]["entities"].append(
168  {
169  "disabled": entity_entry.disabled,
170  "disabled_by": entity_entry.disabled_by,
171  "entity_category": entity_entry.entity_category,
172  "device_class": entity_entry.device_class,
173  "original_device_class": entity_entry.original_device_class,
174  "icon": entity_entry.icon,
175  "original_icon": entity_entry.original_icon,
176  "unit_of_measurement": entity_entry.unit_of_measurement,
177  "state": state_dict,
178  }
179  )
180 
181  return data
dict[str, Any] async_get_config_entry_diagnostics(HomeAssistant hass, TuyaConfigEntry entry)
Definition: diagnostics.py:23
dict[str, Any] _async_get_diagnostics(HomeAssistant hass, TuyaConfigEntry entry, DeviceEntry|None device=None)
Definition: diagnostics.py:40
dict[str, Any] async_get_device_diagnostics(HomeAssistant hass, TuyaConfigEntry entry, DeviceEntry device)
Definition: diagnostics.py:30
dict[str, Any] _async_device_as_dict(HomeAssistant hass, CustomerDevice device)
Definition: diagnostics.py:75