device.py 34 KB

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