4
0

device.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  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. needs_full_poll = now - self._last_full_poll > self._CACHE_TIMEOUT
  292. if now - last_cache > self._CACHE_TIMEOUT or (
  293. persist and needs_full_poll
  294. ):
  295. if (
  296. self._force_dps
  297. and not dps_updated
  298. and self._api_protocol_working
  299. ):
  300. poll = await self._retry_on_failed_connection(
  301. lambda: self._api.updatedps(self._force_dps),
  302. f"Failed to update device dps for {self.name}",
  303. )
  304. dps_updated = True
  305. else:
  306. poll = await self._retry_on_failed_connection(
  307. lambda: self._api.status(),
  308. f"Failed to fetch device status for {self.name}",
  309. )
  310. dps_updated = False
  311. full_poll = True
  312. self._last_full_poll = now
  313. elif persist:
  314. await self._hass.async_add_executor_job(
  315. self._api.heartbeat,
  316. True,
  317. )
  318. poll = await self._hass.async_add_executor_job(
  319. self._api.receive,
  320. )
  321. else:
  322. force_backoff = True
  323. poll = None
  324. if poll:
  325. if "Error" in poll:
  326. # increment the error count if not done already
  327. if error_count == self._api_working_protocol_failures:
  328. self._api_working_protocol_failures += 1
  329. if self._api_working_protocol_failures == 1:
  330. _LOGGER.warning(
  331. "%s error reading: %s", self.name, poll["Error"]
  332. )
  333. else:
  334. _LOGGER.debug(
  335. "%s error reading: %s", self.name, poll["Error"]
  336. )
  337. if "Payload" in poll and poll["Payload"]:
  338. _LOGGER.debug(
  339. "%s err payload: %s",
  340. self.name,
  341. poll["Payload"],
  342. )
  343. else:
  344. if "dps" in poll:
  345. poll = poll["dps"]
  346. poll["full_poll"] = full_poll
  347. yield poll
  348. except CancelledError:
  349. self._running = False
  350. # Close the persistent connection when exiting the loop
  351. self._api.set_socketPersistent(False)
  352. if self._api.parent:
  353. self._api.parent.set_socketPersistent(False)
  354. raise
  355. except Exception as t:
  356. _LOGGER.exception(
  357. "%s receive loop error %s:%s",
  358. self.name,
  359. type(t).__name__,
  360. t,
  361. )
  362. self._api.set_socketPersistent(False)
  363. if self._api.parent:
  364. self._api.parent.set_socketPersistent(False)
  365. force_backoff = True
  366. finally:
  367. if self._api_lock.locked():
  368. self._api_lock.release()
  369. if not self.has_returned_state:
  370. force_backoff = True
  371. await asyncio.sleep(5 if force_backoff else 0.1)
  372. # Close the persistent connection when exiting the loop
  373. self._api.set_socketPersistent(False)
  374. if self._api.parent:
  375. self._api.parent.set_socketPersistent(False)
  376. def set_detected_product_id(self, product_id):
  377. self._product_ids.append(product_id)
  378. async def async_possible_types(self):
  379. cached_state = self._get_cached_state()
  380. if len(cached_state) <= 1:
  381. # in case of device22 devices, we need to poll them with a dp
  382. # that exists on the device to get anything back. Most switch-like
  383. # devices have dp 1. Lights generally start from 20. 101 is where
  384. # vendor specific dps start. Between them, these three should cover
  385. # most devices. 148 covers a doorbell device that didn't have these
  386. # 201 covers remote controllers and 2 and 9 cover others without 1
  387. self._api.set_dpsUsed(
  388. {
  389. "1": None,
  390. "2": None,
  391. "9": None,
  392. "20": None,
  393. "60": None,
  394. "101": None,
  395. "148": None,
  396. "201": None,
  397. }
  398. )
  399. await self.async_refresh()
  400. cached_state = self._get_cached_state()
  401. return await self._hass.async_add_executor_job(
  402. _collect_possible_matches,
  403. cached_state,
  404. self._product_ids,
  405. )
  406. async def async_inferred_type(self):
  407. best_match = None
  408. best_quality = 0
  409. cached_state = self._get_cached_state()
  410. possible = await self.async_possible_types()
  411. for config in possible:
  412. quality = config.match_quality(cached_state, self._product_ids)
  413. _LOGGER.info(
  414. "%s considering %s with quality %s",
  415. self.name,
  416. config.name,
  417. quality,
  418. )
  419. if quality > best_quality:
  420. best_quality = quality
  421. best_match = config
  422. if best_match:
  423. return best_match.config_type
  424. _LOGGER.warning(
  425. "Detection for %s with dps %s failed",
  426. self.name,
  427. log_json(cached_state),
  428. )
  429. async def async_refresh(self):
  430. _LOGGER.debug("Refreshing device state for %s", self.name)
  431. if not self._running:
  432. await self._retry_on_failed_connection(
  433. lambda: self._refresh_cached_state(),
  434. f"Failed to refresh device state for {self.name}.",
  435. )
  436. def get_property(self, dps_id):
  437. cached_state = self._get_cached_state()
  438. return cached_state.get(dps_id)
  439. async def async_set_property(self, dps_id, value):
  440. await self.async_set_properties({dps_id: value})
  441. def anticipate_property_value(self, dps_id, value):
  442. """
  443. Update a value in the cached state only. This is good for when you
  444. know the device will reflect a new state in the next update, but
  445. don't want to wait for that update for the device to represent
  446. this state.
  447. The anticipated value will be cleared with the next update.
  448. """
  449. self._cached_state[dps_id] = value
  450. def _reset_cached_state(self):
  451. self._cached_state = {"updated_at": 0}
  452. self._pending_updates = {}
  453. self._last_connection = 0
  454. self._last_full_poll = 0
  455. def _refresh_cached_state(self):
  456. new_state = self._api.status()
  457. if new_state and "Err" not in new_state:
  458. self._cached_state = self._cached_state | new_state.get("dps", {})
  459. self._cached_state["updated_at"] = time()
  460. for entity in self._children:
  461. for dp in entity._config.dps():
  462. # Clear non-persistant dps that were not in the poll
  463. if not dp.persist and dp.id not in new_state.get("dps", {}):
  464. self._cached_state.pop(dp.id, None)
  465. entity.schedule_update_ha_state()
  466. _LOGGER.debug(
  467. "%s refreshed device state: %s",
  468. self.name,
  469. log_json(new_state),
  470. )
  471. if "Err" in new_state:
  472. if self._api_working_protocol_failures == 1:
  473. _LOGGER.warning(
  474. "%s protocol error %s: %s",
  475. self.name,
  476. new_state.get("Err"),
  477. new_state.get("Error", "message not provided"),
  478. )
  479. else:
  480. _LOGGER.debug(
  481. "%s protocol error %s: %s",
  482. self.name,
  483. new_state.get("Err"),
  484. new_state.get("Error", "message not provided"),
  485. )
  486. _LOGGER.debug(
  487. "new state (incl pending): %s",
  488. log_json(self._get_cached_state()),
  489. )
  490. return new_state
  491. async def async_set_properties(self, properties):
  492. if len(properties) == 0:
  493. return
  494. self._add_properties_to_pending_updates(properties)
  495. await self._debounce_sending_updates()
  496. def _add_properties_to_pending_updates(self, properties):
  497. now = time()
  498. pending_updates = self._get_pending_updates()
  499. for key, value in properties.items():
  500. pending_updates[key] = {
  501. "value": value,
  502. "updated_at": now,
  503. "sent": False,
  504. }
  505. _LOGGER.debug(
  506. "%s new pending updates: %s",
  507. self.name,
  508. log_json(pending_updates),
  509. )
  510. def _remove_properties_from_pending_updates(self, data):
  511. self._pending_updates = {
  512. key: value
  513. for key, value in self._pending_updates.items()
  514. if key not in data or not value["sent"] or data[key] != value["value"]
  515. }
  516. async def _debounce_sending_updates(self):
  517. now = time()
  518. since = now - self._last_connection
  519. # set this now to avoid a race condition, it will be updated later
  520. # when the data is actally sent
  521. self._last_connection = now
  522. # Only delay a second if there was recently another command.
  523. # Otherwise delay 1ms, to keep things simple by reusing the
  524. # same send mechanism.
  525. waittime = 1 if since < 1.1 and self.should_poll else 0.001
  526. await asyncio.sleep(waittime)
  527. await self._send_pending_updates()
  528. async def _send_pending_updates(self):
  529. pending_properties = self._get_unsent_properties()
  530. _LOGGER.debug(
  531. "%s sending dps update: %s",
  532. self.name,
  533. log_json(pending_properties),
  534. )
  535. await self._retry_on_failed_connection(
  536. lambda: self._set_values(pending_properties),
  537. "Failed to update device state.",
  538. )
  539. def _set_values(self, properties):
  540. try:
  541. self._lock.acquire()
  542. self._api.set_multiple_values(properties, nowait=True)
  543. self._cached_state["updated_at"] = 0
  544. now = time()
  545. self._last_connection = now
  546. pending_updates = self._get_pending_updates()
  547. for key in properties.keys():
  548. pending_updates[key]["updated_at"] = now
  549. pending_updates[key]["sent"] = True
  550. finally:
  551. self._lock.release()
  552. async def _retry_on_failed_connection(self, func, error_message):
  553. if self._api_protocol_version_index is None:
  554. await self._rotate_api_protocol_version()
  555. auto = (self._protocol_configured == "auto") and (
  556. not self._api_protocol_working
  557. )
  558. connections = (
  559. self._AUTO_CONNECTION_ATTEMPTS
  560. if auto
  561. else self._SINGLE_PROTO_CONNECTION_ATTEMPTS
  562. )
  563. for i in range(connections):
  564. try:
  565. if not self._hass.is_stopping:
  566. retval = await self._hass.async_add_executor_job(func)
  567. if isinstance(retval, dict) and "Error" in retval:
  568. raise AttributeError(retval["Error"])
  569. self._api_protocol_working = True
  570. self._api_working_protocol_failures = 0
  571. return retval
  572. except Exception as e:
  573. _LOGGER.debug(
  574. "Retrying after exception %s %s (%d/%d)",
  575. type(e).__name__,
  576. e,
  577. i,
  578. connections,
  579. )
  580. if i + 1 == connections:
  581. self._reset_cached_state()
  582. self._api_working_protocol_failures += 1
  583. if (
  584. self._api_working_protocol_failures
  585. > self._AUTO_FAILURE_RESET_COUNT
  586. ):
  587. self._api_protocol_working = False
  588. for entity in self._children:
  589. entity.async_schedule_update_ha_state()
  590. if self._api_working_protocol_failures == 1:
  591. _LOGGER.error(error_message)
  592. else:
  593. _LOGGER.debug(error_message)
  594. if not self._api_protocol_working:
  595. await self._rotate_api_protocol_version()
  596. def _get_cached_state(self):
  597. cached_state = self._cached_state.copy()
  598. return {**cached_state, **self._get_pending_properties()}
  599. def _get_pending_properties(self):
  600. return {
  601. key: property["value"]
  602. for key, property in self._get_pending_updates().items()
  603. }
  604. def _get_unsent_properties(self):
  605. return {
  606. key: info["value"]
  607. for key, info in self._get_pending_updates().items()
  608. if not info["sent"]
  609. }
  610. def _get_pending_updates(self):
  611. now = time()
  612. # sort pending updates according to their API identifier
  613. pending_updates_sorted = sorted(
  614. self._pending_updates.items(), key=lambda x: int(x[0])
  615. )
  616. self._pending_updates = {
  617. key: value
  618. for key, value in pending_updates_sorted
  619. if not value["sent"]
  620. or now - value.get("updated_at", 0) < self._FAKE_IT_TIMEOUT
  621. }
  622. return self._pending_updates
  623. async def _rotate_api_protocol_version(self):
  624. if self._api_protocol_version_index is None:
  625. try:
  626. self._api_protocol_version_index = API_PROTOCOL_VERSIONS.index(
  627. self._protocol_configured
  628. )
  629. except ValueError:
  630. self._api_protocol_version_index = 0
  631. # only rotate if configured as auto
  632. elif self._protocol_configured == "auto":
  633. self._api_protocol_version_index += 1
  634. if self._api_protocol_version_index >= len(API_PROTOCOL_VERSIONS):
  635. self._api_protocol_version_index = 0
  636. new_version = API_PROTOCOL_VERSIONS[self._api_protocol_version_index]
  637. _LOGGER.debug(
  638. "Setting protocol version for %s to %0.1f",
  639. self.name,
  640. new_version,
  641. )
  642. # Only enable tinytuya's auto-detect when using 3.22
  643. if new_version == 3.22:
  644. new_version = 3.3
  645. self._api.disabledetect = False
  646. else:
  647. self._api.disabledetect = True
  648. await self._hass.async_add_executor_job(
  649. self._api.set_version,
  650. new_version,
  651. )
  652. if self._api.parent:
  653. await self._hass.async_add_executor_job(
  654. self._api.parent.set_version,
  655. new_version,
  656. )
  657. @staticmethod
  658. def get_key_for_value(obj, value, fallback=None):
  659. keys = list(obj.keys())
  660. values = list(obj.values())
  661. return keys[values.index(value)] if value in values else fallback
  662. def setup_device(hass: HomeAssistant, config: dict):
  663. """Setup a tuya device based on passed in config."""
  664. _LOGGER.info("Creating device: %s", get_device_id(config))
  665. hass.data[DOMAIN] = hass.data.get(DOMAIN, {})
  666. device = TuyaLocalDevice(
  667. config[CONF_NAME],
  668. config[CONF_DEVICE_ID],
  669. config[CONF_HOST],
  670. config[CONF_LOCAL_KEY],
  671. config[CONF_PROTOCOL_VERSION],
  672. config.get(CONF_DEVICE_CID),
  673. hass,
  674. config[CONF_POLL_ONLY],
  675. )
  676. hass.data[DOMAIN][get_device_id(config)] = {
  677. "device": device,
  678. "tuyadevice": device._api,
  679. "tuyadevicelock": device._api_lock,
  680. }
  681. return device
  682. async def async_delete_device(hass: HomeAssistant, config: dict):
  683. device_id = get_device_id(config)
  684. _LOGGER.info("Deleting device: %s", device_id)
  685. await hass.data[DOMAIN][device_id]["device"].async_stop()
  686. del hass.data[DOMAIN][device_id]["device"]
  687. del hass.data[DOMAIN][device_id]["tuyadevice"]
  688. del hass.data[DOMAIN][device_id]["tuyadevicelock"]