diagnostics.py 6.8 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. for entity in device._children:
  82. if entity._config.unique_id(device.unique_id) != entity_unique_id:
  83. continue
  84. for dp in entity._config.dps():
  85. if not dp.sensitive:
  86. continue
  87. names.append(dp.name)
  88. value = dp.get_value(device)
  89. if value is not None:
  90. values.append(str(value))
  91. if not names:
  92. return state_dict
  93. redacted = dict(state_dict)
  94. if isinstance(redacted.get("attributes"), dict):
  95. redacted["attributes"] = {
  96. k: (REDACTED if k in names else v)
  97. for (k, v) in redacted["attributes"].items()
  98. }
  99. if "state" in redacted and str(redacted["state"]) in values:
  100. redacted["state"] = REDACTED
  101. return redacted
  102. @callback
  103. def _async_device_as_dict(
  104. hass: HomeAssistant, device: TuyaLocalDevice
  105. ) -> dict[str, Any]:
  106. """Represent a Tuya Local device as a dictionary."""
  107. # Base device information, without sensitive information
  108. data = {
  109. "name": device.name,
  110. "api_version_set": device._api.version,
  111. "api_version_used": (
  112. "none"
  113. if device._api_protocol_version_index is None
  114. else API_PROTOCOL_VERSIONS[device._api_protocol_version_index]
  115. ),
  116. "api_working": device._api_protocol_working,
  117. "status": device._api.dps_cache,
  118. "cached_state": redact_dps(device, device._cached_state),
  119. "pending_state": redact_dps(device, device._pending_updates),
  120. "connected": device._running,
  121. "force_dps": device._force_dps,
  122. }
  123. device_registry = dr.async_get(hass)
  124. entity_registry = er.async_get(hass)
  125. hass_device = device_registry.async_get_device(
  126. identifiers={(DOMAIN, device.unique_id)}
  127. )
  128. if hass_device:
  129. data["home_assistant"] = {
  130. "name": hass_device.name,
  131. "name_by_user": hass_device.name_by_user,
  132. "disabled": hass_device.disabled,
  133. "disabled_by": hass_device.disabled_by,
  134. "entities": [],
  135. }
  136. hass_entities = er.async_entries_for_device(
  137. entity_registry,
  138. device_id=hass_device.id,
  139. include_disabled_entities=True,
  140. )
  141. for entity_entry in hass_entities:
  142. state = hass.states.get(entity_entry.entity_id)
  143. state_dict = None
  144. if state:
  145. state_dict = redact_entity(
  146. device,
  147. entity_entry.unique_id,
  148. state.as_dict(),
  149. )
  150. # Redact entity_picture in case it is sensitive
  151. if "entity_picture" in state_dict["attributes"]:
  152. state_dict["attributes"] = {
  153. **state_dict["attributes"],
  154. "entity_picture": REDACTED,
  155. }
  156. # Context is not useful information
  157. state_dict.pop("context", None)
  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