device.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. """
  2. API for Tuya Local devices.
  3. """
  4. import asyncio
  5. import json
  6. import logging
  7. import tinytuya
  8. from threading import Lock
  9. from time import time
  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
  17. from .const import (
  18. API_PROTOCOL_VERSIONS,
  19. CONF_DEVICE_ID,
  20. CONF_LOCAL_KEY,
  21. CONF_POLL_ONLY,
  22. CONF_PROTOCOL_VERSION,
  23. DOMAIN,
  24. )
  25. from .helpers.device_config import possible_matches
  26. _LOGGER = logging.getLogger(__name__)
  27. def non_json(input):
  28. """Handler for json_dumps when used for debugging."""
  29. return f"Non-JSON: ({input})"
  30. class TuyaLocalDevice(object):
  31. def __init__(
  32. self,
  33. name,
  34. dev_id,
  35. address,
  36. local_key,
  37. protocol_version,
  38. hass: HomeAssistant,
  39. poll_only=False,
  40. ):
  41. """
  42. Represents a Tuya-based device.
  43. Args:
  44. dev_id (str): The device id.
  45. address (str): The network address.
  46. local_key (str): The encryption key.
  47. protocol_version (str | number): The protocol version.
  48. hass (HomeAssistant): The Home Assistant instance.
  49. poll_only (bool): True if the device should be polled only
  50. """
  51. self._name = name
  52. self._children = []
  53. self._force_dps = []
  54. self._running = False
  55. self._shutdown_listener = None
  56. self._startup_listener = None
  57. self._api_protocol_version_index = None
  58. self._api_protocol_working = False
  59. self._api = tinytuya.Device(dev_id, address, local_key)
  60. # we handle retries at a higher level so we can rotate protocol version
  61. self._api.set_socketRetryLimit(1)
  62. self._refresh_task = None
  63. self._protocol_configured = protocol_version
  64. self._poll_only = poll_only
  65. self._temporary_poll = False
  66. self._reset_cached_state()
  67. self._hass = hass
  68. # API calls to update Tuya devices are asynchronous and non-blocking.
  69. # This means you can send a change and immediately request an updated
  70. # state (like HA does), but because it has not yet finished processing
  71. # you will be returned the old state.
  72. # The solution is to keep a temporary list of changed properties that
  73. # we can overlay onto the state while we wait for the board to update
  74. # its switches.
  75. self._FAKE_IT_TIMEOUT = 5
  76. self._CACHE_TIMEOUT = 30
  77. # More attempts are needed in auto mode so we can cycle through all
  78. # the possibilities a couple of times
  79. self._AUTO_CONNECTION_ATTEMPTS = len(API_PROTOCOL_VERSIONS) * 2 + 1
  80. self._SINGLE_PROTO_CONNECTION_ATTEMPTS = 3
  81. self._lock = Lock()
  82. @property
  83. def name(self):
  84. return self._name
  85. @property
  86. def unique_id(self):
  87. """Return the unique id for this device (the dev_id)."""
  88. return self._api.id
  89. @property
  90. def device_info(self):
  91. """Return the device information for this device."""
  92. return {
  93. "identifiers": {(DOMAIN, self.unique_id)},
  94. "name": self.name,
  95. "manufacturer": "Tuya",
  96. }
  97. @property
  98. def has_returned_state(self):
  99. """Return True if the device has returned some state."""
  100. return len(self._get_cached_state()) > 1
  101. def actually_start(self, event=None):
  102. _LOGGER.debug("Starting monitor loop for %s", self.name)
  103. self._running = True
  104. self._shutdown_listener = self._hass.bus.async_listen_once(
  105. EVENT_HOMEASSISTANT_STOP, self.async_stop
  106. )
  107. self._refresh_task = self._hass.async_create_task(self.receive_loop())
  108. def start(self):
  109. if self._hass.is_stopping:
  110. return
  111. elif self._hass.is_running:
  112. if self._startup_listener:
  113. self._startup_listener()
  114. self._startup_listener = None
  115. self.actually_start()
  116. else:
  117. self._startup_listener = self._hass.bus.async_listen_once(
  118. EVENT_HOMEASSISTANT_STARTED, self.actually_start
  119. )
  120. async def async_stop(self, event=None):
  121. _LOGGER.debug("Stopping monitor loop for %s", self.name)
  122. self._running = False
  123. if self._shutdown_listener:
  124. self._shutdown_listener()
  125. self._shutdown_listener = None
  126. self._children.clear()
  127. self._force_dps.clear()
  128. if self._refresh_task:
  129. await self._refresh_task
  130. _LOGGER.debug("Monitor loop for %s stopped", self.name)
  131. self._refresh_task = None
  132. def register_entity(self, entity):
  133. # If this is the first child entity to register, refresh the device
  134. # state
  135. should_poll = len(self._children) == 0
  136. self._children.append(entity)
  137. for dp in entity._config.dps():
  138. if dp.force and dp.id not in self._force_dps:
  139. self._force_dps.append(dp.id)
  140. if not self._running and not self._startup_listener:
  141. self.start()
  142. if self.has_returned_state:
  143. entity.async_schedule_update_ha_state()
  144. elif should_poll:
  145. entity.async_schedule_update_ha_state(True)
  146. async def async_unregister_entity(self, entity):
  147. self._children.remove(entity)
  148. if not self._children:
  149. await self.async_stop()
  150. async def receive_loop(self):
  151. """Coroutine wrapper for async_receive generator."""
  152. try:
  153. async for poll in self.async_receive():
  154. if type(poll) is dict:
  155. _LOGGER.debug(
  156. "%s received %s",
  157. self.name,
  158. json.dumps(poll, default=non_json),
  159. )
  160. self._cached_state = self._cached_state | poll
  161. self._cached_state["updated_at"] = time()
  162. for entity in self._children:
  163. entity.async_schedule_update_ha_state()
  164. else:
  165. _LOGGER.debug(
  166. "%s received non data %s",
  167. self.name,
  168. json.dumps(poll, default=non_json),
  169. )
  170. _LOGGER.warning("%s receive loop has terminated", self.name)
  171. except Exception as t:
  172. _LOGGER.exception(
  173. "%s receive loop terminated by exception %s", self.name, t
  174. )
  175. @property
  176. def should_poll(self):
  177. return self._poll_only or self._temporary_poll or not self.has_returned_state
  178. def pause(self):
  179. self._temporary_poll = True
  180. def resume(self):
  181. self._temporary_poll = False
  182. async def async_receive(self):
  183. """Receive messages from a persistent connection asynchronously."""
  184. # If we didn't yet get any state from the device, we may need to
  185. # negotiate the protocol before making the connection persistent
  186. persist = not self.should_poll
  187. # flag to alternate updatedps and status calls to ensure we get
  188. # all dps updated
  189. dps_updated = False
  190. self._api.set_socketPersistent(persist)
  191. while self._running:
  192. try:
  193. last_cache = self._cached_state.get("updated_at", 0)
  194. now = time()
  195. if persist == self.should_poll:
  196. # use persistent connections after initial communication
  197. # has been established. Until then, we need to rotate
  198. # the protocol version, which seems to require a fresh
  199. # connection.
  200. persist = not self.should_poll
  201. self._api.set_socketPersistent(persist)
  202. if now - last_cache > self._CACHE_TIMEOUT:
  203. if (
  204. self._force_dps
  205. and not dps_updated
  206. and self._api_protocol_working
  207. ):
  208. poll = await self._retry_on_failed_connection(
  209. lambda: self._api.updatedps(self._force_dps),
  210. f"Failed to refresh device state for {self.name}",
  211. )
  212. dps_updated = True
  213. else:
  214. poll = await self._retry_on_failed_connection(
  215. lambda: self._api.status(),
  216. f"Failed to refresh device state for {self.name}",
  217. )
  218. dps_updated = False
  219. else:
  220. await self._hass.async_add_executor_job(
  221. self._api.heartbeat,
  222. True,
  223. )
  224. poll = await self._hass.async_add_executor_job(
  225. self._api.receive,
  226. )
  227. if poll:
  228. if "Error" in poll:
  229. _LOGGER.warning(
  230. "%s error reading: %s", self.name, poll["Error"]
  231. )
  232. if "Payload" in poll and poll["Payload"]:
  233. _LOGGER.info(
  234. "%s err payload: %s",
  235. self.name,
  236. poll["Payload"],
  237. )
  238. else:
  239. if "dps" in poll:
  240. poll = poll["dps"]
  241. yield poll
  242. await asyncio.sleep(0.1 if self.has_returned_state else 5)
  243. except asyncio.CancelledError:
  244. self._running = False
  245. # Close the persistent connection when exiting the loop
  246. self._api.set_socketPersistent(False)
  247. raise
  248. except Exception as t:
  249. _LOGGER.exception(
  250. "%s receive loop error %s:%s",
  251. self.name,
  252. type(t),
  253. t,
  254. )
  255. await asyncio.sleep(5)
  256. # Close the persistent connection when exiting the loop
  257. self._api.set_socketPersistent(False)
  258. async def async_possible_types(self):
  259. cached_state = self._get_cached_state()
  260. if len(cached_state) <= 1:
  261. await self.async_refresh()
  262. cached_state = self._get_cached_state()
  263. for match in possible_matches(cached_state):
  264. yield match
  265. async def async_inferred_type(self):
  266. best_match = None
  267. best_quality = 0
  268. cached_state = self._get_cached_state()
  269. async for config in self.async_possible_types():
  270. quality = config.match_quality(cached_state)
  271. _LOGGER.info(
  272. "%s considering %s with quality %s",
  273. self.name,
  274. config.name,
  275. quality,
  276. )
  277. if quality > best_quality:
  278. best_quality = quality
  279. best_match = config
  280. if best_match is None:
  281. _LOGGER.warning(
  282. "Detection for %s with dps %s failed",
  283. self.name,
  284. json.dumps(cached_state, default=non_json),
  285. )
  286. return None
  287. return best_match.config_type
  288. async def async_refresh(self):
  289. _LOGGER.debug("Refreshing device state for %s", self.name)
  290. await self._retry_on_failed_connection(
  291. lambda: self._refresh_cached_state(),
  292. f"Failed to refresh device state for {self.name}.",
  293. )
  294. def get_property(self, dps_id):
  295. cached_state = self._get_cached_state()
  296. return cached_state.get(dps_id)
  297. async def async_set_property(self, dps_id, value):
  298. await self.async_set_properties({dps_id: value})
  299. def anticipate_property_value(self, dps_id, value):
  300. """
  301. Update a value in the cached state only. This is good for when you
  302. know the device will reflect a new state in the next update, but
  303. don't want to wait for that update for the device to represent
  304. this state.
  305. The anticipated value will be cleared with the next update.
  306. """
  307. self._cached_state[dps_id] = value
  308. def _reset_cached_state(self):
  309. self._cached_state = {"updated_at": 0}
  310. self._pending_updates = {}
  311. self._last_connection = 0
  312. def _refresh_cached_state(self):
  313. new_state = self._api.status()
  314. self._cached_state = self._cached_state | new_state.get("dps", {})
  315. self._cached_state["updated_at"] = time()
  316. for entity in self._children:
  317. entity.async_schedule_update_ha_state()
  318. _LOGGER.debug(
  319. "%s refreshed device state: %s",
  320. self.name,
  321. json.dumps(new_state, default=non_json),
  322. )
  323. _LOGGER.debug(
  324. "new state (incl pending): %s",
  325. json.dumps(self._get_cached_state(), default=non_json),
  326. )
  327. async def async_set_properties(self, properties):
  328. if len(properties) == 0:
  329. return
  330. self._add_properties_to_pending_updates(properties)
  331. await self._debounce_sending_updates()
  332. def _add_properties_to_pending_updates(self, properties):
  333. now = time()
  334. pending_updates = self._get_pending_updates()
  335. for key, value in properties.items():
  336. pending_updates[key] = {
  337. "value": value,
  338. "updated_at": now,
  339. "sent": False,
  340. }
  341. _LOGGER.debug(
  342. "%s new pending updates: %s",
  343. self.name,
  344. json.dumps(pending_updates, default=non_json),
  345. )
  346. async def _debounce_sending_updates(self):
  347. now = time()
  348. since = now - self._last_connection
  349. # set this now to avoid a race condition, it will be updated later
  350. # when the data is actally sent
  351. self._last_connection = now
  352. # Only delay a second if there was recently another command.
  353. # Otherwise delay 1ms, to keep things simple by reusing the
  354. # same send mechanism.
  355. waittime = 1 if since < 1.1 else 0.001
  356. await asyncio.sleep(waittime)
  357. await self._send_pending_updates()
  358. async def _send_pending_updates(self):
  359. pending_properties = self._get_unsent_properties()
  360. _LOGGER.debug(
  361. "%s sending dps update: %s",
  362. self.name,
  363. json.dumps(pending_properties, default=non_json),
  364. )
  365. await self._retry_on_failed_connection(
  366. lambda: self._set_values(pending_properties),
  367. "Failed to update device state.",
  368. )
  369. def _set_values(self, properties):
  370. try:
  371. self._lock.acquire()
  372. self._api.set_multiple_values(properties, nowait=True)
  373. self._cached_state["updated_at"] = 0
  374. now = time()
  375. self._last_connection = now
  376. pending_updates = self._get_pending_updates()
  377. for key in properties.keys():
  378. pending_updates[key]["updated_at"] = now
  379. pending_updates[key]["sent"] = True
  380. finally:
  381. self._lock.release()
  382. async def _retry_on_failed_connection(self, func, error_message):
  383. if self._api_protocol_version_index is None:
  384. await self._rotate_api_protocol_version()
  385. auto = (self._protocol_configured == "auto") and (
  386. not self._api_protocol_working
  387. )
  388. connections = (
  389. self._AUTO_CONNECTION_ATTEMPTS
  390. if auto
  391. else self._SINGLE_PROTO_CONNECTION_ATTEMPTS
  392. )
  393. for i in range(connections):
  394. try:
  395. if not self._hass.is_stopping:
  396. retval = await self._hass.async_add_executor_job(func)
  397. if type(retval) is dict and "Error" in retval:
  398. raise AttributeError
  399. self._api_protocol_working = True
  400. return retval
  401. except Exception as e:
  402. _LOGGER.debug(
  403. "Retrying after exception %s (%d/%d)",
  404. e,
  405. i,
  406. connections,
  407. )
  408. if i + 1 == connections:
  409. self._reset_cached_state()
  410. self._api_protocol_working = False
  411. for entity in self._children:
  412. entity.async_schedule_update_ha_state()
  413. _LOGGER.error(error_message)
  414. if not self._api_protocol_working:
  415. await self._rotate_api_protocol_version()
  416. def _get_cached_state(self):
  417. cached_state = self._cached_state.copy()
  418. return {**cached_state, **self._get_pending_properties()}
  419. def _get_pending_properties(self):
  420. return {
  421. key: property["value"]
  422. for key, property in self._get_pending_updates().items()
  423. }
  424. def _get_unsent_properties(self):
  425. return {
  426. key: info["value"]
  427. for key, info in self._get_pending_updates().items()
  428. if not info["sent"]
  429. }
  430. def _get_pending_updates(self):
  431. now = time()
  432. self._pending_updates = {
  433. key: value
  434. for key, value in self._pending_updates.items()
  435. if now - value.get("updated_at", 0) < self._FAKE_IT_TIMEOUT
  436. }
  437. return self._pending_updates
  438. async def _rotate_api_protocol_version(self):
  439. if self._api_protocol_version_index is None:
  440. try:
  441. self._api_protocol_version_index = API_PROTOCOL_VERSIONS.index(
  442. self._protocol_configured
  443. )
  444. except ValueError:
  445. self._api_protocol_version_index = 0
  446. # only rotate if configured as auto
  447. elif self._protocol_configured == "auto":
  448. self._api_protocol_version_index += 1
  449. if self._api_protocol_version_index >= len(API_PROTOCOL_VERSIONS):
  450. self._api_protocol_version_index = 0
  451. new_version = API_PROTOCOL_VERSIONS[self._api_protocol_version_index]
  452. _LOGGER.info(
  453. "Setting protocol version for %s to %f",
  454. self.name,
  455. new_version,
  456. )
  457. await self._hass.async_add_executor_job(
  458. self._api.set_version,
  459. new_version,
  460. )
  461. @staticmethod
  462. def get_key_for_value(obj, value, fallback=None):
  463. keys = list(obj.keys())
  464. values = list(obj.values())
  465. return keys[values.index(value)] if value in values else fallback
  466. def setup_device(hass: HomeAssistant, config: dict):
  467. """Setup a tuya device based on passed in config."""
  468. _LOGGER.info("Creating device: %s", config[CONF_DEVICE_ID])
  469. hass.data[DOMAIN] = hass.data.get(DOMAIN, {})
  470. device = TuyaLocalDevice(
  471. config[CONF_NAME],
  472. config[CONF_DEVICE_ID],
  473. config[CONF_HOST],
  474. config[CONF_LOCAL_KEY],
  475. config[CONF_PROTOCOL_VERSION],
  476. hass,
  477. config[CONF_POLL_ONLY],
  478. )
  479. hass.data[DOMAIN][config[CONF_DEVICE_ID]] = {"device": device}
  480. return device
  481. async def async_delete_device(hass: HomeAssistant, config: dict):
  482. _LOGGER.info("Deleting device: %s", config[CONF_DEVICE_ID])
  483. await hass.data[DOMAIN][config[CONF_DEVICE_ID]]["device"].async_stop()
  484. del hass.data[DOMAIN][config[CONF_DEVICE_ID]]["device"]