device.py 31 KB

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