device.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. """
  2. API for Tuya Local devices.
  3. """
  4. import asyncio
  5. import json
  6. import logging
  7. import tinytuya
  8. from threading import Lock
  9. from time import time
  10. from homeassistant.const import (
  11. CONF_HOST,
  12. CONF_NAME,
  13. EVENT_HOMEASSISTANT_STARTED,
  14. EVENT_HOMEASSISTANT_STOP,
  15. )
  16. from homeassistant.core import HomeAssistant
  17. from .const import (
  18. API_PROTOCOL_VERSIONS,
  19. CONF_DEVICE_ID,
  20. CONF_LOCAL_KEY,
  21. CONF_PROTOCOL_VERSION,
  22. DOMAIN,
  23. )
  24. from .helpers.device_config import possible_matches
  25. _LOGGER = logging.getLogger(__name__)
  26. class TuyaLocalDevice(object):
  27. def __init__(
  28. self,
  29. name,
  30. dev_id,
  31. address,
  32. local_key,
  33. protocol_version,
  34. hass: HomeAssistant,
  35. ):
  36. """
  37. Represents a Tuya-based device.
  38. Args:
  39. dev_id (str): The device id.
  40. address (str): The network address.
  41. local_key (str): The encryption key.
  42. protocol_version (str | number): The protocol version.
  43. """
  44. self._name = name
  45. self._children = []
  46. self._running = False
  47. self._shutdown_listener = None
  48. self._startup_listener = None
  49. self._api_protocol_version_index = None
  50. self._api_protocol_working = False
  51. self._api = tinytuya.Device(dev_id, address, local_key)
  52. self._refresh_task = None
  53. self._protocol_configured = protocol_version
  54. self._reset_cached_state()
  55. self._hass = hass
  56. # API calls to update Tuya devices are asynchronous and non-blocking.
  57. # This means you can send a change and immediately request an updated
  58. # state (like HA does), but because it has not yet finished processing
  59. # you will be returned the old state.
  60. # The solution is to keep a temporary list of changed properties that
  61. # we can overlay onto the state while we wait for the board to update
  62. # its switches.
  63. self._FAKE_IT_TIMEOUT = 5
  64. self._CACHE_TIMEOUT = 120
  65. # More attempts are needed in auto mode so we can cycle through all
  66. # the possibilities a couple of times
  67. self._AUTO_CONNECTION_ATTEMPTS = 9
  68. self._SINGLE_PROTO_CONNECTION_ATTEMPTS = 3
  69. self._lock = Lock()
  70. @property
  71. def name(self):
  72. return self._name
  73. @property
  74. def unique_id(self):
  75. """Return the unique id for this device (the dev_id)."""
  76. return self._api.id
  77. @property
  78. def device_info(self):
  79. """Return the device information for this device."""
  80. return {
  81. "identifiers": {(DOMAIN, self.unique_id)},
  82. "name": self.name,
  83. "manufacturer": "Tuya",
  84. }
  85. @property
  86. def has_returned_state(self):
  87. """Return True if the device has returned some state."""
  88. return len(self._get_cached_state()) > 1
  89. def actually_start(self, event=None):
  90. _LOGGER.debug(f"Starting monitor loop for {self.name}")
  91. self._running = True
  92. self._shutdown_listener = self._hass.bus.async_listen_once(
  93. EVENT_HOMEASSISTANT_STOP, self.async_stop
  94. )
  95. self._refresh_task = self._hass.async_create_task(self.receive_loop())
  96. def start(self):
  97. if self._hass.is_stopping:
  98. return
  99. elif self._hass.is_running:
  100. if self._startup_listener:
  101. self._startup_listener()
  102. self._startup_listener = None
  103. self.actually_start()
  104. else:
  105. self._startup_listener = self._hass.bus.async_listen_once(
  106. EVENT_HOMEASSISTANT_STARTED, self.actually_start
  107. )
  108. async def async_stop(self, event=None):
  109. _LOGGER.debug(f"Stopping monitor loop for {self.name}")
  110. self._running = False
  111. if self._shutdown_listener:
  112. self._shutdown_listener()
  113. self._shutdown_listener = None
  114. self._children.clear()
  115. if self._refresh_task:
  116. await self._refresh_task
  117. _LOGGER.debug(f"Monitor loop for {self.name} stopped")
  118. self._refresh_task = None
  119. def register_entity(self, entity):
  120. self._children.append(entity)
  121. if not self._running and not self._startup_listener:
  122. self.start()
  123. async def async_unregister_entity(self, entity):
  124. self._children.remove(entity)
  125. if not self._children:
  126. await self.async_stop()
  127. async def receive_loop(self):
  128. """Coroutine wrapper for async_receive generator."""
  129. try:
  130. async for poll in self.async_receive():
  131. if type(poll) is dict:
  132. _LOGGER.debug(f"{self.name} received {poll}")
  133. self._cached_state = self._cached_state | poll
  134. self._cached_state["updated_at"] = time()
  135. for entity in self._children:
  136. entity.async_schedule_update_ha_state()
  137. else:
  138. _LOGGER.debug(f"{self.name} received non data {poll}")
  139. _LOGGER.warning(f"{self.name} receive loop has terminated")
  140. except Exception as t:
  141. _LOGGER.exception(
  142. f"{self.name} receive loop terminated by exception {t}",
  143. )
  144. async def async_receive(self):
  145. """Receive messages from a persistent connection asynchronously."""
  146. # If we didn't yet get any state from the device, we may need to
  147. # negotiate the protocol before making the connection persistent
  148. persist = self.has_returned_state
  149. self._api.set_socketPersistent(persist)
  150. while self._running:
  151. try:
  152. last_cache = self._cached_state["updated_at"]
  153. now = time()
  154. if persist != self.has_returned_state:
  155. # use persistent connections after initial communication
  156. # has been established. Until then, we need to rotate
  157. # the protocol version, which seems to require a fresh
  158. # connection.
  159. persist = self.has_returned_state
  160. self._api.set_socketPersistent(persist)
  161. last_cache = 0
  162. if now - last_cache > self._CACHE_TIMEOUT:
  163. poll = await self._retry_on_failed_connection(
  164. lambda: self._api.status(),
  165. f"Failed to refresh device state for {self.name}",
  166. )
  167. else:
  168. await self._hass.async_add_executor_job(
  169. self._api.heartbeat,
  170. True,
  171. )
  172. poll = await self._hass.async_add_executor_job(
  173. self._api.receive,
  174. )
  175. if poll:
  176. if "Error" in poll:
  177. _LOGGER.warning(
  178. f"{self.name} error reading: {poll['Error']}",
  179. )
  180. if "Payload" in poll and poll["Payload"]:
  181. _LOGGER.info(
  182. f"{self.name} err payload: {poll['Payload']}",
  183. )
  184. else:
  185. if "dps" in poll:
  186. poll = poll["dps"]
  187. yield poll
  188. await asyncio.sleep(0.1 if self.has_returned_state else 5)
  189. except asyncio.CancelledError:
  190. self._running = False
  191. # Close the persistent connection when exiting the loop
  192. self._api.set_socketPersistent(False)
  193. raise
  194. except Exception as t:
  195. _LOGGER.exception(
  196. f"{self.name} receive loop error {type(t)}:{t}",
  197. )
  198. await asyncio.sleep(5)
  199. # Close the persistent connection when exiting the loop
  200. self._api.set_socketPersistent(False)
  201. async def async_possible_types(self):
  202. cached_state = self._get_cached_state()
  203. if len(cached_state) <= 1:
  204. await self.async_refresh()
  205. cached_state = self._get_cached_state()
  206. for match in possible_matches(cached_state):
  207. yield match
  208. async def async_inferred_type(self):
  209. best_match = None
  210. best_quality = 0
  211. cached_state = {}
  212. async for config in self.async_possible_types():
  213. cached_state = self._get_cached_state()
  214. quality = config.match_quality(cached_state)
  215. _LOGGER.info(
  216. f"{self.name} considering {config.name} with quality {quality}"
  217. )
  218. if quality > best_quality:
  219. best_quality = quality
  220. best_match = config
  221. if best_match is None:
  222. _LOGGER.warning(
  223. f"Detection for {self.name} with dps {cached_state} failed",
  224. )
  225. return None
  226. return best_match.config_type
  227. async def async_refresh(self):
  228. _LOGGER.debug(f"Refreshing device state for {self.name}.")
  229. await self._retry_on_failed_connection(
  230. lambda: self._refresh_cached_state(),
  231. f"Failed to refresh device state for {self.name}.",
  232. )
  233. def get_property(self, dps_id):
  234. cached_state = self._get_cached_state()
  235. if dps_id in cached_state:
  236. return cached_state[dps_id]
  237. else:
  238. return None
  239. async def async_set_property(self, dps_id, value):
  240. await self.async_set_properties({dps_id: value})
  241. def anticipate_property_value(self, dps_id, value):
  242. """
  243. Update a value in the cached state only. This is good for when you
  244. know the device will reflect a new state in the next update, but
  245. don't want to wait for that update for the device to represent
  246. this state.
  247. The anticipated value will be cleared with the next update.
  248. """
  249. self._cached_state[dps_id] = value
  250. def _reset_cached_state(self):
  251. self._cached_state = {"updated_at": 0}
  252. self._pending_updates = {}
  253. self._last_connection = 0
  254. def _refresh_cached_state(self):
  255. new_state = self._api.status()
  256. self._cached_state = self._cached_state | new_state["dps"]
  257. self._cached_state["updated_at"] = time()
  258. _LOGGER.debug(
  259. f"{self.name} refreshed device state: {json.dumps(new_state)}",
  260. )
  261. _LOGGER.debug(
  262. f"new state (incl pending): {json.dumps(self._get_cached_state())}"
  263. )
  264. async def async_set_properties(self, properties):
  265. if len(properties) == 0:
  266. return
  267. self._add_properties_to_pending_updates(properties)
  268. await self._debounce_sending_updates()
  269. def _add_properties_to_pending_updates(self, properties):
  270. now = time()
  271. pending_updates = self._get_pending_updates()
  272. for key, value in properties.items():
  273. pending_updates[key] = {
  274. "value": value,
  275. "updated_at": now,
  276. "sent": False,
  277. }
  278. _LOGGER.debug(
  279. f"{self.name} new pending updates: {json.dumps(pending_updates)}",
  280. )
  281. async def _debounce_sending_updates(self):
  282. now = time()
  283. since = now - self._last_connection
  284. # set this now to avoid a race condition, it will be updated later
  285. # when the data is actally sent
  286. self._last_connection = now
  287. # Only delay a second if there was recently another command.
  288. # Otherwise delay 1ms, to keep things simple by reusing the
  289. # same send mechanism.
  290. waittime = 1 if since < 1.1 else 0.001
  291. await asyncio.sleep(waittime)
  292. await self._send_pending_updates()
  293. async def _send_pending_updates(self):
  294. pending_properties = self._get_unsent_properties()
  295. payload = self._api.generate_payload(
  296. tinytuya.CONTROL,
  297. pending_properties,
  298. )
  299. _LOGGER.debug(
  300. f"{self.name} sending dps update: {json.dumps(pending_properties)}"
  301. )
  302. await self._retry_on_failed_connection(
  303. lambda: self._send_payload(payload),
  304. "Failed to update device state.",
  305. )
  306. def _send_payload(self, payload):
  307. try:
  308. self._lock.acquire()
  309. self._api.send(payload)
  310. self._cached_state["updated_at"] = 0
  311. now = time()
  312. self._last_connection = now
  313. pending_updates = self._get_pending_updates()
  314. for key in list(pending_updates):
  315. pending_updates[key]["updated_at"] = now
  316. pending_updates[key]["sent"] = True
  317. finally:
  318. self._lock.release()
  319. async def _retry_on_failed_connection(self, func, error_message):
  320. if self._api_protocol_version_index is None:
  321. await self._rotate_api_protocol_version()
  322. auto = (self._protocol_configured == "auto") and (
  323. not self._api_protocol_working
  324. )
  325. connections = (
  326. self._AUTO_CONNECTION_ATTEMPTS
  327. if auto
  328. else self._SINGLE_PROTO_CONNECTION_ATTEMPTS
  329. )
  330. for i in range(connections):
  331. try:
  332. retval = await self._hass.async_add_executor_job(func)
  333. if type(retval) is dict and "Error" in retval:
  334. raise AttributeError
  335. self._api_protocol_working = True
  336. return retval
  337. except Exception as e:
  338. _LOGGER.debug(f"Retrying after exception {e}")
  339. if i + 1 == connections:
  340. self._reset_cached_state()
  341. self._api_protocol_working = False
  342. _LOGGER.error(error_message)
  343. if not self._api_protocol_working:
  344. await self._rotate_api_protocol_version()
  345. def _get_cached_state(self):
  346. cached_state = self._cached_state.copy()
  347. return {**cached_state, **self._get_pending_properties()}
  348. def _get_pending_properties(self):
  349. return {
  350. key: property["value"]
  351. for key, property in self._get_pending_updates().items()
  352. }
  353. def _get_unsent_properties(self):
  354. return {
  355. key: info["value"]
  356. for key, info in self._get_pending_updates().items()
  357. if not info["sent"]
  358. }
  359. def _get_pending_updates(self):
  360. now = time()
  361. self._pending_updates = {
  362. key: value
  363. for key, value in self._pending_updates.items()
  364. if now - value["updated_at"] < self._FAKE_IT_TIMEOUT
  365. }
  366. return self._pending_updates
  367. async def _rotate_api_protocol_version(self):
  368. if self._api_protocol_version_index is None:
  369. try:
  370. self._api_protocol_version_index = API_PROTOCOL_VERSIONS.index(
  371. self._protocol_configured
  372. )
  373. except ValueError:
  374. self._api_protocol_version_index = 0
  375. # only rotate if configured as auto
  376. elif self._protocol_configured == "auto":
  377. self._api_protocol_version_index += 1
  378. if self._api_protocol_version_index >= len(API_PROTOCOL_VERSIONS):
  379. self._api_protocol_version_index = 0
  380. new_version = API_PROTOCOL_VERSIONS[self._api_protocol_version_index]
  381. _LOGGER.info(
  382. f"Setting protocol version for {self.name} to {new_version}.",
  383. )
  384. await self._hass.async_add_executor_job(
  385. self._api.set_version,
  386. new_version,
  387. )
  388. @staticmethod
  389. def get_key_for_value(obj, value, fallback=None):
  390. keys = list(obj.keys())
  391. values = list(obj.values())
  392. return keys[values.index(value)] if value in values else fallback
  393. def setup_device(hass: HomeAssistant, config: dict):
  394. """Setup a tuya device based on passed in config."""
  395. _LOGGER.info(f"Creating device: {config[CONF_DEVICE_ID]}")
  396. hass.data[DOMAIN] = hass.data.get(DOMAIN, {})
  397. device = TuyaLocalDevice(
  398. config[CONF_NAME],
  399. config[CONF_DEVICE_ID],
  400. config[CONF_HOST],
  401. config[CONF_LOCAL_KEY],
  402. config[CONF_PROTOCOL_VERSION],
  403. hass,
  404. )
  405. hass.data[DOMAIN][config[CONF_DEVICE_ID]] = {"device": device}
  406. return device
  407. async def async_delete_device(hass: HomeAssistant, config: dict):
  408. _LOGGER.info(f"Deleting device: {config[CONF_DEVICE_ID]}")
  409. await hass.data[DOMAIN][config[CONF_DEVICE_ID]]["device"].async_stop()
  410. del hass.data[DOMAIN][config[CONF_DEVICE_ID]]["device"]