device.py 27 KB

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