device.py 31 KB

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