device.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. """
  2. API for Tuya Local devices.
  3. """
  4. import asyncio
  5. import logging
  6. import tinytuya
  7. from threading import Lock
  8. from time import time
  9. from homeassistant.const import (
  10. CONF_HOST,
  11. CONF_NAME,
  12. EVENT_HOMEASSISTANT_STARTED,
  13. EVENT_HOMEASSISTANT_STOP,
  14. )
  15. from homeassistant.core import HomeAssistant
  16. from .const import (
  17. API_PROTOCOL_VERSIONS,
  18. CONF_DEVICE_ID,
  19. CONF_LOCAL_KEY,
  20. CONF_POLL_ONLY,
  21. CONF_PROTOCOL_VERSION,
  22. DOMAIN,
  23. CONF_DEVICE_CID,
  24. )
  25. from .helpers.config import get_device_id
  26. from .helpers.device_config import possible_matches
  27. from .helpers.log import log_json
  28. _LOGGER = logging.getLogger(__name__)
  29. class TuyaLocalDevice(object):
  30. def __init__(
  31. self,
  32. name,
  33. dev_id,
  34. address,
  35. local_key,
  36. protocol_version,
  37. dev_cid,
  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. dev_cid (str): The sub device id.
  49. hass (HomeAssistant): The Home Assistant instance.
  50. poll_only (bool): True if the device should be polled only
  51. """
  52. self._name = name
  53. self._children = []
  54. self._force_dps = []
  55. self._running = False
  56. self._shutdown_listener = None
  57. self._startup_listener = None
  58. self._api_protocol_version_index = None
  59. self._api_protocol_working = False
  60. self._api_working_protocol_failures = 0
  61. try:
  62. if dev_cid is not None:
  63. self._api = tinytuya.Device(
  64. dev_id,
  65. cid=dev_cid,
  66. parent=tinytuya.Device(dev_id, address, local_key),
  67. )
  68. else:
  69. self._api = tinytuya.Device(dev_id, address, local_key)
  70. self.dev_cid = dev_cid
  71. except Exception as e:
  72. _LOGGER.error(
  73. "%s: %s while initialising device %s",
  74. type(e),
  75. e,
  76. dev_id,
  77. )
  78. raise e
  79. # we handle retries at a higher level so we can rotate protocol version
  80. self._api.set_socketRetryLimit(1)
  81. if self._api.parent:
  82. self._api.parent.set_socketRetryLimit(1)
  83. self._refresh_task = None
  84. self._protocol_configured = protocol_version
  85. self._poll_only = poll_only
  86. self._temporary_poll = False
  87. self._reset_cached_state()
  88. self._hass = hass
  89. # API calls to update Tuya devices are asynchronous and non-blocking.
  90. # This means you can send a change and immediately request an updated
  91. # state (like HA does), but because it has not yet finished processing
  92. # you will be returned the old state.
  93. # The solution is to keep a temporary list of changed properties that
  94. # we can overlay onto the state while we wait for the board to update
  95. # its switches.
  96. self._FAKE_IT_TIMEOUT = 5
  97. self._CACHE_TIMEOUT = 30
  98. # More attempts are needed in auto mode so we can cycle through all
  99. # the possibilities a couple of times
  100. self._AUTO_CONNECTION_ATTEMPTS = len(API_PROTOCOL_VERSIONS) * 2 + 1
  101. self._SINGLE_PROTO_CONNECTION_ATTEMPTS = 3
  102. # The number of failures from a working protocol before retrying other protocols.
  103. self._AUTO_FAILURE_RESET_COUNT = 10
  104. self._lock = Lock()
  105. @property
  106. def name(self):
  107. return self._name
  108. @property
  109. def unique_id(self):
  110. """Return the unique id for this device (the dev_id or dev_cid)."""
  111. return self.dev_cid or self._api.id
  112. @property
  113. def device_info(self):
  114. """Return the device information for this device."""
  115. return {
  116. "identifiers": {(DOMAIN, self.unique_id)},
  117. "name": self.name,
  118. "manufacturer": "Tuya",
  119. }
  120. @property
  121. def has_returned_state(self):
  122. """Return True if the device has returned some state."""
  123. return len(self._get_cached_state()) > 1
  124. def actually_start(self, event=None):
  125. _LOGGER.debug("Starting monitor loop for %s", self.name)
  126. self._running = True
  127. self._shutdown_listener = self._hass.bus.async_listen_once(
  128. EVENT_HOMEASSISTANT_STOP, self.async_stop
  129. )
  130. self._refresh_task = self._hass.async_create_task(self.receive_loop())
  131. def start(self):
  132. if self._hass.is_stopping:
  133. return
  134. elif self._hass.is_running:
  135. if self._startup_listener:
  136. self._startup_listener()
  137. self._startup_listener = None
  138. self.actually_start()
  139. else:
  140. self._startup_listener = self._hass.bus.async_listen_once(
  141. EVENT_HOMEASSISTANT_STARTED, self.actually_start
  142. )
  143. async def async_stop(self, event=None):
  144. _LOGGER.debug("Stopping monitor loop for %s", self.name)
  145. self._running = False
  146. if self._shutdown_listener:
  147. self._shutdown_listener()
  148. self._shutdown_listener = None
  149. self._children.clear()
  150. self._force_dps.clear()
  151. if self._refresh_task:
  152. await self._refresh_task
  153. _LOGGER.debug("Monitor loop for %s stopped", self.name)
  154. self._refresh_task = None
  155. def register_entity(self, entity):
  156. # If this is the first child entity to register, and HA is still
  157. # starting, refresh the device state so it shows as available without
  158. # waiting for startup to complete.
  159. should_poll = len(self._children) == 0 and not self._hass.is_running
  160. self._children.append(entity)
  161. for dp in entity._config.dps():
  162. if dp.force and dp.id not in self._force_dps:
  163. self._force_dps.append(int(dp.id))
  164. if not self._running and not self._startup_listener:
  165. self.start()
  166. if self.has_returned_state:
  167. entity.async_schedule_update_ha_state()
  168. elif should_poll:
  169. entity.async_schedule_update_ha_state(True)
  170. async def async_unregister_entity(self, entity):
  171. self._children.remove(entity)
  172. if not self._children:
  173. await self.async_stop()
  174. async def receive_loop(self):
  175. """Coroutine wrapper for async_receive generator."""
  176. try:
  177. async for poll in self.async_receive():
  178. if type(poll) is dict:
  179. _LOGGER.debug(
  180. "%s received %s",
  181. self.name,
  182. log_json(poll),
  183. )
  184. full_poll = poll.pop("full_poll", False)
  185. self._cached_state = self._cached_state | poll
  186. self._cached_state["updated_at"] = time()
  187. for entity in self._children:
  188. # clear non-persistant dps that were not in a full poll
  189. if full_poll:
  190. for dp in entity._config.dps():
  191. if not dp.persist and dp.id not in poll:
  192. self._cached_state.pop(dp.id, None)
  193. entity.async_write_ha_state()
  194. else:
  195. _LOGGER.debug(
  196. "%s received non data %s",
  197. self.name,
  198. log_json(poll),
  199. )
  200. _LOGGER.warning("%s receive loop has terminated", self.name)
  201. except Exception as t:
  202. _LOGGER.exception(
  203. "%s receive loop terminated by exception %s", self.name, t
  204. )
  205. @property
  206. def should_poll(self):
  207. return self._poll_only or self._temporary_poll or not self.has_returned_state
  208. def pause(self):
  209. self._temporary_poll = True
  210. def resume(self):
  211. self._temporary_poll = False
  212. async def async_receive(self):
  213. """Receive messages from a persistent connection asynchronously."""
  214. # If we didn't yet get any state from the device, we may need to
  215. # negotiate the protocol before making the connection persistent
  216. persist = not self.should_poll
  217. # flag to alternate updatedps and status calls to ensure we get
  218. # all dps updated
  219. dps_updated = False
  220. self._api.set_socketPersistent(persist)
  221. if self._api.parent:
  222. self._api.parent.set_socketPersistent(persist)
  223. while self._running:
  224. try:
  225. last_cache = self._cached_state.get("updated_at", 0)
  226. now = time()
  227. full_poll = False
  228. if persist == self.should_poll:
  229. # use persistent connections after initial communication
  230. # has been established. Until then, we need to rotate
  231. # the protocol version, which seems to require a fresh
  232. # connection.
  233. persist = not self.should_poll
  234. self._api.set_socketPersistent(persist)
  235. if self._api.parent:
  236. self._api.parent.set_socketPersistent(persist)
  237. if now - last_cache > self._CACHE_TIMEOUT:
  238. if (
  239. self._force_dps
  240. and not dps_updated
  241. and self._api_protocol_working
  242. ):
  243. poll = await self._retry_on_failed_connection(
  244. lambda: self._api.updatedps(self._force_dps),
  245. f"Failed to update device dps for {self.name}",
  246. )
  247. dps_updated = True
  248. else:
  249. poll = await self._retry_on_failed_connection(
  250. lambda: self._api.status(),
  251. f"Failed to fetch device status for {self.name}",
  252. )
  253. dps_updated = False
  254. full_poll = True
  255. elif persist:
  256. await self._hass.async_add_executor_job(
  257. self._api.heartbeat,
  258. True,
  259. )
  260. poll = await self._hass.async_add_executor_job(
  261. self._api.receive,
  262. )
  263. else:
  264. asyncio.sleep(5)
  265. poll = None
  266. if poll:
  267. if "Error" in poll:
  268. _LOGGER.warning(
  269. "%s error reading: %s", self.name, poll["Error"]
  270. )
  271. if "Payload" in poll and poll["Payload"]:
  272. _LOGGER.info(
  273. "%s err payload: %s",
  274. self.name,
  275. poll["Payload"],
  276. )
  277. else:
  278. if "dps" in poll:
  279. poll = poll["dps"]
  280. poll["full_poll"] = full_poll
  281. yield poll
  282. await asyncio.sleep(0.1 if self.has_returned_state else 5)
  283. except asyncio.CancelledError:
  284. self._running = False
  285. # Close the persistent connection when exiting the loop
  286. self._api.set_socketPersistent(False)
  287. if self._api.parent:
  288. self._api.parent.set_socketPersistent(False)
  289. raise
  290. except Exception as t:
  291. _LOGGER.exception(
  292. "%s receive loop error %s:%s",
  293. self.name,
  294. type(t),
  295. t,
  296. )
  297. await asyncio.sleep(5)
  298. # Close the persistent connection when exiting the loop
  299. self._api.set_socketPersistent(False)
  300. if self._api.parent:
  301. self._api.parent.set_socketPersistent(False)
  302. async def async_possible_types(self):
  303. cached_state = self._get_cached_state()
  304. if len(cached_state) <= 1:
  305. # in case of device22 devices, we need to poll them with a dp
  306. # that exists on the device to get anything back. Most switch-like
  307. # devices have dp 1. Lights generally start from 20. 101 is where
  308. # vendor specific dps start. Between them, these three should cover
  309. # most devices.
  310. self._api.set_dpsUsed({"1": None, "20": None, "101": None})
  311. await self.async_refresh()
  312. cached_state = self._get_cached_state()
  313. for match in possible_matches(cached_state):
  314. yield match
  315. async def async_inferred_type(self):
  316. best_match = None
  317. best_quality = 0
  318. cached_state = self._get_cached_state()
  319. async for config in self.async_possible_types():
  320. quality = config.match_quality(cached_state)
  321. _LOGGER.info(
  322. "%s considering %s with quality %s",
  323. self.name,
  324. config.name,
  325. quality,
  326. )
  327. if quality > best_quality:
  328. best_quality = quality
  329. best_match = config
  330. if best_match is None:
  331. _LOGGER.warning(
  332. "Detection for %s with dps %s failed",
  333. self.name,
  334. log_json(cached_state),
  335. )
  336. return None
  337. return best_match.config_type
  338. async def async_refresh(self):
  339. _LOGGER.debug("Refreshing device state for %s", self.name)
  340. await self._retry_on_failed_connection(
  341. lambda: self._refresh_cached_state(),
  342. f"Failed to refresh device state for {self.name}.",
  343. )
  344. def get_property(self, dps_id):
  345. cached_state = self._get_cached_state()
  346. return cached_state.get(dps_id)
  347. async def async_set_property(self, dps_id, value):
  348. await self.async_set_properties({dps_id: value})
  349. def anticipate_property_value(self, dps_id, value):
  350. """
  351. Update a value in the cached state only. This is good for when you
  352. know the device will reflect a new state in the next update, but
  353. don't want to wait for that update for the device to represent
  354. this state.
  355. The anticipated value will be cleared with the next update.
  356. """
  357. self._cached_state[dps_id] = value
  358. def _reset_cached_state(self):
  359. self._cached_state = {"updated_at": 0}
  360. self._pending_updates = {}
  361. self._last_connection = 0
  362. def _refresh_cached_state(self):
  363. new_state = self._api.status()
  364. if new_state:
  365. self._cached_state = self._cached_state | new_state.get("dps", {})
  366. self._cached_state["updated_at"] = time()
  367. for entity in self._children:
  368. for dp in entity._config.dps():
  369. # Clear non-persistant dps that were not in the poll
  370. if not dp.persist and dp.id not in new_state.get("dps", {}):
  371. self._cached_state.pop(dp.id, None)
  372. entity.async_write_ha_state()
  373. _LOGGER.debug(
  374. "%s refreshed device state: %s",
  375. self.name,
  376. log_json(new_state),
  377. )
  378. _LOGGER.debug(
  379. "new state (incl pending): %s",
  380. log_json(self._get_cached_state()),
  381. )
  382. async def async_set_properties(self, properties):
  383. if len(properties) == 0:
  384. return
  385. self._add_properties_to_pending_updates(properties)
  386. await self._debounce_sending_updates()
  387. def _add_properties_to_pending_updates(self, properties):
  388. now = time()
  389. pending_updates = self._get_pending_updates()
  390. for key, value in properties.items():
  391. pending_updates[key] = {
  392. "value": value,
  393. "updated_at": now,
  394. "sent": False,
  395. }
  396. _LOGGER.debug(
  397. "%s new pending updates: %s",
  398. self.name,
  399. log_json(pending_updates),
  400. )
  401. async def _debounce_sending_updates(self):
  402. now = time()
  403. since = now - self._last_connection
  404. # set this now to avoid a race condition, it will be updated later
  405. # when the data is actally sent
  406. self._last_connection = now
  407. # Only delay a second if there was recently another command.
  408. # Otherwise delay 1ms, to keep things simple by reusing the
  409. # same send mechanism.
  410. waittime = 1 if since < 1.1 else 0.001
  411. await asyncio.sleep(waittime)
  412. await self._send_pending_updates()
  413. async def _send_pending_updates(self):
  414. pending_properties = self._get_unsent_properties()
  415. _LOGGER.debug(
  416. "%s sending dps update: %s",
  417. self.name,
  418. log_json(pending_properties),
  419. )
  420. await self._retry_on_failed_connection(
  421. lambda: self._set_values(pending_properties),
  422. "Failed to update device state.",
  423. )
  424. def _set_values(self, properties):
  425. try:
  426. self._lock.acquire()
  427. self._api.set_multiple_values(properties, nowait=True)
  428. self._cached_state["updated_at"] = 0
  429. now = time()
  430. self._last_connection = now
  431. pending_updates = self._get_pending_updates()
  432. for key in properties.keys():
  433. pending_updates[key]["updated_at"] = now
  434. pending_updates[key]["sent"] = True
  435. finally:
  436. self._lock.release()
  437. async def _retry_on_failed_connection(self, func, error_message):
  438. if self._api_protocol_version_index is None:
  439. await self._rotate_api_protocol_version()
  440. auto = (self._protocol_configured == "auto") and (
  441. not self._api_protocol_working
  442. )
  443. connections = (
  444. self._AUTO_CONNECTION_ATTEMPTS
  445. if auto
  446. else self._SINGLE_PROTO_CONNECTION_ATTEMPTS
  447. )
  448. for i in range(connections):
  449. try:
  450. if not self._hass.is_stopping:
  451. retval = await self._hass.async_add_executor_job(func)
  452. if type(retval) is dict and "Error" in retval:
  453. raise AttributeError(retval["Error"])
  454. self._api_protocol_working = True
  455. self._api_working_protocol_failures = 0
  456. return retval
  457. except Exception as e:
  458. _LOGGER.debug(
  459. "Retrying after exception %s %s (%d/%d)",
  460. type(e),
  461. e,
  462. i,
  463. connections,
  464. )
  465. if i + 1 == connections:
  466. self._reset_cached_state()
  467. self._api_working_protocol_failures += 1
  468. if (
  469. self._api_working_protocol_failures
  470. > self._AUTO_FAILURE_RESET_COUNT
  471. ):
  472. self._api_protocol_working = False
  473. for entity in self._children:
  474. entity.async_schedule_update_ha_state()
  475. _LOGGER.error(error_message)
  476. if not self._api_protocol_working:
  477. await self._rotate_api_protocol_version()
  478. def _get_cached_state(self):
  479. cached_state = self._cached_state.copy()
  480. return {**cached_state, **self._get_pending_properties()}
  481. def _get_pending_properties(self):
  482. return {
  483. key: property["value"]
  484. for key, property in self._get_pending_updates().items()
  485. }
  486. def _get_unsent_properties(self):
  487. return {
  488. key: info["value"]
  489. for key, info in self._get_pending_updates().items()
  490. if not info["sent"]
  491. }
  492. def _get_pending_updates(self):
  493. now = time()
  494. self._pending_updates = {
  495. key: value
  496. for key, value in self._pending_updates.items()
  497. if now - value.get("updated_at", 0) < self._FAKE_IT_TIMEOUT
  498. }
  499. return self._pending_updates
  500. async def _rotate_api_protocol_version(self):
  501. if self._api_protocol_version_index is None:
  502. try:
  503. self._api_protocol_version_index = API_PROTOCOL_VERSIONS.index(
  504. self._protocol_configured
  505. )
  506. except ValueError:
  507. self._api_protocol_version_index = 0
  508. # only rotate if configured as auto
  509. elif self._protocol_configured == "auto":
  510. self._api_protocol_version_index += 1
  511. if self._api_protocol_version_index >= len(API_PROTOCOL_VERSIONS):
  512. self._api_protocol_version_index = 0
  513. new_version = API_PROTOCOL_VERSIONS[self._api_protocol_version_index]
  514. _LOGGER.info(
  515. "Setting protocol version for %s to %0.1f",
  516. self.name,
  517. new_version,
  518. )
  519. await self._hass.async_add_executor_job(
  520. self._api.set_version,
  521. new_version,
  522. )
  523. if self._api.parent:
  524. await self._hass.async_add_executor_job(
  525. self._api.parent.set_version,
  526. new_version,
  527. )
  528. @staticmethod
  529. def get_key_for_value(obj, value, fallback=None):
  530. keys = list(obj.keys())
  531. values = list(obj.values())
  532. return keys[values.index(value)] if value in values else fallback
  533. def setup_device(hass: HomeAssistant, config: dict):
  534. """Setup a tuya device based on passed in config."""
  535. _LOGGER.info("Creating device: %s", get_device_id(config))
  536. hass.data[DOMAIN] = hass.data.get(DOMAIN, {})
  537. device = TuyaLocalDevice(
  538. config[CONF_NAME],
  539. config[CONF_DEVICE_ID],
  540. config[CONF_HOST],
  541. config[CONF_LOCAL_KEY],
  542. config[CONF_PROTOCOL_VERSION],
  543. config.get(CONF_DEVICE_CID),
  544. hass,
  545. config[CONF_POLL_ONLY],
  546. )
  547. hass.data[DOMAIN][get_device_id(config)] = {"device": device}
  548. return device
  549. async def async_delete_device(hass: HomeAssistant, config: dict):
  550. device_id = get_device_id(config)
  551. _LOGGER.info("Deleting device: %s", device_id)
  552. await hass.data[DOMAIN][device_id]["device"].async_stop()
  553. del hass.data[DOMAIN][device_id]["device"]