diagnostics.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. """Diagnostics support for tuya-local."""
  2. from __future__ import annotations
  3. from typing import Any
  4. from homeassistant.components.diagnostics import REDACTED
  5. from homeassistant.config_entries import ConfigEntry
  6. from homeassistant.const import CONF_HOST
  7. from homeassistant.core import HomeAssistant, callback
  8. from homeassistant.helpers import device_registry as dr
  9. from homeassistant.helpers import entity_registry as er
  10. from homeassistant.helpers.device_registry import DeviceEntry
  11. from tinytuya import __version__ as tinytuya_version
  12. from .const import (
  13. API_PROTOCOL_VERSIONS,
  14. CONF_DEVICE_CID,
  15. CONF_PROTOCOL_VERSION,
  16. CONF_TYPE,
  17. DOMAIN,
  18. )
  19. from .device import TuyaLocalDevice
  20. from .helpers.config import get_device_id
  21. async def async_get_config_entry_diagnostics(
  22. hass: HomeAssistant, entry: ConfigEntry
  23. ) -> dict[str, Any]:
  24. """Return diagnostics for a config entry."""
  25. return _async_get_diagnostics(hass, entry)
  26. async def async_get_device_diagnostics(
  27. hass: HomeAssistant, entry: ConfigEntry, device: DeviceEntry
  28. ) -> dict[str, Any]:
  29. """Return diagnostics for a device entry."""
  30. return _async_get_diagnostics(hass, entry, device)
  31. @callback
  32. def _async_get_diagnostics(
  33. hass: HomeAssistant,
  34. entry: ConfigEntry,
  35. device: DeviceEntry | None = None,
  36. ) -> dict[str, Any]:
  37. """Return diagnostics for a tuya-local config entry."""
  38. hass_data = hass.data[DOMAIN][get_device_id(entry.data)]
  39. hostname = entry.data.get(CONF_HOST, "")
  40. data = {
  41. "name": entry.title,
  42. "type": entry.data[CONF_TYPE],
  43. "device_id": REDACTED,
  44. "device_cid": REDACTED if entry.data.get(CONF_DEVICE_CID, "") != "" else "",
  45. "local_key": REDACTED,
  46. "host": REDACTED
  47. if hostname != "" and hostname.casefold() != "auto"
  48. else hostname,
  49. "protocol_version": entry.data[CONF_PROTOCOL_VERSION],
  50. "tinytuya_version": tinytuya_version,
  51. }
  52. # The DeviceEntry also has interesting looking data, but this
  53. # integration does not publish anything to it other than some hardcoded
  54. # values that don't change between devices. Instead get the live data
  55. # from the running hass.
  56. data |= _async_device_as_dict(hass, hass_data["device"])
  57. return data
  58. def redact_dps(device: TuyaLocalDevice, dps: dict[str, Any]) -> dict[str, Any]:
  59. """Redact any sensitive data from a list of dps"""
  60. sensitive = []
  61. for entity in device._children:
  62. for dp in entity._config.dps():
  63. if dp.sensitive:
  64. sensitive.append(dp.id)
  65. return {k: (REDACTED if k in sensitive else v) for (k, v) in dps.items()}
  66. def redact_entity(
  67. device: TuyaLocalDevice,
  68. entity_unique_id: str | None,
  69. state_dict: dict[str, Any],
  70. ) -> dict[str, Any]:
  71. """Redact any sensitive dps from an entity's state.
  72. Sensitive dps the entity publishes as extra attributes are redacted by
  73. name. A sensitive dp consumed by the platform itself, such as a text
  74. entity's `value`, is reported as the state instead, so the state is
  75. redacted only when it actually carries that dp's value - blanking it
  76. unconditionally would discard useful states such as a camera's
  77. `recording`, whose sensitive `snapshot` dp is never the state.
  78. """
  79. names = []
  80. values = []
  81. redacted = dict(state_dict)
  82. # Context is not useful information
  83. redacted.pop("context", None)
  84. # Redact entity_picture in case it is sensitive
  85. if "entity_picture" in redacted.get("attributes"):
  86. redacted["attributes"] = {
  87. **redacted["attributes"],
  88. "entity_picture": REDACTED,
  89. }
  90. for entity in device._children:
  91. if entity._config.unique_id(device.unique_id) != entity_unique_id:
  92. continue
  93. for dp in entity._config.dps():
  94. if not dp.sensitive:
  95. continue
  96. names.append(dp.name)
  97. value = dp.get_value(device)
  98. if value is not None:
  99. values.append(str(value))
  100. if not names:
  101. return redacted
  102. if isinstance(redacted.get("attributes"), dict):
  103. redacted["attributes"] = {
  104. k: (REDACTED if k in names else v)
  105. for (k, v) in redacted["attributes"].items()
  106. }
  107. if "state" in redacted and str(redacted["state"]) in values:
  108. redacted["state"] = REDACTED
  109. return redacted
  110. @callback
  111. def _async_device_as_dict(
  112. hass: HomeAssistant, device: TuyaLocalDevice
  113. ) -> dict[str, Any]:
  114. """Represent a Tuya Local device as a dictionary."""
  115. # Base device information, without sensitive information
  116. data = {
  117. "name": device.name,
  118. "api_version_set": device._api.version,
  119. "api_version_used": (
  120. "none"
  121. if device._api_protocol_version_index is None
  122. else API_PROTOCOL_VERSIONS[device._api_protocol_version_index]
  123. ),
  124. "api_working": device._api_protocol_working,
  125. "status": device._api.dps_cache,
  126. "cached_state": redact_dps(device, device._cached_state),
  127. "pending_state": redact_dps(device, device._pending_updates),
  128. "connected": device._running,
  129. "force_dps": device._force_dps,
  130. }
  131. device_registry = dr.async_get(hass)
  132. entity_registry = er.async_get(hass)
  133. hass_device = device_registry.async_get_device(
  134. identifiers={(DOMAIN, device.unique_id)}
  135. )
  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. hass_entities = er.async_entries_for_device(
  145. entity_registry,
  146. device_id=hass_device.id,
  147. include_disabled_entities=True,
  148. )
  149. for entity_entry in hass_entities:
  150. state = hass.states.get(entity_entry.entity_id)
  151. state_dict = None
  152. if state:
  153. state_dict = redact_entity(
  154. device,
  155. entity_entry.unique_id,
  156. state.as_dict(),
  157. )
  158. data["home_assistant"]["entities"].append(
  159. {
  160. "disabled": entity_entry.disabled,
  161. "disabled_by": entity_entry.disabled_by,
  162. "entity_category": entity_entry.entity_category,
  163. "device_class": entity_entry.device_class,
  164. "original_device_class": entity_entry.original_device_class,
  165. "icon": entity_entry.icon,
  166. "unit_of_measurement": entity_entry.unit_of_measurement,
  167. "state": state_dict,
  168. }
  169. )
  170. return data