device.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. """
  2. API for Tuya Local devices.
  3. """
  4. import json
  5. import logging
  6. from threading import Lock, Timer
  7. from time import time, sleep
  8. from homeassistant.const import TEMP_CELSIUS
  9. from homeassistant.core import HomeAssistant
  10. from .const import (
  11. DOMAIN,
  12. API_PROTOCOL_VERSIONS,
  13. CONF_TYPE_DEHUMIDIFIER,
  14. CONF_TYPE_FAN,
  15. CONF_TYPE_GECO_HEATER,
  16. CONF_TYPE_GPCV_HEATER,
  17. CONF_TYPE_GPPH_HEATER,
  18. CONF_TYPE_KOGAN_HEATER,
  19. )
  20. _LOGGER = logging.getLogger(__name__)
  21. class TuyaLocalDevice(object):
  22. def __init__(self, name, dev_id, address, local_key, hass: HomeAssistant):
  23. """
  24. Represents a Tuya-based device.
  25. Args:
  26. dev_id (str): The device id.
  27. address (str): The network address.
  28. local_key (str): The encryption key.
  29. """
  30. import pytuya
  31. self._name = name
  32. self._api_protocol_version_index = None
  33. self._api = pytuya.Device(dev_id, address, local_key, "device")
  34. self._refresh_task = None
  35. self._rotate_api_protocol_version()
  36. self._fixed_properties = {}
  37. self._reset_cached_state()
  38. self._TEMPERATURE_UNIT = TEMP_CELSIUS
  39. self._hass = hass
  40. # API calls to update Tuya devices are asynchronous and non-blocking. This means
  41. # you can send a change and immediately request an updated state (like HA does),
  42. # but because it has not yet finished processing you will be returned the old state.
  43. # The solution is to keep a temporary list of changed properties that we can overlay
  44. # onto the state while we wait for the board to update its switches.
  45. self._FAKE_IT_TIL_YOU_MAKE_IT_TIMEOUT = 10
  46. self._CACHE_TIMEOUT = 20
  47. self._CONNECTION_ATTEMPTS = 4
  48. self._lock = Lock()
  49. @property
  50. def name(self):
  51. return self._name
  52. @property
  53. def unique_id(self):
  54. """Return the unique id for this device (the dev_id)."""
  55. return self._api.id
  56. @property
  57. def device_info(self):
  58. """Return the device information for this device."""
  59. return {
  60. "identifiers": {(DOMAIN, self.unique_id)},
  61. "name": self.name,
  62. "manufacturer": "Tuya",
  63. }
  64. @property
  65. def temperature_unit(self):
  66. return self._TEMPERATURE_UNIT
  67. async def async_inferred_type(self):
  68. cached_state = self._get_cached_state()
  69. if "1" not in cached_state and "3" not in cached_state:
  70. await self.async_refresh()
  71. cached_state = self._get_cached_state()
  72. _LOGGER.debug(f"Inferring device type from cached state: {cached_state}")
  73. if "1" not in cached_state:
  74. return CONF_TYPE_KOGAN_HEATER
  75. if "5" in cached_state and "3" not in cached_state:
  76. return CONF_TYPE_DEHUMIDIFIER
  77. if "8" in cached_state:
  78. return CONF_TYPE_FAN
  79. if "106" in cached_state:
  80. return CONF_TYPE_GPPH_HEATER
  81. if "7" in cached_state:
  82. return CONF_TYPE_GPCV_HEATER
  83. if "3" in cached_state:
  84. return CONF_TYPE_GECO_HEATER
  85. return None
  86. def set_fixed_properties(self, fixed_properties):
  87. self._fixed_properties = fixed_properties
  88. set_fixed_properties = Timer(
  89. 10, lambda: self._set_properties(self._fixed_properties)
  90. )
  91. set_fixed_properties.start()
  92. async def async_refresh(self):
  93. last_updated = self._get_cached_state()["updated_at"]
  94. if self._refresh_task is None or time() - last_updated >= self._CACHE_TIMEOUT:
  95. self._cached_state["updated_at"] = time()
  96. self._refresh_task = self._hass.async_add_executor_job(self.refresh)
  97. await self._refresh_task
  98. def refresh(self):
  99. _LOGGER.debug(f"Refreshing device state for {self.name}.")
  100. self._retry_on_failed_connection(
  101. lambda: self._refresh_cached_state(),
  102. f"Failed to refresh device state for {self.name}.",
  103. )
  104. def get_property(self, dps_id):
  105. cached_state = self._get_cached_state()
  106. if dps_id in cached_state:
  107. return cached_state[dps_id]
  108. else:
  109. return None
  110. def set_property(self, dps_id, value):
  111. self._set_properties({dps_id: value})
  112. async def async_set_property(self, dps_id, value):
  113. await self._hass.async_add_executor_job(self.set_property, dps_id, value)
  114. def anticipate_property_value(self, dps_id, value):
  115. """
  116. Update a value in the cached state only. This is good for when you know the device will reflect a new state in
  117. the next update, but don't want to wait for that update for the device to represent this state.
  118. The anticipated value will be cleared with the next update.
  119. """
  120. self._cached_state[dps_id] = value
  121. def _reset_cached_state(self):
  122. self._cached_state = {"updated_at": 0}
  123. self._pending_updates = {}
  124. def _refresh_cached_state(self):
  125. new_state = self._api.status()
  126. self._cached_state = new_state["dps"]
  127. self._cached_state["updated_at"] = time()
  128. _LOGGER.info(f"refreshed device state: {json.dumps(new_state)}")
  129. _LOGGER.debug(
  130. f"new cache state (including pending properties): {json.dumps(self._get_cached_state())}"
  131. )
  132. def _set_properties(self, properties):
  133. if len(properties) == 0:
  134. return
  135. self._add_properties_to_pending_updates(properties)
  136. self._debounce_sending_updates()
  137. def _add_properties_to_pending_updates(self, properties):
  138. now = time()
  139. properties = {**properties, **self._fixed_properties}
  140. pending_updates = self._get_pending_updates()
  141. for key, value in properties.items():
  142. pending_updates[key] = {"value": value, "updated_at": now}
  143. _LOGGER.debug(f"new pending updates: {json.dumps(self._pending_updates)}")
  144. def _debounce_sending_updates(self):
  145. try:
  146. self._debounce.cancel()
  147. except AttributeError:
  148. pass
  149. self._debounce = Timer(1, self._send_pending_updates)
  150. self._debounce.start()
  151. def _send_pending_updates(self):
  152. pending_properties = self._get_pending_properties()
  153. payload = self._api.generate_payload("set", pending_properties)
  154. _LOGGER.info(f"sending dps update: {json.dumps(pending_properties)}")
  155. self._retry_on_failed_connection(
  156. lambda: self._send_payload(payload), "Failed to update device state."
  157. )
  158. def _send_payload(self, payload):
  159. try:
  160. self._lock.acquire()
  161. self._api._send_receive(payload)
  162. self._cached_state["updated_at"] = 0
  163. now = time()
  164. pending_updates = self._get_pending_updates()
  165. for key, value in pending_updates.items():
  166. pending_updates[key]["updated_at"] = now
  167. finally:
  168. self._lock.release()
  169. def _retry_on_failed_connection(self, func, error_message):
  170. for i in range(self._CONNECTION_ATTEMPTS):
  171. try:
  172. func()
  173. break
  174. except Exception as e:
  175. _LOGGER.debug(f"Retrying after exception {e}")
  176. if i + 1 == self._CONNECTION_ATTEMPTS:
  177. self._reset_cached_state()
  178. _LOGGER.error(error_message)
  179. else:
  180. self._rotate_api_protocol_version()
  181. def _get_cached_state(self):
  182. cached_state = self._cached_state.copy()
  183. return {**cached_state, **self._get_pending_properties()}
  184. def _get_pending_properties(self):
  185. return {key: info["value"] for key, info in self._get_pending_updates().items()}
  186. def _get_pending_updates(self):
  187. now = time()
  188. self._pending_updates = {
  189. key: value
  190. for key, value in self._pending_updates.items()
  191. if now - value["updated_at"] < self._FAKE_IT_TIL_YOU_MAKE_IT_TIMEOUT
  192. }
  193. return self._pending_updates
  194. def _rotate_api_protocol_version(self):
  195. if self._api_protocol_version_index is None:
  196. self._api_protocol_version_index = 0
  197. else:
  198. self._api_protocol_version_index += 1
  199. if self._api_protocol_version_index >= len(API_PROTOCOL_VERSIONS):
  200. self._api_protocol_version_index = 0
  201. new_version = API_PROTOCOL_VERSIONS[self._api_protocol_version_index]
  202. _LOGGER.info(f"Setting protocol version for {self.name} to {new_version}.")
  203. self._api.set_version(new_version)
  204. @staticmethod
  205. def get_key_for_value(obj, value, fallback=None):
  206. keys = list(obj.keys())
  207. values = list(obj.values())
  208. return keys[values.index(value)] or fallback