device.py 29 KB

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