device.py 34 KB

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