device.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  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 = 10
  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. self._api.set_socketPersistent(False)
  285. if self._api.parent:
  286. self._api.parent.set_socketPersistent(False)
  287. def resume(self):
  288. self._temporary_poll = False
  289. async def async_receive(self):
  290. """Receive messages from a persistent connection asynchronously."""
  291. # If we didn't yet get any state from the device, we may need to
  292. # negotiate the protocol before making the connection persistent
  293. persist = not self.should_poll
  294. # flag to alternate updatedps and status calls to ensure we get
  295. # all dps updated
  296. dps_updated = False
  297. self._api.set_socketPersistent(persist)
  298. if self._api.parent:
  299. self._api.parent.set_socketPersistent(persist)
  300. last_heartbeat = self._cached_state.get("updated_at", 0)
  301. while self._running:
  302. error_count = self._api_working_protocol_failures
  303. force_backoff = False
  304. try:
  305. await self._api_lock.acquire()
  306. last_cache = self._cached_state.get("updated_at", 0)
  307. now = time()
  308. full_poll = False
  309. if persist == self.should_poll:
  310. # use persistent connections after initial communication
  311. # has been established. Until then, we need to rotate
  312. # the protocol version, which seems to require a fresh
  313. # connection.
  314. persist = not self.should_poll
  315. _LOGGER.debug(
  316. "%s persistant connection set to %s", self.name, persist
  317. )
  318. self._api.set_socketPersistent(persist)
  319. if self._api.parent:
  320. self._api.parent.set_socketPersistent(persist)
  321. self._last_full_poll = 0 # ensure we start with a full poll
  322. needs_full_poll = now - self._last_full_poll > self._CACHE_TIMEOUT
  323. if now - last_cache > self._CACHE_TIMEOUT or (
  324. persist and needs_full_poll
  325. ):
  326. if (
  327. self._force_dps
  328. and not dps_updated
  329. and self._api_protocol_working
  330. ):
  331. poll = await self._retry_on_failed_connection(
  332. lambda: self._api.updatedps(self._force_dps),
  333. f"Failed to update device dps for {self.name}",
  334. )
  335. dps_updated = True
  336. else:
  337. poll = await self._retry_on_failed_connection(
  338. lambda: self._api.status(),
  339. f"Failed to fetch device status for {self.name}",
  340. )
  341. dps_updated = False
  342. full_poll = True
  343. self._last_full_poll = now
  344. last_heartbeat = now # reset heartbeat timer on full poll
  345. elif persist:
  346. if now - last_heartbeat > self._HEARTBEAT_INTERVAL:
  347. await self._hass.async_add_executor_job(
  348. self._api.heartbeat,
  349. True,
  350. )
  351. last_heartbeat = now
  352. poll = await self._hass.async_add_executor_job(
  353. self._api.receive,
  354. )
  355. # Ignore Payload error 904, as 3.4 protocol devices seem to return
  356. # this when there is no new data, instead of just returning nothing.
  357. if poll and "Err" in poll and poll["Err"] == "904":
  358. poll = None
  359. else:
  360. force_backoff = True
  361. poll = None
  362. if poll:
  363. if "Error" in poll:
  364. # increment the error count if not done already
  365. if error_count == self._api_working_protocol_failures:
  366. self._api_working_protocol_failures += 1
  367. if self._api_working_protocol_failures == 1:
  368. _LOGGER.warning(
  369. "%s error reading: %s", self.name, poll["Error"]
  370. )
  371. else:
  372. _LOGGER.debug(
  373. "%s error reading: %s", self.name, poll["Error"]
  374. )
  375. if "Payload" in poll and poll["Payload"]:
  376. _LOGGER.debug(
  377. "%s err payload: %s",
  378. self.name,
  379. poll["Payload"],
  380. )
  381. else:
  382. if "dps" in poll:
  383. poll = poll["dps"]
  384. if isinstance(poll, dict):
  385. poll["full_poll"] = full_poll
  386. yield poll
  387. except CancelledError:
  388. self._running = False
  389. # Close the persistent connection when exiting the loop
  390. persist = False
  391. self._api.set_socketPersistent(False)
  392. if self._api.parent:
  393. self._api.parent.set_socketPersistent(False)
  394. raise
  395. except Exception as t:
  396. _LOGGER.exception(
  397. "%s receive loop error %s:%s",
  398. self.name,
  399. type(t).__name__,
  400. t,
  401. )
  402. persist = False
  403. self._api.set_socketPersistent(False)
  404. if self._api.parent:
  405. self._api.parent.set_socketPersistent(False)
  406. force_backoff = True
  407. finally:
  408. if self._api_lock.locked():
  409. self._api_lock.release()
  410. if not self.has_returned_state:
  411. force_backoff = True
  412. await asyncio.sleep(5 if force_backoff else 0.1)
  413. # Close the persistent connection when exiting the loop
  414. self._api.set_socketPersistent(False)
  415. if self._api.parent:
  416. self._api.parent.set_socketPersistent(False)
  417. def set_detected_product_id(self, product_id):
  418. self._product_ids.append(product_id)
  419. async def async_possible_types(self):
  420. cached_state = self._get_cached_state()
  421. if len(cached_state) <= 1:
  422. # in case of device22 devices, we need to poll them with a dp
  423. # that exists on the device to get anything back. Most switch-like
  424. # devices have dp 1. Lights generally start from 20. 101 is where
  425. # vendor specific dps start. Between them, these three should cover
  426. # most devices. 148 covers a doorbell device that didn't have these
  427. # 201 covers remote controllers and 2 and 9 cover others without 1
  428. self._api.set_dpsUsed(
  429. {
  430. "1": None,
  431. "2": None,
  432. "9": None,
  433. "20": None,
  434. "60": None,
  435. "101": None,
  436. "148": None,
  437. "201": None,
  438. }
  439. )
  440. await self.async_refresh()
  441. cached_state = self._get_cached_state()
  442. return await self._hass.async_add_executor_job(
  443. _collect_possible_matches,
  444. cached_state,
  445. self._product_ids,
  446. )
  447. async def async_inferred_type(self):
  448. best_match = None
  449. best_quality = 0
  450. cached_state = self._get_cached_state()
  451. possible = await self.async_possible_types()
  452. for config in possible:
  453. quality = config.match_quality(cached_state, self._product_ids)
  454. _LOGGER.info(
  455. "%s considering %s with quality %s",
  456. self.name,
  457. config.name,
  458. quality,
  459. )
  460. if quality > best_quality:
  461. best_quality = quality
  462. best_match = config
  463. if best_match:
  464. return best_match.config_type
  465. _LOGGER.warning(
  466. "Detection for %s with dps %s failed",
  467. self.name,
  468. log_json(cached_state),
  469. )
  470. async def async_refresh(self):
  471. _LOGGER.debug("Refreshing device state for %s", self.name)
  472. if not self._running:
  473. await self._retry_on_failed_connection(
  474. lambda: self._refresh_cached_state(),
  475. f"Failed to refresh device state for {self.name}.",
  476. )
  477. def get_property(self, dps_id):
  478. cached_state = self._get_cached_state()
  479. return cached_state.get(dps_id)
  480. async def async_set_property(self, dps_id, value):
  481. await self.async_set_properties({dps_id: value})
  482. def anticipate_property_value(self, dps_id, value):
  483. """
  484. Update a value in the cached state only. This is good for when you
  485. know the device will reflect a new state in the next update, but
  486. don't want to wait for that update for the device to represent
  487. this state.
  488. The anticipated value will be cleared with the next update.
  489. """
  490. self._cached_state[dps_id] = value
  491. def _reset_cached_state(self):
  492. self._cached_state = {"updated_at": 0}
  493. self._pending_updates = {}
  494. self._last_connection = 0
  495. self._last_full_poll = 0
  496. def _refresh_cached_state(self):
  497. new_state = self._api.status()
  498. if new_state:
  499. if "Err" not in new_state:
  500. self._cached_state = self._cached_state | new_state.get("dps", {})
  501. self._cached_state["updated_at"] = time()
  502. for entity in self._children:
  503. for dp in entity._config.dps():
  504. # Clear non-persistant dps that were not in the poll
  505. if not dp.persist and dp.id not in new_state.get("dps", {}):
  506. self._cached_state.pop(dp.id, None)
  507. entity.schedule_update_ha_state()
  508. elif self._api_working_protocol_failures == 1:
  509. _LOGGER.warning(
  510. "%s protocol error %s: %s",
  511. self.name,
  512. new_state.get("Err"),
  513. new_state.get("Error", "message not provided"),
  514. )
  515. else:
  516. _LOGGER.debug(
  517. "%s protocol error %s: %s",
  518. self.name,
  519. new_state.get("Err"),
  520. new_state.get("Error", "message not provided"),
  521. )
  522. _LOGGER.debug(
  523. "%s refreshed device state: %s",
  524. self.name,
  525. log_json(new_state),
  526. )
  527. _LOGGER.debug(
  528. "new state (incl pending): %s",
  529. log_json(self._get_cached_state()),
  530. )
  531. return new_state
  532. async def async_set_properties(self, properties):
  533. if len(properties) == 0:
  534. return
  535. self._add_properties_to_pending_updates(properties)
  536. await self._debounce_sending_updates()
  537. def _add_properties_to_pending_updates(self, properties):
  538. now = time()
  539. pending_updates = self._get_pending_updates()
  540. for key, value in properties.items():
  541. pending_updates[key] = {
  542. "value": value,
  543. "updated_at": now,
  544. "sent": False,
  545. }
  546. _LOGGER.debug(
  547. "%s new pending updates: %s",
  548. self.name,
  549. log_json(pending_updates),
  550. )
  551. def _remove_properties_from_pending_updates(self, data):
  552. self._pending_updates = {
  553. key: value
  554. for key, value in self._pending_updates.items()
  555. if key not in data or not value["sent"] or data[key] != value["value"]
  556. }
  557. async def _debounce_sending_updates(self):
  558. now = time()
  559. since = now - self._last_connection
  560. # set this now to avoid a race condition, it will be updated later
  561. # when the data is actally sent
  562. self._last_connection = now
  563. # Only delay a second if there was recently another command.
  564. # Otherwise delay 1ms, to keep things simple by reusing the
  565. # same send mechanism.
  566. waittime = 1 if since < 1.1 and self.should_poll else 0.001
  567. await asyncio.sleep(waittime)
  568. await self._send_pending_updates()
  569. async def _send_pending_updates(self):
  570. pending_properties = self._get_unsent_properties()
  571. _LOGGER.debug(
  572. "%s sending dps update: %s",
  573. self.name,
  574. log_json(pending_properties),
  575. )
  576. await self._retry_on_failed_connection(
  577. lambda: self._set_values(pending_properties),
  578. "Failed to update device state.",
  579. )
  580. def _set_values(self, properties):
  581. try:
  582. self._lock.acquire()
  583. self._api.set_multiple_values(properties, nowait=True)
  584. now = time()
  585. self._last_connection = now
  586. pending_updates = self._get_pending_updates()
  587. for key in properties.keys():
  588. pending_updates[key]["updated_at"] = now
  589. pending_updates[key]["sent"] = True
  590. finally:
  591. self._lock.release()
  592. async def _retry_on_failed_connection(self, func, error_message):
  593. if self._api_protocol_version_index is None:
  594. await self._rotate_api_protocol_version()
  595. auto = (self._protocol_configured == "auto") and (
  596. not self._api_protocol_working
  597. )
  598. connections = (
  599. self._AUTO_CONNECTION_ATTEMPTS
  600. if auto
  601. else self._SINGLE_PROTO_CONNECTION_ATTEMPTS
  602. )
  603. last_err_code = None
  604. last_err_msg = None
  605. for i in range(connections):
  606. try:
  607. if not self._hass.is_stopping:
  608. retval = await self._hass.async_add_executor_job(func)
  609. if isinstance(retval, dict) and "Error" in retval:
  610. last_err_code = retval.get("Err")
  611. last_err_msg = retval.get("Error")
  612. if last_err_code == "900":
  613. # Some devices (e.g. IR/RF remotes) never return
  614. # status data; error 900 is their normal response
  615. # to a status query. Treat as reachable with no
  616. # data so commands can still be sent.
  617. self._cached_state["updated_at"] = time()
  618. retval = None
  619. else:
  620. raise AttributeError(retval["Error"])
  621. self._api_protocol_working = True
  622. self._api_working_protocol_failures = 0
  623. return retval
  624. except Exception as e:
  625. _LOGGER.debug(
  626. "Retrying after exception %s %s (%d/%d)",
  627. type(e).__name__,
  628. e,
  629. i,
  630. connections,
  631. )
  632. # Ensure we have a fresh connection for the next attempt
  633. self._api.set_socketPersistent(False)
  634. if self._api.parent:
  635. self._api.parent.set_socketPersistent(False)
  636. if i + 1 == connections:
  637. self._reset_cached_state()
  638. self._api_working_protocol_failures += 1
  639. if (
  640. self._api_working_protocol_failures
  641. > self._AUTO_FAILURE_RESET_COUNT
  642. ):
  643. self._api_protocol_working = False
  644. for entity in self._children:
  645. entity.async_schedule_update_ha_state()
  646. if last_err_code:
  647. log_format = "%s Device reported error %s: %s%s"
  648. log_args = (
  649. error_message,
  650. last_err_code,
  651. last_err_msg,
  652. _ERROR_HINTS.get(last_err_code, ""),
  653. )
  654. else:
  655. log_format = "%s"
  656. log_args = (error_message,)
  657. if self._api_working_protocol_failures == 1 and not (
  658. last_err_code == "914" and self._protocol_configured == "auto"
  659. ):
  660. _LOGGER.error(log_format, *log_args)
  661. else:
  662. _LOGGER.debug(log_format, *log_args)
  663. if not self._api_protocol_working:
  664. await self._rotate_api_protocol_version()
  665. def _get_cached_state(self):
  666. cached_state = self._cached_state.copy()
  667. return {**cached_state, **self._get_pending_properties()}
  668. def _get_pending_properties(self):
  669. return {key: prop["value"] for key, prop in self._get_pending_updates().items()}
  670. def _get_unsent_properties(self):
  671. return {
  672. key: info["value"]
  673. for key, info in self._get_pending_updates().items()
  674. if not info["sent"]
  675. }
  676. def _get_pending_updates(self):
  677. now = time()
  678. # sort pending updates according to their API identifier
  679. pending_updates_sorted = sorted(
  680. self._pending_updates.items(), key=lambda x: int(x[0])
  681. )
  682. self._pending_updates = {
  683. key: value
  684. for key, value in pending_updates_sorted
  685. if not value["sent"]
  686. or now - value.get("updated_at", 0) < self._FAKE_IT_TIMEOUT
  687. }
  688. return self._pending_updates
  689. async def _rotate_api_protocol_version(self):
  690. if self._api_protocol_version_index is None:
  691. try:
  692. self._api_protocol_version_index = API_PROTOCOL_VERSIONS.index(
  693. self._protocol_configured
  694. )
  695. except ValueError:
  696. self._api_protocol_version_index = 0
  697. # only rotate if configured as auto
  698. elif self._protocol_configured == "auto":
  699. self._api_protocol_version_index += 1
  700. if self._api_protocol_version_index >= len(API_PROTOCOL_VERSIONS):
  701. self._api_protocol_version_index = 0
  702. new_version = API_PROTOCOL_VERSIONS[self._api_protocol_version_index]
  703. _LOGGER.debug(
  704. "Setting protocol version for %s to %s",
  705. self.name,
  706. new_version,
  707. )
  708. # Only enable tinytuya's "device22" auto-detect when using 3.22, 3.4, or 3.5
  709. # Enabling this on 3.1 or 3.3 devices can cause them to stop responding to commands.
  710. # 3.2 always uses the "device22" protocol variant.
  711. # 3.22 is a fake version that actually means 3.3 with auto-detect enabled
  712. #
  713. # Note: "device22" is a misnomer for historical reasons. Not all devices with
  714. # 22 character device ids use this protocol variant.
  715. if new_version == 3.22:
  716. new_version = 3.3
  717. self._api.disabledetect = False
  718. else:
  719. self._api.disabledetect = new_version < 3.4
  720. await self._hass.async_add_executor_job(
  721. self._api.set_version,
  722. new_version,
  723. )
  724. if self._api.parent:
  725. await self._hass.async_add_executor_job(
  726. self._api.parent.set_version,
  727. new_version,
  728. )
  729. @staticmethod
  730. def get_key_for_value(obj, value, fallback=None):
  731. keys = list(obj.keys())
  732. values = list(obj.values())
  733. return keys[values.index(value)] if value in values else fallback
  734. def setup_device(hass: HomeAssistant, config: dict):
  735. """Setup a tuya device based on passed in config."""
  736. _LOGGER.info("Creating device: %s", get_device_id(config))
  737. hass.data[DOMAIN] = hass.data.get(DOMAIN, {})
  738. device = TuyaLocalDevice(
  739. config[CONF_NAME],
  740. config[CONF_DEVICE_ID],
  741. config[CONF_HOST],
  742. config[CONF_LOCAL_KEY],
  743. config[CONF_PROTOCOL_VERSION],
  744. config.get(CONF_DEVICE_CID),
  745. hass,
  746. config[CONF_POLL_ONLY],
  747. manufacturer=config.get(CONF_MANUFACTURER),
  748. model=config.get(CONF_MODEL),
  749. )
  750. hass.data[DOMAIN][get_device_id(config)] = {
  751. "device": device,
  752. "tuyadevice": device._api,
  753. "tuyadevicelock": device._api_lock,
  754. }
  755. return device
  756. async def async_delete_device(hass: HomeAssistant, config: dict):
  757. device_id = get_device_id(config)
  758. _LOGGER.info("Deleting device: %s", device_id)
  759. domain_data = hass.data.get(DOMAIN, {})
  760. device_entry = domain_data.get(device_id)
  761. if device_entry is None:
  762. return
  763. device = device_entry.get("device")
  764. if device is not None:
  765. await device.async_stop()
  766. device_entry.pop("device", None)
  767. device_entry.pop("tuyadevice", None)
  768. device_entry.pop("tuyadevicelock", None)
  769. # Platform setup may cache entity instances in this bucket by config_id.
  770. # Only drop empty buckets here; async_unload_entry removes the whole bucket
  771. # after forwarded platform unloads complete.
  772. if not device_entry:
  773. domain_data.pop(device_id, None)