4
0

device.py 11 KB

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