device.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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 CONF_HOST, CONF_NAME, UnitOfTemperature
  10. from homeassistant.core import HomeAssistant
  11. from .const import (
  12. API_PROTOCOL_VERSIONS,
  13. CONF_DEVICE_ID,
  14. CONF_LOCAL_KEY,
  15. DOMAIN,
  16. )
  17. from .helpers.device_config import possible_matches
  18. _LOGGER = logging.getLogger(__name__)
  19. class TuyaLocalDevice(object):
  20. def __init__(self, name, dev_id, address, local_key, hass: HomeAssistant):
  21. """
  22. Represents a Tuya-based device.
  23. Args:
  24. dev_id (str): The device id.
  25. address (str): The network address.
  26. local_key (str): The encryption key.
  27. """
  28. self._name = name
  29. self._api_protocol_version_index = None
  30. self._api_protocol_working = False
  31. self._api = tinytuya.Device(dev_id, address, local_key)
  32. self._refresh_task = None
  33. self._rotate_api_protocol_version()
  34. self._reset_cached_state()
  35. self._TEMPERATURE_UNIT = UnitOfTemperature.CELSIUS
  36. self._hass = hass
  37. # API calls to update Tuya devices are asynchronous and non-blocking.
  38. # This means you can send a change and immediately request an updated
  39. # state (like HA does), but because it has not yet finished processing
  40. # you will be returned the old state.
  41. # The solution is to keep a temporary list of changed properties that
  42. # we can overlay onto the state while we wait for the board to update
  43. # its switches.
  44. self._FAKE_IT_TIL_YOU_MAKE_IT_TIMEOUT = 10
  45. self._CACHE_TIMEOUT = 20
  46. self._CONNECTION_ATTEMPTS = 9
  47. self._lock = Lock()
  48. @property
  49. def name(self):
  50. return self._name
  51. @property
  52. def unique_id(self):
  53. """Return the unique id for this device (the dev_id)."""
  54. return self._api.id
  55. @property
  56. def device_info(self):
  57. """Return the device information for this device."""
  58. return {
  59. "identifiers": {(DOMAIN, self.unique_id)},
  60. "name": self.name,
  61. "manufacturer": "Tuya",
  62. }
  63. @property
  64. def has_returned_state(self):
  65. """Return True if the device has returned some state."""
  66. return len(self._get_cached_state()) > 1
  67. @property
  68. def temperature_unit(self):
  69. return self._TEMPERATURE_UNIT
  70. async def async_possible_types(self):
  71. cached_state = self._get_cached_state()
  72. if len(cached_state) <= 1:
  73. await self.async_refresh()
  74. cached_state = self._get_cached_state()
  75. for match in possible_matches(cached_state):
  76. yield match
  77. async def async_inferred_type(self):
  78. best_match = None
  79. best_quality = 0
  80. cached_state = {}
  81. async for config in self.async_possible_types():
  82. cached_state = self._get_cached_state()
  83. quality = config.match_quality(cached_state)
  84. _LOGGER.info(
  85. f"{self.name} considering {config.name} with quality {quality}"
  86. )
  87. if quality > best_quality:
  88. best_quality = quality
  89. best_match = config
  90. if best_match is None:
  91. _LOGGER.warning(f"Detection for {self.name} with dps {cached_state} failed")
  92. return None
  93. return best_match.config_type
  94. async def async_refresh(self):
  95. cache = self._get_cached_state()
  96. if "updated_at" in cache:
  97. last_updated = self._get_cached_state()["updated_at"]
  98. else:
  99. last_updated = 0
  100. if self._refresh_task is None or time() - last_updated >= self._CACHE_TIMEOUT:
  101. self._cached_state["updated_at"] = time()
  102. self._refresh_task = self._hass.async_add_executor_job(self.refresh)
  103. await self._refresh_task
  104. def refresh(self):
  105. _LOGGER.debug(f"Refreshing device state for {self.name}.")
  106. self._retry_on_failed_connection(
  107. lambda: self._refresh_cached_state(),
  108. f"Failed to refresh device state for {self.name}.",
  109. )
  110. def get_property(self, dps_id):
  111. cached_state = self._get_cached_state()
  112. if dps_id in cached_state:
  113. return cached_state[dps_id]
  114. else:
  115. return None
  116. def set_property(self, dps_id, value):
  117. self._set_properties({dps_id: value})
  118. async def async_set_property(self, dps_id, value):
  119. await self._hass.async_add_executor_job(self.set_property, dps_id, value)
  120. async def async_set_properties(self, dps_map):
  121. await self._hass.async_add_executor_job(self._set_properties, dps_map)
  122. def anticipate_property_value(self, dps_id, value):
  123. """
  124. Update a value in the cached state only. This is good for when you know the device will reflect a new state in
  125. the next update, but don't want to wait for that update for the device to represent this state.
  126. The anticipated value will be cleared with the next update.
  127. """
  128. self._cached_state[dps_id] = value
  129. def _reset_cached_state(self):
  130. self._cached_state = {"updated_at": 0}
  131. self._pending_updates = {}
  132. self._last_connection = 0
  133. def _refresh_cached_state(self):
  134. new_state = self._api.status()
  135. self._cached_state = self._cached_state | new_state["dps"]
  136. self._cached_state["updated_at"] = time()
  137. _LOGGER.debug(f"{self.name} refreshed device state: {json.dumps(new_state)}")
  138. _LOGGER.debug(
  139. f"new cache state (including pending properties): {json.dumps(self._get_cached_state())}"
  140. )
  141. def _set_properties(self, properties):
  142. if len(properties) == 0:
  143. return
  144. self._add_properties_to_pending_updates(properties)
  145. self._debounce_sending_updates()
  146. def _add_properties_to_pending_updates(self, properties):
  147. now = time()
  148. pending_updates = self._get_pending_updates()
  149. for key, value in properties.items():
  150. pending_updates[key] = {"value": value, "updated_at": now}
  151. _LOGGER.debug(
  152. f"{self.name} new pending updates: {json.dumps(self._pending_updates)}"
  153. )
  154. def _debounce_sending_updates(self):
  155. now = time()
  156. since = now - self._last_connection
  157. # set this now to avoid a race condition, it will be updated later
  158. # when the data is actally sent
  159. self._last_connection = now
  160. # Only delay a second if there was recently another command.
  161. # Otherwise delay 1ms, to keep things simple by reusing the
  162. # same send mechanism.
  163. waittime = 1 if since < 1.0 else 0.001
  164. try:
  165. self._debounce.cancel()
  166. except AttributeError:
  167. pass
  168. self._debounce = Timer(waittime, self._send_pending_updates)
  169. self._debounce.start()
  170. def _send_pending_updates(self):
  171. pending_properties = self._get_pending_properties()
  172. payload = self._api.generate_payload(tinytuya.CONTROL, pending_properties)
  173. _LOGGER.debug(
  174. f"{self.name} sending dps update: {json.dumps(pending_properties)}"
  175. )
  176. self._retry_on_failed_connection(
  177. lambda: self._send_payload(payload), "Failed to update device state."
  178. )
  179. def _send_payload(self, payload):
  180. try:
  181. self._lock.acquire()
  182. self._api._send_receive(payload)
  183. self._cached_state["updated_at"] = 0
  184. now = time()
  185. self._last_connection = now
  186. pending_updates = self._get_pending_updates()
  187. for key, value in pending_updates.items():
  188. pending_updates[key]["updated_at"] = now
  189. finally:
  190. self._lock.release()
  191. def _retry_on_failed_connection(self, func, error_message):
  192. for i in range(self._CONNECTION_ATTEMPTS):
  193. try:
  194. func()
  195. self._api_protocol_working = True
  196. break
  197. except Exception as e:
  198. _LOGGER.debug(f"Retrying after exception {e}")
  199. if i + 1 == self._CONNECTION_ATTEMPTS:
  200. self._reset_cached_state()
  201. self._api_protocol_working = False
  202. _LOGGER.error(error_message)
  203. if not self._api_protocol_working:
  204. self._rotate_api_protocol_version()
  205. def _get_cached_state(self):
  206. cached_state = self._cached_state.copy()
  207. return {**cached_state, **self._get_pending_properties()}
  208. def _get_pending_properties(self):
  209. return {key: info["value"] for key, info in self._get_pending_updates().items()}
  210. def _get_pending_updates(self):
  211. now = time()
  212. self._pending_updates = {
  213. key: value
  214. for key, value in self._pending_updates.items()
  215. if now - value["updated_at"] < self._FAKE_IT_TIL_YOU_MAKE_IT_TIMEOUT
  216. }
  217. return self._pending_updates
  218. def _rotate_api_protocol_version(self):
  219. if self._api_protocol_version_index is None:
  220. self._api_protocol_version_index = 0
  221. else:
  222. self._api_protocol_version_index += 1
  223. if self._api_protocol_version_index >= len(API_PROTOCOL_VERSIONS):
  224. self._api_protocol_version_index = 0
  225. new_version = API_PROTOCOL_VERSIONS[self._api_protocol_version_index]
  226. _LOGGER.info(f"Setting protocol version for {self.name} to {new_version}.")
  227. self._api.set_version(new_version)
  228. @staticmethod
  229. def get_key_for_value(obj, value, fallback=None):
  230. keys = list(obj.keys())
  231. values = list(obj.values())
  232. return keys[values.index(value)] if value in values else fallback
  233. def setup_device(hass: HomeAssistant, config: dict):
  234. """Setup a tuya device based on passed in config."""
  235. _LOGGER.info(f"Creating device: {config[CONF_DEVICE_ID]}")
  236. hass.data[DOMAIN] = hass.data.get(DOMAIN, {})
  237. device = TuyaLocalDevice(
  238. config[CONF_NAME],
  239. config[CONF_DEVICE_ID],
  240. config[CONF_HOST],
  241. config[CONF_LOCAL_KEY],
  242. hass,
  243. )
  244. hass.data[DOMAIN][config[CONF_DEVICE_ID]] = {"device": device}
  245. return device
  246. def delete_device(hass: HomeAssistant, config: dict):
  247. _LOGGER.info(f"Deleting device: {config[CONF_DEVICE_ID]}")
  248. del hass.data[DOMAIN][config[CONF_DEVICE_ID]]["device"]