__init__.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. """
  2. Platform for Goldair WiFi-connected heaters and panels.
  3. Based on sean6541/tuya-homeassistant for service call logic, and TarxBoy's
  4. investigation into Goldair's tuyapi statuses
  5. https://github.com/codetheweb/tuyapi/issues/31.
  6. """
  7. from time import time
  8. from threading import Timer, Lock
  9. import logging
  10. import json
  11. import voluptuous as vol
  12. import homeassistant.helpers.config_validation as cv
  13. from homeassistant.const import (CONF_NAME, CONF_HOST, TEMP_CELSIUS)
  14. from homeassistant.helpers.discovery import load_platform
  15. VERSION = '0.0.6'
  16. _LOGGER = logging.getLogger(__name__)
  17. DOMAIN = 'goldair_climate'
  18. DATA_GOLDAIR_CLIMATE = 'data_goldair_climate'
  19. CONF_DEVICE_ID = 'device_id'
  20. CONF_LOCAL_KEY = 'local_key'
  21. CONF_TYPE = 'type'
  22. CONF_TYPE_HEATER = 'heater'
  23. CONF_TYPE_DEHUMIDIFIER = 'dehumidifier'
  24. CONF_CLIMATE = 'climate'
  25. CONF_DISPLAY_LIGHT = 'display_light'
  26. CONF_CHILD_LOCK = 'child_lock'
  27. PLATFORM_SCHEMA = vol.Schema({
  28. vol.Required(CONF_NAME): cv.string,
  29. vol.Required(CONF_HOST): cv.string,
  30. vol.Required(CONF_DEVICE_ID): cv.string,
  31. vol.Required(CONF_LOCAL_KEY): cv.string,
  32. vol.Required(CONF_TYPE): vol.In([CONF_TYPE_HEATER, CONF_TYPE_DEHUMIDIFIER]),
  33. vol.Optional(CONF_CLIMATE, default=True): cv.boolean,
  34. vol.Optional(CONF_DISPLAY_LIGHT, default=False): cv.boolean,
  35. vol.Optional(CONF_CHILD_LOCK, default=False): cv.boolean,
  36. })
  37. CONFIG_SCHEMA = vol.Schema({
  38. DOMAIN: vol.All(cv.ensure_list, [PLATFORM_SCHEMA])
  39. }, extra=vol.ALLOW_EXTRA)
  40. def setup(hass, config):
  41. hass.data[DOMAIN] = {}
  42. for device_config in config.get(DOMAIN, []):
  43. host = device_config.get(CONF_HOST)
  44. device = GoldairTuyaDevice(
  45. device_config.get(CONF_NAME),
  46. device_config.get(CONF_DEVICE_ID),
  47. device_config.get(CONF_HOST),
  48. device_config.get(CONF_LOCAL_KEY)
  49. )
  50. hass.data[DOMAIN][host] = device
  51. discovery_info = {CONF_HOST: host, CONF_TYPE: device_config.get(CONF_TYPE)}
  52. if device_config.get(CONF_CLIMATE) == True:
  53. load_platform(hass, 'climate', DOMAIN, discovery_info, config)
  54. if device_config.get(CONF_DISPLAY_LIGHT) == True:
  55. load_platform(hass, 'light', DOMAIN, discovery_info, config)
  56. if device_config.get(CONF_CHILD_LOCK) == True:
  57. load_platform(hass, 'lock', DOMAIN, discovery_info, config)
  58. return True
  59. class GoldairTuyaDevice(object):
  60. def __init__(self, name, dev_id, address, local_key):
  61. """
  62. Represents a Goldair Tuya-based device.
  63. Args:
  64. dev_id (str): The device id.
  65. address (str): The network address.
  66. local_key (str): The encryption key.
  67. """
  68. import pytuya
  69. self._name = name
  70. self._api = pytuya.Device(dev_id, address, local_key, 'device')
  71. self._fixed_properties = {}
  72. self._reset_cached_state()
  73. self._TEMPERATURE_UNIT = TEMP_CELSIUS
  74. # API calls to update Goldair heaters are asynchronous and non-blocking. This means
  75. # you can send a change and immediately request an updated state (like HA does),
  76. # but because it has not yet finished processing you will be returned the old state.
  77. # The solution is to keep a temporary list of changed properties that we can overlay
  78. # onto the state while we wait for the board to update its switches.
  79. self._FAKE_IT_TIL_YOU_MAKE_IT_TIMEOUT = 10
  80. self._CACHE_TIMEOUT = 20
  81. self._CONNECTION_ATTEMPTS = 2
  82. self._lock = Lock()
  83. @property
  84. def name(self):
  85. return self._name
  86. @property
  87. def temperature_unit(self):
  88. return self._TEMPERATURE_UNIT
  89. def set_fixed_properties(self, fixed_properties):
  90. self._fixed_properties = fixed_properties
  91. set_fixed_properties = Timer(10, lambda: self._set_properties(self._fixed_properties))
  92. set_fixed_properties.start()
  93. def refresh(self):
  94. now = time()
  95. cached_state = self._get_cached_state()
  96. if now - cached_state['updated_at'] >= self._CACHE_TIMEOUT:
  97. self._cached_state['updated_at'] = time()
  98. self._retry_on_failed_connection(lambda: self._refresh_cached_state(), 'Failed to refresh device state.')
  99. def get_property(self, dps_id):
  100. cached_state = self._get_cached_state()
  101. if dps_id in cached_state:
  102. return cached_state[dps_id]
  103. else:
  104. return None
  105. def set_property(self, dps_id, value):
  106. self._set_properties({dps_id: value})
  107. def anticipate_property_value(self, dps_id, value):
  108. """
  109. Update a value in the cached state only. This is good for when you know the device will reflect a new state in
  110. the next update, but don't want to wait for that update for the device to represent this state.
  111. The anticipated value will be cleared with the next update.
  112. """
  113. self._cached_state[dps_id] = value
  114. def _reset_cached_state(self):
  115. self._cached_state = {
  116. 'updated_at': 0
  117. }
  118. self._pending_updates = {}
  119. def _refresh_cached_state(self):
  120. new_state = self._api.status()
  121. self._cached_state = new_state['dps']
  122. self._cached_state['updated_at'] = time()
  123. _LOGGER.info(f'refreshed device state: {json.dumps(new_state)}')
  124. _LOGGER.debug(f'new cache state (including pending properties): {json.dumps(self._get_cached_state())}')
  125. def _set_properties(self, properties):
  126. if len(properties) == 0:
  127. return
  128. self._add_properties_to_pending_updates(properties)
  129. self._debounce_sending_updates()
  130. def _add_properties_to_pending_updates(self, properties):
  131. now = time()
  132. properties = {**properties, **self._fixed_properties}
  133. pending_updates = self._get_pending_updates()
  134. for key, value in properties.items():
  135. pending_updates[key] = {
  136. 'value': value,
  137. 'updated_at': now
  138. }
  139. _LOGGER.debug(f'new pending updates: {json.dumps(self._pending_updates)}')
  140. def _debounce_sending_updates(self):
  141. try:
  142. self._debounce.cancel()
  143. except AttributeError:
  144. pass
  145. self._debounce = Timer(1, self._send_pending_updates)
  146. self._debounce.start()
  147. def _send_pending_updates(self):
  148. pending_properties = self._get_pending_properties()
  149. payload = self._api.generate_payload('set', pending_properties)
  150. _LOGGER.info(f'sending dps update: {json.dumps(pending_properties)}')
  151. self._retry_on_failed_connection(lambda: self._send_payload(payload), 'Failed to update device state.')
  152. def _send_payload(self, payload):
  153. try:
  154. self._lock.acquire()
  155. self._api._send_receive(payload)
  156. self._cached_state['updated_at'] = 0
  157. now = time()
  158. pending_updates = self._get_pending_updates()
  159. for key, value in pending_updates.items():
  160. pending_updates[key]['updated_at'] = now
  161. finally:
  162. self._lock.release()
  163. def _retry_on_failed_connection(self, func, error_message):
  164. for i in range(self._CONNECTION_ATTEMPTS):
  165. try:
  166. func()
  167. except:
  168. if i + 1 == self._CONNECTION_ATTEMPTS:
  169. self._reset_cached_state()
  170. _LOGGER.error(error_message)
  171. def _get_cached_state(self):
  172. cached_state = self._cached_state.copy()
  173. _LOGGER.debug(f'pending updates: {json.dumps(self._get_pending_updates())}')
  174. return {**cached_state, **self._get_pending_properties()}
  175. def _get_pending_properties(self):
  176. return {key: info['value'] for key, info in self._get_pending_updates().items()}
  177. def _get_pending_updates(self):
  178. now = time()
  179. self._pending_updates = {key: value for key, value in self._pending_updates.items()
  180. if now - value['updated_at'] < self._FAKE_IT_TIL_YOU_MAKE_IT_TIMEOUT}
  181. return self._pending_updates
  182. @staticmethod
  183. def get_key_for_value(obj, value):
  184. keys = list(obj.keys())
  185. values = list(obj.values())
  186. return keys[values.index(value)]