device.py 23 KB

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