device.py 23 KB

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