device.py 24 KB

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