fan.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. """
  2. Setup for different kinds of Tuya fan devices
  3. """
  4. import logging
  5. from typing import Any
  6. from homeassistant.components.fan import FanEntity, FanEntityFeature
  7. from homeassistant.util.percentage import (
  8. percentage_to_ranged_value,
  9. ranged_value_to_percentage,
  10. )
  11. from .device import TuyaLocalDevice
  12. from .entity import TuyaLocalEntity
  13. from .helpers.config import async_tuya_setup_platform
  14. from .helpers.device_config import TuyaEntityConfig
  15. _LOGGER = logging.getLogger(__name__)
  16. async def async_setup_entry(hass, config_entry, async_add_entities):
  17. config = {**config_entry.data, **config_entry.options}
  18. await async_tuya_setup_platform(
  19. hass,
  20. async_add_entities,
  21. config,
  22. "fan",
  23. TuyaLocalFan,
  24. )
  25. class TuyaLocalFan(TuyaLocalEntity, FanEntity):
  26. """Representation of a Tuya Fan entity."""
  27. def __init__(self, device: TuyaLocalDevice, config: TuyaEntityConfig):
  28. """
  29. Initialise the fan device.
  30. Args:
  31. device (TuyaLocalDevice): The device API instance.
  32. config (TuyaEntityConfig): The entity config.
  33. """
  34. super().__init__()
  35. dps_map = self._init_begin(device, config)
  36. self._switch_dps = dps_map.pop("switch", None)
  37. self._preset_dps = dps_map.pop("preset_mode", None)
  38. self._speed_dps = dps_map.pop("speed", None)
  39. self._oscillate_dps = dps_map.pop("oscillate", None)
  40. self._direction_dps = dps_map.pop("direction", None)
  41. self._init_end(dps_map)
  42. self._support_flags = FanEntityFeature(0)
  43. if self._preset_dps:
  44. self._support_flags |= FanEntityFeature.PRESET_MODE
  45. if self._speed_dps:
  46. self._support_flags |= FanEntityFeature.SET_SPEED
  47. if self._oscillate_dps:
  48. self._support_flags |= FanEntityFeature.OSCILLATE
  49. if self._direction_dps:
  50. self._support_flags |= FanEntityFeature.DIRECTION
  51. if self._switch_dps:
  52. self._support_flags |= FanEntityFeature.TURN_ON | FanEntityFeature.TURN_OFF
  53. elif self._speed_dps:
  54. r = self._speed_dps.range(self._device)
  55. if r and r[0] == 0:
  56. self._support_flags |= FanEntityFeature.TURN_OFF
  57. # Until the deprecation period ends (expected 2025.2)
  58. self._enable_turn_on_off_backwards_compatibility = False
  59. @property
  60. def supported_features(self):
  61. """Return the features supported by this climate device."""
  62. return self._support_flags
  63. @property
  64. def is_on(self):
  65. """Return whether the switch is on or not."""
  66. # If there is no switch, it is always on
  67. if self._switch_dps is None:
  68. return self.available
  69. return self._switch_dps.get_value(self._device)
  70. async def async_turn_on(
  71. self,
  72. percentage: int | None = None,
  73. preset_mode: str | None = None,
  74. **kwargs: Any,
  75. ):
  76. """Turn the fan on, setting any other parameters given"""
  77. settings = {}
  78. if self._switch_dps:
  79. settings = {
  80. **settings,
  81. **self._switch_dps.get_values_to_set(self._device, True),
  82. }
  83. if percentage is not None and self._speed_dps:
  84. r = self._speed_dps.range(self._device)
  85. if r:
  86. if r[0] == 0:
  87. r = (1, r[1])
  88. percentage = percentage_to_ranged_value(r, percentage)
  89. settings = {
  90. **settings,
  91. **self._speed_dps.get_values_to_set(self._device, percentage),
  92. }
  93. if preset_mode and self._preset_dps:
  94. settings = {
  95. **settings,
  96. **self._preset_dps.get_values_to_set(self._device, preset_mode),
  97. }
  98. # TODO: potentially handle other kwargs.
  99. if settings:
  100. await self._device.async_set_properties(settings)
  101. async def async_turn_off(self, **kwargs):
  102. """Turn the switch off"""
  103. if self._switch_dps:
  104. await self._switch_dps.async_set_value(self._device, False)
  105. elif (
  106. self._speed_dps
  107. and self._speed_dps.range(self._device)
  108. and self._speed_dps.range(self._device)[0] == 0
  109. ):
  110. await self._speed_dps.async_set_value(self._device, 0)
  111. else:
  112. raise NotImplementedError
  113. @property
  114. def percentage(self):
  115. """Return the currently set percentage."""
  116. if self._speed_dps is None:
  117. return None
  118. r = self._speed_dps.range(self._device)
  119. val = self._speed_dps.get_value(self._device)
  120. if r and val is not None:
  121. if r[0] == 0:
  122. r = (1, r[1])
  123. val = ranged_value_to_percentage(r, val)
  124. return val
  125. @property
  126. def percentage_step(self):
  127. """Return the step for percentage."""
  128. if self._speed_dps is None:
  129. return None
  130. if self._speed_dps.values(self._device):
  131. return 100 / len(self._speed_dps.values(self._device))
  132. r = self._speed_dps.range(self._device)
  133. scale = 100 / r[1] if r else 1.0
  134. return self._speed_dps.step(self._device) * scale
  135. @property
  136. def speed_count(self):
  137. """Return the number of speeds supported by the fan."""
  138. if self._speed_dps is None:
  139. return 0
  140. if self._speed_dps.values(self._device):
  141. return len(self._speed_dps.values(self._device))
  142. return int(round(100 / self.percentage_step))
  143. async def async_set_percentage(self, percentage):
  144. """Set the fan speed as a percentage."""
  145. # If speed is 0, turn the fan off
  146. if percentage == 0 and self._switch_dps:
  147. return await self.async_turn_off()
  148. if self._speed_dps is None:
  149. return None
  150. # If there is a fixed list of values, snap to the closest one
  151. if self._speed_dps.values(self._device):
  152. percentage = min(
  153. self._speed_dps.values(self._device),
  154. key=lambda x: abs(x - percentage),
  155. )
  156. elif self._speed_dps.range(self._device):
  157. r = self._speed_dps.range(self._device)
  158. if r[0] == 0:
  159. r = (1, r[1])
  160. percentage = percentage_to_ranged_value(r, percentage)
  161. values_to_set = self._speed_dps.get_values_to_set(self._device, percentage)
  162. if not self.is_on and self._switch_dps:
  163. values_to_set.update(self._switch_dps.get_values_to_set(self._device, True))
  164. await self._device.async_set_properties(values_to_set)
  165. @property
  166. def preset_mode(self):
  167. """Return the current preset mode."""
  168. if self._preset_dps:
  169. return self._preset_dps.get_value(self._device)
  170. @property
  171. def preset_modes(self):
  172. """Return the list of presets that this device supports."""
  173. if self._preset_dps is None:
  174. return []
  175. return self._preset_dps.values(self._device)
  176. async def async_set_preset_mode(self, preset_mode):
  177. """Set the preset mode."""
  178. if self._preset_dps is None:
  179. raise NotImplementedError()
  180. await self._preset_dps.async_set_value(self._device, preset_mode)
  181. @property
  182. def current_direction(self):
  183. """Return the current direction [forward or reverse]."""
  184. if self._direction_dps:
  185. return self._direction_dps.get_value(self._device)
  186. async def async_set_direction(self, direction):
  187. """Set the direction of the fan."""
  188. if self._direction_dps is None:
  189. raise NotImplementedError()
  190. await self._direction_dps.async_set_value(self._device, direction)
  191. @property
  192. def oscillating(self):
  193. """Return whether or not the fan is oscillating."""
  194. if self._oscillate_dps:
  195. return self._oscillate_dps.get_value(self._device)
  196. async def async_oscillate(self, oscillating):
  197. """Oscillate the fan."""
  198. if self._oscillate_dps is None:
  199. raise NotImplementedError()
  200. await self._oscillate_dps.async_set_value(self._device, oscillating)