device.py 24 KB

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