device.py 33 KB

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