device.py 17 KB

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