device.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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 = len(API_PROTOCOL_VERSIONS) * 2 + 1
  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. # If this is the first child entity to register, refresh the device
  124. # state
  125. should_poll = len(self._children) == 0
  126. self._children.append(entity)
  127. if not self._running and not self._startup_listener:
  128. self.start()
  129. if self.has_returned_state:
  130. entity.async_schedule_update_ha_state()
  131. elif should_poll:
  132. entity.async_schedule_update_ha_state(True)
  133. async def async_unregister_entity(self, entity):
  134. self._children.remove(entity)
  135. if not self._children:
  136. await self.async_stop()
  137. async def receive_loop(self):
  138. """Coroutine wrapper for async_receive generator."""
  139. try:
  140. async for poll in self.async_receive():
  141. if type(poll) is dict:
  142. _LOGGER.debug(f"{self.name} received {poll}")
  143. self._cached_state = self._cached_state | poll
  144. self._cached_state["updated_at"] = time()
  145. for entity in self._children:
  146. entity.async_schedule_update_ha_state()
  147. else:
  148. _LOGGER.debug(f"{self.name} received non data {poll}")
  149. _LOGGER.warning(f"{self.name} receive loop has terminated")
  150. except Exception as t:
  151. _LOGGER.exception(
  152. f"{self.name} receive loop terminated by exception {t}",
  153. )
  154. async def async_receive(self):
  155. """Receive messages from a persistent connection asynchronously."""
  156. # If we didn't yet get any state from the device, we may need to
  157. # negotiate the protocol before making the connection persistent
  158. persist = self.has_returned_state
  159. self._api.set_socketPersistent(persist)
  160. while self._running:
  161. try:
  162. last_cache = self._cached_state["updated_at"]
  163. now = time()
  164. if persist != self.has_returned_state:
  165. # use persistent connections after initial communication
  166. # has been established. Until then, we need to rotate
  167. # the protocol version, which seems to require a fresh
  168. # connection.
  169. persist = self.has_returned_state
  170. self._api.set_socketPersistent(persist)
  171. if now - last_cache > self._CACHE_TIMEOUT:
  172. poll = await self._retry_on_failed_connection(
  173. lambda: self._api.status(),
  174. f"Failed to refresh device state for {self.name}",
  175. )
  176. else:
  177. await self._hass.async_add_executor_job(
  178. self._api.heartbeat,
  179. True,
  180. )
  181. poll = await self._hass.async_add_executor_job(
  182. self._api.receive,
  183. )
  184. if poll:
  185. if "Error" in poll:
  186. _LOGGER.warning(
  187. f"{self.name} error reading: {poll['Error']}",
  188. )
  189. if "Payload" in poll and poll["Payload"]:
  190. _LOGGER.info(
  191. f"{self.name} err payload: {poll['Payload']}",
  192. )
  193. else:
  194. if "dps" in poll:
  195. poll = poll["dps"]
  196. yield poll
  197. await asyncio.sleep(0.1 if self.has_returned_state else 5)
  198. except asyncio.CancelledError:
  199. self._running = False
  200. # Close the persistent connection when exiting the loop
  201. self._api.set_socketPersistent(False)
  202. raise
  203. except Exception as t:
  204. _LOGGER.exception(
  205. f"{self.name} receive loop error {type(t)}:{t}",
  206. )
  207. await asyncio.sleep(5)
  208. # Close the persistent connection when exiting the loop
  209. self._api.set_socketPersistent(False)
  210. async def async_possible_types(self):
  211. cached_state = self._get_cached_state()
  212. if len(cached_state) <= 1:
  213. await self.async_refresh()
  214. cached_state = self._get_cached_state()
  215. for match in possible_matches(cached_state):
  216. yield match
  217. async def async_inferred_type(self):
  218. best_match = None
  219. best_quality = 0
  220. cached_state = {}
  221. async for config in self.async_possible_types():
  222. cached_state = self._get_cached_state()
  223. quality = config.match_quality(cached_state)
  224. _LOGGER.info(
  225. f"{self.name} considering {config.name} with quality {quality}"
  226. )
  227. if quality > best_quality:
  228. best_quality = quality
  229. best_match = config
  230. if best_match is None:
  231. _LOGGER.warning(
  232. f"Detection for {self.name} with dps {cached_state} failed",
  233. )
  234. return None
  235. return best_match.config_type
  236. async def async_refresh(self):
  237. _LOGGER.debug(f"Refreshing device state for {self.name}.")
  238. await self._retry_on_failed_connection(
  239. lambda: self._refresh_cached_state(),
  240. f"Failed to refresh device state for {self.name}.",
  241. )
  242. def get_property(self, dps_id):
  243. cached_state = self._get_cached_state()
  244. if dps_id in cached_state:
  245. return cached_state[dps_id]
  246. else:
  247. return None
  248. async def async_set_property(self, dps_id, value):
  249. await self.async_set_properties({dps_id: value})
  250. def anticipate_property_value(self, dps_id, value):
  251. """
  252. Update a value in the cached state only. This is good for when you
  253. know the device will reflect a new state in the next update, but
  254. don't want to wait for that update for the device to represent
  255. this state.
  256. The anticipated value will be cleared with the next update.
  257. """
  258. self._cached_state[dps_id] = value
  259. def _reset_cached_state(self):
  260. self._cached_state = {"updated_at": 0}
  261. self._pending_updates = {}
  262. self._last_connection = 0
  263. def _refresh_cached_state(self):
  264. new_state = self._api.status()
  265. self._cached_state = self._cached_state | new_state["dps"]
  266. self._cached_state["updated_at"] = time()
  267. for entity in self._children:
  268. entity.async_schedule_update_ha_state()
  269. _LOGGER.debug(
  270. f"{self.name} refreshed device state: {json.dumps(new_state, default=non_json)}",
  271. )
  272. _LOGGER.debug(
  273. f"new state (incl pending): {json.dumps(self._get_cached_state(), default=non_json)}"
  274. )
  275. async def async_set_properties(self, properties):
  276. if len(properties) == 0:
  277. return
  278. self._add_properties_to_pending_updates(properties)
  279. await self._debounce_sending_updates()
  280. def _add_properties_to_pending_updates(self, properties):
  281. now = time()
  282. pending_updates = self._get_pending_updates()
  283. for key, value in properties.items():
  284. pending_updates[key] = {
  285. "value": value,
  286. "updated_at": now,
  287. "sent": False,
  288. }
  289. _LOGGER.debug(
  290. f"{self.name} new pending updates: {json.dumps(pending_updates, default=non_json)}",
  291. )
  292. async def _debounce_sending_updates(self):
  293. now = time()
  294. since = now - self._last_connection
  295. # set this now to avoid a race condition, it will be updated later
  296. # when the data is actally sent
  297. self._last_connection = now
  298. # Only delay a second if there was recently another command.
  299. # Otherwise delay 1ms, to keep things simple by reusing the
  300. # same send mechanism.
  301. waittime = 1 if since < 1.1 else 0.001
  302. await asyncio.sleep(waittime)
  303. await self._send_pending_updates()
  304. async def _send_pending_updates(self):
  305. pending_properties = self._get_unsent_properties()
  306. payload = self._api.generate_payload(
  307. tinytuya.CONTROL,
  308. pending_properties,
  309. )
  310. _LOGGER.debug(
  311. f"{self.name} sending dps update: {json.dumps(pending_properties, default=non_json)}"
  312. )
  313. await self._retry_on_failed_connection(
  314. lambda: self._send_payload(payload),
  315. "Failed to update device state.",
  316. )
  317. def _send_payload(self, payload):
  318. try:
  319. self._lock.acquire()
  320. self._api.send(payload)
  321. self._cached_state["updated_at"] = 0
  322. now = time()
  323. self._last_connection = now
  324. pending_updates = self._get_pending_updates()
  325. for key in list(pending_updates):
  326. pending_updates[key]["updated_at"] = now
  327. pending_updates[key]["sent"] = True
  328. finally:
  329. self._lock.release()
  330. async def _retry_on_failed_connection(self, func, error_message):
  331. if self._api_protocol_version_index is None:
  332. await self._rotate_api_protocol_version()
  333. auto = (self._protocol_configured == "auto") and (
  334. not self._api_protocol_working
  335. )
  336. connections = (
  337. self._AUTO_CONNECTION_ATTEMPTS
  338. if auto
  339. else self._SINGLE_PROTO_CONNECTION_ATTEMPTS
  340. )
  341. for i in range(connections):
  342. try:
  343. retval = await self._hass.async_add_executor_job(func)
  344. if type(retval) is dict and "Error" in retval:
  345. raise AttributeError
  346. self._api_protocol_working = True
  347. return retval
  348. except Exception as e:
  349. _LOGGER.debug(
  350. f"Retrying after exception {e} ({i}/{connections})",
  351. )
  352. if i + 1 == connections:
  353. self._reset_cached_state()
  354. self._api_protocol_working = False
  355. for entity in self._children:
  356. entity.async_schedule_update_ha_state()
  357. _LOGGER.error(error_message)
  358. if not self._api_protocol_working:
  359. await self._rotate_api_protocol_version()
  360. def _get_cached_state(self):
  361. cached_state = self._cached_state.copy()
  362. return {**cached_state, **self._get_pending_properties()}
  363. def _get_pending_properties(self):
  364. return {
  365. key: property["value"]
  366. for key, property in self._get_pending_updates().items()
  367. }
  368. def _get_unsent_properties(self):
  369. return {
  370. key: info["value"]
  371. for key, info in self._get_pending_updates().items()
  372. if not info["sent"]
  373. }
  374. def _get_pending_updates(self):
  375. now = time()
  376. self._pending_updates = {
  377. key: value
  378. for key, value in self._pending_updates.items()
  379. if now - value["updated_at"] < self._FAKE_IT_TIMEOUT
  380. }
  381. return self._pending_updates
  382. async def _rotate_api_protocol_version(self):
  383. if self._api_protocol_version_index is None:
  384. try:
  385. self._api_protocol_version_index = API_PROTOCOL_VERSIONS.index(
  386. self._protocol_configured
  387. )
  388. except ValueError:
  389. self._api_protocol_version_index = 0
  390. # only rotate if configured as auto
  391. elif self._protocol_configured == "auto":
  392. self._api_protocol_version_index += 1
  393. if self._api_protocol_version_index >= len(API_PROTOCOL_VERSIONS):
  394. self._api_protocol_version_index = 0
  395. new_version = API_PROTOCOL_VERSIONS[self._api_protocol_version_index]
  396. _LOGGER.info(
  397. f"Setting protocol version for {self.name} to {new_version}.",
  398. )
  399. await self._hass.async_add_executor_job(
  400. self._api.set_version,
  401. new_version,
  402. )
  403. @staticmethod
  404. def get_key_for_value(obj, value, fallback=None):
  405. keys = list(obj.keys())
  406. values = list(obj.values())
  407. return keys[values.index(value)] if value in values else fallback
  408. def setup_device(hass: HomeAssistant, config: dict):
  409. """Setup a tuya device based on passed in config."""
  410. _LOGGER.info(f"Creating device: {config[CONF_DEVICE_ID]}")
  411. hass.data[DOMAIN] = hass.data.get(DOMAIN, {})
  412. device = TuyaLocalDevice(
  413. config[CONF_NAME],
  414. config[CONF_DEVICE_ID],
  415. config[CONF_HOST],
  416. config[CONF_LOCAL_KEY],
  417. config[CONF_PROTOCOL_VERSION],
  418. hass,
  419. )
  420. hass.data[DOMAIN][config[CONF_DEVICE_ID]] = {"device": device}
  421. return device
  422. async def async_delete_device(hass: HomeAssistant, config: dict):
  423. _LOGGER.info(f"Deleting device: {config[CONF_DEVICE_ID]}")
  424. await hass.data[DOMAIN][config[CONF_DEVICE_ID]]["device"].async_stop()
  425. del hass.data[DOMAIN][config[CONF_DEVICE_ID]]["device"]