device.py 33 KB

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