device.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. 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. return CONF_TYPE_KOGAN_HEATER
  76. if "5" in cached_state and "3" not in cached_state and "103" in cached_state:
  77. return CONF_TYPE_DEHUMIDIFIER
  78. if "8" in cached_state:
  79. return CONF_TYPE_FAN
  80. if "5" in cached_state and "3" not in cached_state:
  81. return CONF_TYPE_KOGAN_SWITCH
  82. if "106" in cached_state:
  83. return CONF_TYPE_GPPH_HEATER
  84. if "7" in cached_state:
  85. return CONF_TYPE_GPCV_HEATER
  86. if "3" in cached_state:
  87. return CONF_TYPE_GECO_HEATER
  88. return None
  89. def set_fixed_properties(self, fixed_properties):
  90. self._fixed_properties = fixed_properties
  91. set_fixed_properties = Timer(
  92. 10, lambda: self._set_properties(self._fixed_properties)
  93. )
  94. set_fixed_properties.start()
  95. async def async_refresh(self):
  96. last_updated = self._get_cached_state()["updated_at"]
  97. if self._refresh_task is None or time() - last_updated >= self._CACHE_TIMEOUT:
  98. self._cached_state["updated_at"] = time()
  99. self._refresh_task = self._hass.async_add_executor_job(self.refresh)
  100. await self._refresh_task
  101. def refresh(self):
  102. _LOGGER.debug(f"Refreshing device state for {self.name}.")
  103. self._retry_on_failed_connection(
  104. lambda: self._refresh_cached_state(),
  105. f"Failed to refresh device state for {self.name}.",
  106. )
  107. def get_property(self, dps_id):
  108. cached_state = self._get_cached_state()
  109. if dps_id in cached_state:
  110. return cached_state[dps_id]
  111. else:
  112. return None
  113. def set_property(self, dps_id, value):
  114. self._set_properties({dps_id: value})
  115. async def async_set_property(self, dps_id, value):
  116. await self._hass.async_add_executor_job(self.set_property, dps_id, value)
  117. def anticipate_property_value(self, dps_id, value):
  118. """
  119. Update a value in the cached state only. This is good for when you know the device will reflect a new state in
  120. the next update, but don't want to wait for that update for the device to represent this state.
  121. The anticipated value will be cleared with the next update.
  122. """
  123. self._cached_state[dps_id] = value
  124. def _reset_cached_state(self):
  125. self._cached_state = {"updated_at": 0}
  126. self._pending_updates = {}
  127. def _refresh_cached_state(self):
  128. new_state = self._api.status()
  129. self._cached_state = new_state["dps"]
  130. self._cached_state["updated_at"] = time()
  131. _LOGGER.info(f"refreshed device state: {json.dumps(new_state)}")
  132. _LOGGER.debug(
  133. f"new cache state (including pending properties): {json.dumps(self._get_cached_state())}"
  134. )
  135. def _set_properties(self, properties):
  136. if len(properties) == 0:
  137. return
  138. self._add_properties_to_pending_updates(properties)
  139. self._debounce_sending_updates()
  140. def _add_properties_to_pending_updates(self, properties):
  141. now = time()
  142. properties = {**properties, **self._fixed_properties}
  143. pending_updates = self._get_pending_updates()
  144. for key, value in properties.items():
  145. pending_updates[key] = {"value": value, "updated_at": now}
  146. _LOGGER.debug(f"new pending updates: {json.dumps(self._pending_updates)}")
  147. def _debounce_sending_updates(self):
  148. try:
  149. self._debounce.cancel()
  150. except AttributeError:
  151. pass
  152. self._debounce = Timer(1, self._send_pending_updates)
  153. self._debounce.start()
  154. def _send_pending_updates(self):
  155. pending_properties = self._get_pending_properties()
  156. payload = self._api.generate_payload("set", pending_properties)
  157. _LOGGER.info(f"sending dps update: {json.dumps(pending_properties)}")
  158. self._retry_on_failed_connection(
  159. lambda: self._send_payload(payload), "Failed to update device state."
  160. )
  161. def _send_payload(self, payload):
  162. try:
  163. self._lock.acquire()
  164. self._api._send_receive(payload)
  165. self._cached_state["updated_at"] = 0
  166. now = time()
  167. pending_updates = self._get_pending_updates()
  168. for key, value in pending_updates.items():
  169. pending_updates[key]["updated_at"] = now
  170. finally:
  171. self._lock.release()
  172. def _retry_on_failed_connection(self, func, error_message):
  173. for i in range(self._CONNECTION_ATTEMPTS):
  174. try:
  175. func()
  176. break
  177. except Exception as e:
  178. _LOGGER.debug(f"Retrying after exception {e}")
  179. if i + 1 == self._CONNECTION_ATTEMPTS:
  180. self._reset_cached_state()
  181. _LOGGER.error(error_message)
  182. else:
  183. self._rotate_api_protocol_version()
  184. def _get_cached_state(self):
  185. cached_state = self._cached_state.copy()
  186. return {**cached_state, **self._get_pending_properties()}
  187. def _get_pending_properties(self):
  188. return {key: info["value"] for key, info in self._get_pending_updates().items()}
  189. def _get_pending_updates(self):
  190. now = time()
  191. self._pending_updates = {
  192. key: value
  193. for key, value in self._pending_updates.items()
  194. if now - value["updated_at"] < self._FAKE_IT_TIL_YOU_MAKE_IT_TIMEOUT
  195. }
  196. return self._pending_updates
  197. def _rotate_api_protocol_version(self):
  198. if self._api_protocol_version_index is None:
  199. self._api_protocol_version_index = 0
  200. else:
  201. self._api_protocol_version_index += 1
  202. if self._api_protocol_version_index >= len(API_PROTOCOL_VERSIONS):
  203. self._api_protocol_version_index = 0
  204. new_version = API_PROTOCOL_VERSIONS[self._api_protocol_version_index]
  205. _LOGGER.info(f"Setting protocol version for {self.name} to {new_version}.")
  206. self._api.set_version(new_version)
  207. @staticmethod
  208. def get_key_for_value(obj, value, fallback=None):
  209. keys = list(obj.keys())
  210. values = list(obj.values())
  211. return keys[values.index(value)] or fallback