device.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. """
  2. API for Tuya Local devices.
  3. """
  4. import json
  5. import logging
  6. import tinytuya
  7. from threading import Lock, Timer
  8. from time import time
  9. from homeassistant.const import TEMP_CELSIUS
  10. from homeassistant.core import HomeAssistant
  11. from .const import (
  12. API_PROTOCOL_VERSIONS,
  13. DOMAIN,
  14. )
  15. _LOGGER = logging.getLogger(__name__)
  16. class TuyaLocalDevice(object):
  17. def __init__(self, name, dev_id, address, local_key, hass: HomeAssistant):
  18. """
  19. Represents a Tuya-based device.
  20. Args:
  21. dev_id (str): The device id.
  22. address (str): The network address.
  23. local_key (str): The encryption key.
  24. """
  25. self._name = name
  26. self._api_protocol_version_index = None
  27. self._api_protocol_working = False
  28. self._api = tinytuya.Device(dev_id, address, local_key)
  29. self._refresh_task = None
  30. self._rotate_api_protocol_version()
  31. self._reset_cached_state()
  32. self._TEMPERATURE_UNIT = TEMP_CELSIUS
  33. self._hass = hass
  34. # API calls to update Tuya devices are asynchronous and non-blocking.
  35. # This means you can send a change and immediately request an updated
  36. # state (like HA does), but because it has not yet finished processing
  37. # you will be returned the old state.
  38. # The solution is to keep a temporary list of changed properties that
  39. # we can overlay onto the state while we wait for the board to update
  40. # its switches.
  41. self._FAKE_IT_TIL_YOU_MAKE_IT_TIMEOUT = 10
  42. self._CACHE_TIMEOUT = 20
  43. self._CONNECTION_ATTEMPTS = 4
  44. self._lock = Lock()
  45. @property
  46. def name(self):
  47. return self._name
  48. @property
  49. def unique_id(self):
  50. """Return the unique id for this device (the dev_id)."""
  51. return self._api.id
  52. @property
  53. def device_info(self):
  54. """Return the device information for this device."""
  55. return {
  56. "identifiers": {(DOMAIN, self.unique_id)},
  57. "name": self.name,
  58. "manufacturer": "Tuya",
  59. }
  60. @property
  61. def temperature_unit(self):
  62. return self._TEMPERATURE_UNIT
  63. async def async_inferred_type(self):
  64. from .helpers.device_config import possible_matches
  65. cached_state = self._get_cached_state()
  66. if "1" not in cached_state and "3" not in cached_state:
  67. await self.async_refresh()
  68. cached_state = self._get_cached_state()
  69. _LOGGER.debug(f"Inferring device type from cached state: {cached_state}")
  70. best_match = None
  71. best_quality = 0
  72. for config in possible_matches(cached_state):
  73. quality = config.match_quality(cached_state)
  74. _LOGGER.debug(f"Considering {config.name} with quality {quality}")
  75. if quality > best_quality:
  76. best_quality = quality
  77. best_match = config
  78. if best_match is None:
  79. _LOGGER.warning(f"Detection for {self.name} failed")
  80. return None
  81. return best_match.legacy_type
  82. async def async_refresh(self):
  83. last_updated = self._get_cached_state()["updated_at"]
  84. if self._refresh_task is None or time() - last_updated >= self._CACHE_TIMEOUT:
  85. self._cached_state["updated_at"] = time()
  86. self._refresh_task = self._hass.async_add_executor_job(self.refresh)
  87. await self._refresh_task
  88. def refresh(self):
  89. _LOGGER.debug(f"Refreshing device state for {self.name}.")
  90. self._retry_on_failed_connection(
  91. lambda: self._refresh_cached_state(),
  92. f"Failed to refresh device state for {self.name}.",
  93. )
  94. def get_property(self, dps_id):
  95. cached_state = self._get_cached_state()
  96. if dps_id in cached_state:
  97. return cached_state[dps_id]
  98. else:
  99. return None
  100. def set_property(self, dps_id, value):
  101. self._set_properties({dps_id: value})
  102. async def async_set_property(self, dps_id, value):
  103. await self._hass.async_add_executor_job(self.set_property, dps_id, value)
  104. def anticipate_property_value(self, dps_id, value):
  105. """
  106. Update a value in the cached state only. This is good for when you know the device will reflect a new state in
  107. the next update, but don't want to wait for that update for the device to represent this state.
  108. The anticipated value will be cleared with the next update.
  109. """
  110. self._cached_state[dps_id] = value
  111. def _reset_cached_state(self):
  112. self._cached_state = {"updated_at": 0}
  113. self._pending_updates = {}
  114. def _refresh_cached_state(self):
  115. new_state = self._api.status()
  116. self._cached_state = new_state["dps"]
  117. self._cached_state["updated_at"] = time()
  118. _LOGGER.debug(f"refreshed device state: {json.dumps(new_state)}")
  119. _LOGGER.debug(
  120. f"new cache state (including pending properties): {json.dumps(self._get_cached_state())}"
  121. )
  122. def _set_properties(self, properties):
  123. if len(properties) == 0:
  124. return
  125. self._add_properties_to_pending_updates(properties)
  126. self._debounce_sending_updates()
  127. def _add_properties_to_pending_updates(self, properties):
  128. now = time()
  129. pending_updates = self._get_pending_updates()
  130. for key, value in properties.items():
  131. pending_updates[key] = {"value": value, "updated_at": now}
  132. _LOGGER.debug(f"new pending updates: {json.dumps(self._pending_updates)}")
  133. def _debounce_sending_updates(self):
  134. try:
  135. self._debounce.cancel()
  136. except AttributeError:
  137. pass
  138. self._debounce = Timer(1, self._send_pending_updates)
  139. self._debounce.start()
  140. def _send_pending_updates(self):
  141. pending_properties = self._get_pending_properties()
  142. payload = self._api.generate_payload(tinytuya.CONTROL, pending_properties)
  143. _LOGGER.debug(f"sending dps update: {json.dumps(pending_properties)}")
  144. self._retry_on_failed_connection(
  145. lambda: self._send_payload(payload), "Failed to update device state."
  146. )
  147. def _send_payload(self, payload):
  148. try:
  149. self._lock.acquire()
  150. self._api._send_receive(payload)
  151. self._cached_state["updated_at"] = 0
  152. now = time()
  153. pending_updates = self._get_pending_updates()
  154. for key, value in pending_updates.items():
  155. pending_updates[key]["updated_at"] = now
  156. finally:
  157. self._lock.release()
  158. def _retry_on_failed_connection(self, func, error_message):
  159. for i in range(self._CONNECTION_ATTEMPTS):
  160. try:
  161. func()
  162. self._api_protocol_working = True
  163. break
  164. except Exception as e:
  165. _LOGGER.info(f"Retrying after exception {e}")
  166. if i + 1 == self._CONNECTION_ATTEMPTS:
  167. self._reset_cached_state()
  168. self._api_protocol_working = False
  169. _LOGGER.error(error_message)
  170. elif self._api_protocol_working is False:
  171. self._rotate_api_protocol_version()
  172. def _get_cached_state(self):
  173. cached_state = self._cached_state.copy()
  174. return {**cached_state, **self._get_pending_properties()}
  175. def _get_pending_properties(self):
  176. return {key: info["value"] for key, info in self._get_pending_updates().items()}
  177. def _get_pending_updates(self):
  178. now = time()
  179. self._pending_updates = {
  180. key: value
  181. for key, value in self._pending_updates.items()
  182. if now - value["updated_at"] < self._FAKE_IT_TIL_YOU_MAKE_IT_TIMEOUT
  183. }
  184. return self._pending_updates
  185. def _rotate_api_protocol_version(self):
  186. if self._api_protocol_version_index is None:
  187. self._api_protocol_version_index = 0
  188. else:
  189. self._api_protocol_version_index += 1
  190. if self._api_protocol_version_index >= len(API_PROTOCOL_VERSIONS):
  191. self._api_protocol_version_index = 0
  192. new_version = API_PROTOCOL_VERSIONS[self._api_protocol_version_index]
  193. _LOGGER.info(f"Setting protocol version for {self.name} to {new_version}.")
  194. self._api.set_version(new_version)
  195. @staticmethod
  196. def get_key_for_value(obj, value, fallback=None):
  197. keys = list(obj.keys())
  198. values = list(obj.values())
  199. return keys[values.index(value)] if value in values else fallback