device.py 9.3 KB

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