device.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  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. @property
  226. def should_poll(self):
  227. return self._poll_only or self._temporary_poll or not self.has_returned_state
  228. def pause(self):
  229. self._temporary_poll = True
  230. self._api.setSocketPersistent(False)
  231. if self._api.parent:
  232. self._api.parent.setSocketPersistent(False)
  233. def resume(self):
  234. self._temporary_poll = False
  235. async def async_receive(self):
  236. """Receive messages from a persistent connection asynchronously."""
  237. # If we didn't yet get any state from the device, we may need to
  238. # negotiate the protocol before making the connection persistent
  239. persist = not self.should_poll
  240. # flag to alternate updatedps and status calls to ensure we get
  241. # all dps updated
  242. dps_updated = False
  243. self._api.set_socketPersistent(persist)
  244. if self._api.parent:
  245. self._api.parent.set_socketPersistent(persist)
  246. while self._running:
  247. try:
  248. last_cache = self._cached_state.get("updated_at", 0)
  249. now = time()
  250. full_poll = False
  251. if persist == self.should_poll:
  252. # use persistent connections after initial communication
  253. # has been established. Until then, we need to rotate
  254. # the protocol version, which seems to require a fresh
  255. # connection.
  256. persist = not self.should_poll
  257. _LOGGER.debug(
  258. "%s persistant connection set to %s", self.name, persist
  259. )
  260. self._api.set_socketPersistent(persist)
  261. if self._api.parent:
  262. self._api.parent.set_socketPersistent(persist)
  263. if now - last_cache > self._CACHE_TIMEOUT:
  264. if (
  265. self._force_dps
  266. and not dps_updated
  267. and self._api_protocol_working
  268. ):
  269. poll = await self._retry_on_failed_connection(
  270. lambda: self._api.updatedps(self._force_dps),
  271. f"Failed to update device dps for {self.name}",
  272. )
  273. dps_updated = True
  274. else:
  275. poll = await self._retry_on_failed_connection(
  276. lambda: self._api.status(),
  277. f"Failed to fetch device status for {self.name}",
  278. )
  279. dps_updated = False
  280. full_poll = True
  281. elif persist:
  282. await self._hass.async_add_executor_job(
  283. self._api.heartbeat,
  284. True,
  285. )
  286. poll = await self._hass.async_add_executor_job(
  287. self._api.receive,
  288. )
  289. else:
  290. await asyncio.sleep(5)
  291. poll = None
  292. if poll:
  293. if "Error" in poll:
  294. _LOGGER.warning(
  295. "%s error reading: %s", self.name, poll["Error"]
  296. )
  297. if "Payload" in poll and poll["Payload"]:
  298. _LOGGER.info(
  299. "%s err payload: %s",
  300. self.name,
  301. poll["Payload"],
  302. )
  303. else:
  304. if "dps" in poll:
  305. poll = poll["dps"]
  306. poll["full_poll"] = full_poll
  307. yield poll
  308. await asyncio.sleep(0.1 if self.has_returned_state else 5)
  309. except CancelledError:
  310. self._running = False
  311. # Close the persistent connection when exiting the loop
  312. self._api.set_socketPersistent(False)
  313. if self._api.parent:
  314. self._api.parent.set_socketPersistent(False)
  315. raise
  316. except Exception as t:
  317. _LOGGER.exception(
  318. "%s receive loop error %s:%s",
  319. self.name,
  320. type(t),
  321. t,
  322. )
  323. await asyncio.sleep(5)
  324. # Close the persistent connection when exiting the loop
  325. self._api.set_socketPersistent(False)
  326. if self._api.parent:
  327. self._api.parent.set_socketPersistent(False)
  328. async def async_possible_types(self):
  329. cached_state = self._get_cached_state()
  330. if len(cached_state) <= 1:
  331. # in case of device22 devices, we need to poll them with a dp
  332. # that exists on the device to get anything back. Most switch-like
  333. # devices have dp 1. Lights generally start from 20. 101 is where
  334. # vendor specific dps start. Between them, these three should cover
  335. # most devices. 148 covers a doorbell device that didn't have these
  336. self._api.set_dpsUsed({"1": None, "20": None, "101": None, "148": None})
  337. await self.async_refresh()
  338. cached_state = self._get_cached_state()
  339. possible = await self._hass.async_add_executor_job(
  340. possible_matches,
  341. cached_state,
  342. )
  343. for match in possible:
  344. await asyncio.sleep(0)
  345. yield match
  346. async def async_inferred_type(self):
  347. best_match = None
  348. best_quality = 0
  349. cached_state = self._get_cached_state()
  350. async for config in self.async_possible_types():
  351. quality = config.match_quality(cached_state)
  352. _LOGGER.info(
  353. "%s considering %s with quality %s",
  354. self.name,
  355. config.name,
  356. quality,
  357. )
  358. if quality > best_quality:
  359. best_quality = quality
  360. best_match = config
  361. if best_match:
  362. return best_match.config_type
  363. _LOGGER.warning(
  364. "Detection for %s with dps %s failed",
  365. self.name,
  366. log_json(cached_state),
  367. )
  368. async def async_refresh(self):
  369. _LOGGER.debug("Refreshing device state for %s", self.name)
  370. if self.should_poll:
  371. await self._retry_on_failed_connection(
  372. lambda: self._refresh_cached_state(),
  373. f"Failed to refresh device state for {self.name}.",
  374. )
  375. def get_property(self, dps_id):
  376. cached_state = self._get_cached_state()
  377. return cached_state.get(dps_id)
  378. async def async_set_property(self, dps_id, value):
  379. await self.async_set_properties({dps_id: value})
  380. def anticipate_property_value(self, dps_id, value):
  381. """
  382. Update a value in the cached state only. This is good for when you
  383. know the device will reflect a new state in the next update, but
  384. don't want to wait for that update for the device to represent
  385. this state.
  386. The anticipated value will be cleared with the next update.
  387. """
  388. self._cached_state[dps_id] = value
  389. def _reset_cached_state(self):
  390. self._cached_state = {"updated_at": 0}
  391. self._pending_updates = {}
  392. self._last_connection = 0
  393. def _refresh_cached_state(self):
  394. new_state = self._api.status()
  395. if new_state:
  396. self._cached_state = self._cached_state | new_state.get("dps", {})
  397. self._cached_state["updated_at"] = time()
  398. for entity in self._children:
  399. for dp in entity._config.dps():
  400. # Clear non-persistant dps that were not in the poll
  401. if not dp.persist and dp.id not in new_state.get("dps", {}):
  402. self._cached_state.pop(dp.id, None)
  403. entity.schedule_update_ha_state()
  404. _LOGGER.debug(
  405. "%s refreshed device state: %s",
  406. self.name,
  407. log_json(new_state),
  408. )
  409. if "Err" in new_state:
  410. _LOGGER.warning(
  411. "%s protocol error %s: %s",
  412. self.name,
  413. new_state.get("Err"),
  414. new_state.get("Error", "message not provided"),
  415. )
  416. _LOGGER.debug(
  417. "new state (incl pending): %s",
  418. log_json(self._get_cached_state()),
  419. )
  420. async def async_set_properties(self, properties):
  421. if len(properties) == 0:
  422. return
  423. self._add_properties_to_pending_updates(properties)
  424. await self._debounce_sending_updates()
  425. def _add_properties_to_pending_updates(self, properties):
  426. now = time()
  427. pending_updates = self._get_pending_updates()
  428. for key, value in properties.items():
  429. pending_updates[key] = {
  430. "value": value,
  431. "updated_at": now,
  432. "sent": False,
  433. }
  434. _LOGGER.debug(
  435. "%s new pending updates: %s",
  436. self.name,
  437. log_json(pending_updates),
  438. )
  439. def _remove_properties_from_pending_updates(self, data):
  440. self._pending_updates = {
  441. key: value
  442. for key, value in self._pending_updates.items()
  443. if key not in data or not value["sent"] or data[key] != value["value"]
  444. }
  445. async def _debounce_sending_updates(self):
  446. now = time()
  447. since = now - self._last_connection
  448. # set this now to avoid a race condition, it will be updated later
  449. # when the data is actally sent
  450. self._last_connection = now
  451. # Only delay a second if there was recently another command.
  452. # Otherwise delay 1ms, to keep things simple by reusing the
  453. # same send mechanism.
  454. waittime = 1 if since < 1.1 and self.should_poll else 0.001
  455. await asyncio.sleep(waittime)
  456. await self._send_pending_updates()
  457. async def _send_pending_updates(self):
  458. pending_properties = self._get_unsent_properties()
  459. _LOGGER.debug(
  460. "%s sending dps update: %s",
  461. self.name,
  462. log_json(pending_properties),
  463. )
  464. await self._retry_on_failed_connection(
  465. lambda: self._set_values(pending_properties),
  466. "Failed to update device state.",
  467. )
  468. def _set_values(self, properties):
  469. try:
  470. self._lock.acquire()
  471. self._api.set_multiple_values(properties, nowait=True)
  472. self._cached_state["updated_at"] = 0
  473. now = time()
  474. self._last_connection = now
  475. pending_updates = self._get_pending_updates()
  476. for key in properties.keys():
  477. pending_updates[key]["updated_at"] = now
  478. pending_updates[key]["sent"] = True
  479. finally:
  480. self._lock.release()
  481. async def _retry_on_failed_connection(self, func, error_message):
  482. if self._api_protocol_version_index is None:
  483. await self._rotate_api_protocol_version()
  484. auto = (self._protocol_configured == "auto") and (
  485. not self._api_protocol_working
  486. )
  487. connections = (
  488. self._AUTO_CONNECTION_ATTEMPTS
  489. if auto
  490. else self._SINGLE_PROTO_CONNECTION_ATTEMPTS
  491. )
  492. for i in range(connections):
  493. try:
  494. if not self._hass.is_stopping:
  495. retval = await self._hass.async_add_executor_job(func)
  496. if isinstance(retval, dict) and "Error" in retval:
  497. raise AttributeError(retval["Error"])
  498. self._api_protocol_working = True
  499. self._api_working_protocol_failures = 0
  500. return retval
  501. except Exception as e:
  502. _LOGGER.debug(
  503. "Retrying after exception %s %s (%d/%d)",
  504. type(e),
  505. e,
  506. i,
  507. connections,
  508. )
  509. if i + 1 == connections:
  510. self._reset_cached_state()
  511. self._api_working_protocol_failures += 1
  512. if (
  513. self._api_working_protocol_failures
  514. > self._AUTO_FAILURE_RESET_COUNT
  515. ):
  516. self._api_protocol_working = False
  517. for entity in self._children:
  518. entity.async_schedule_update_ha_state()
  519. _LOGGER.error(error_message)
  520. if not self._api_protocol_working:
  521. await self._rotate_api_protocol_version()
  522. def _get_cached_state(self):
  523. cached_state = self._cached_state.copy()
  524. return {**cached_state, **self._get_pending_properties()}
  525. def _get_pending_properties(self):
  526. return {
  527. key: property["value"]
  528. for key, property in self._get_pending_updates().items()
  529. }
  530. def _get_unsent_properties(self):
  531. return {
  532. key: info["value"]
  533. for key, info in self._get_pending_updates().items()
  534. if not info["sent"]
  535. }
  536. def _get_pending_updates(self):
  537. now = time()
  538. # sort pending updates according to their API identifier
  539. pending_updates_sorted = sorted(
  540. self._pending_updates.items(), key=lambda x: int(x[0])
  541. )
  542. self._pending_updates = {
  543. key: value
  544. for key, value in pending_updates_sorted
  545. if not value["sent"]
  546. or now - value.get("updated_at", 0) < self._FAKE_IT_TIMEOUT
  547. }
  548. return self._pending_updates
  549. async def _rotate_api_protocol_version(self):
  550. if self._api_protocol_version_index is None:
  551. try:
  552. self._api_protocol_version_index = API_PROTOCOL_VERSIONS.index(
  553. self._protocol_configured
  554. )
  555. except ValueError:
  556. self._api_protocol_version_index = 0
  557. # only rotate if configured as auto
  558. elif self._protocol_configured == "auto":
  559. self._api_protocol_version_index += 1
  560. if self._api_protocol_version_index >= len(API_PROTOCOL_VERSIONS):
  561. self._api_protocol_version_index = 0
  562. new_version = API_PROTOCOL_VERSIONS[self._api_protocol_version_index]
  563. _LOGGER.info(
  564. "Setting protocol version for %s to %0.1f",
  565. self.name,
  566. new_version,
  567. )
  568. await self._hass.async_add_executor_job(
  569. self._api.set_version,
  570. new_version,
  571. )
  572. if self._api.parent:
  573. await self._hass.async_add_executor_job(
  574. self._api.parent.set_version,
  575. new_version,
  576. )
  577. @staticmethod
  578. def get_key_for_value(obj, value, fallback=None):
  579. keys = list(obj.keys())
  580. values = list(obj.values())
  581. return keys[values.index(value)] if value in values else fallback
  582. def setup_device(hass: HomeAssistant, config: dict):
  583. """Setup a tuya device based on passed in config."""
  584. _LOGGER.info("Creating device: %s", get_device_id(config))
  585. hass.data[DOMAIN] = hass.data.get(DOMAIN, {})
  586. device = TuyaLocalDevice(
  587. config[CONF_NAME],
  588. config[CONF_DEVICE_ID],
  589. config[CONF_HOST],
  590. config[CONF_LOCAL_KEY],
  591. config[CONF_PROTOCOL_VERSION],
  592. config.get(CONF_DEVICE_CID),
  593. hass,
  594. config[CONF_POLL_ONLY],
  595. )
  596. hass.data[DOMAIN][get_device_id(config)] = {
  597. "device": device,
  598. "tuyadevice": device._api,
  599. }
  600. return device
  601. async def async_delete_device(hass: HomeAssistant, config: dict):
  602. device_id = get_device_id(config)
  603. _LOGGER.info("Deleting device: %s", device_id)
  604. await hass.data[DOMAIN][device_id]["device"].async_stop()
  605. del hass.data[DOMAIN][device_id]["device"]
  606. del hass.data[DOMAIN][device_id]["tuyadevice"]