device.py 28 KB

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