device.py 9.7 KB

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