device.py 25 KB

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