device.py 22 KB

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