device.py 23 KB

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