device.py 11 KB

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