device.py 8.1 KB

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