device.py 18 KB

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