device.py 7.4 KB

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