device.py 26 KB

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