fan.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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 .helpers.config import async_tuya_setup_platform
  13. from .helpers.device_config import TuyaEntityConfig
  14. from .helpers.mixin import TuyaLocalEntity
  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. # Until the deprecation period ends (eexpected 2025.2)
  54. self._enable_turn_on_off_backwards_compatibility = False
  55. @property
  56. def supported_features(self):
  57. """Return the features supported by this climate device."""
  58. return self._support_flags
  59. @property
  60. def is_on(self):
  61. """Return whether the switch is on or not."""
  62. # If there is no switch, it is always on
  63. if self._switch_dps is None:
  64. return self.available
  65. return self._switch_dps.get_value(self._device)
  66. async def async_turn_on(
  67. self,
  68. percentage: int | None = None,
  69. preset_mode: str | None = None,
  70. **kwargs: Any,
  71. ):
  72. """Turn the fan on, setting any other parameters given"""
  73. settings = {}
  74. if self._switch_dps:
  75. settings = {
  76. **settings,
  77. **self._switch_dps.get_values_to_set(self._device, True),
  78. }
  79. if percentage is not None and self._speed_dps:
  80. r = self._speed_dps.range(self._device)
  81. if r:
  82. percentage = percentage_to_ranged_value(r, percentage)
  83. settings = {
  84. **settings,
  85. **self._speed_dps.get_values_to_set(self._device, percentage),
  86. }
  87. if preset_mode and self._preset_dps:
  88. settings = {
  89. **settings,
  90. **self._preset_dps.get_values_to_set(self._device, preset_mode),
  91. }
  92. # TODO: potentially handle other kwargs.
  93. if settings:
  94. await self._device.async_set_properties(settings)
  95. async def async_turn_off(self, **kwargs):
  96. """Turn the switch off"""
  97. if self._switch_dps is None:
  98. raise NotImplementedError
  99. await self._switch_dps.async_set_value(self._device, False)
  100. @property
  101. def percentage(self):
  102. """Return the currently set percentage."""
  103. if self._speed_dps is None:
  104. return None
  105. r = self._speed_dps.range(self._device)
  106. val = self._speed_dps.get_value(self._device)
  107. if r and val is not None:
  108. val = ranged_value_to_percentage(r, val)
  109. return val
  110. @property
  111. def percentage_step(self):
  112. """Return the step for percentage."""
  113. if self._speed_dps is None:
  114. return None
  115. if self._speed_dps.values(self._device):
  116. return 100 / len(self._speed_dps.values(self._device))
  117. r = self._speed_dps.range(self._device)
  118. scale = 100 / r[1] if r else 1.0
  119. return self._speed_dps.step(self._device) * scale
  120. @property
  121. def speed_count(self):
  122. """Return the number of speeds supported by the fan."""
  123. if self._speed_dps is None:
  124. return 0
  125. if self._speed_dps.values(self._device):
  126. return len(self._speed_dps.values(self._device))
  127. return int(round(100 / self.percentage_step))
  128. async def async_set_percentage(self, percentage):
  129. """Set the fan speed as a percentage."""
  130. # If speed is 0, turn the fan off
  131. if percentage == 0 and self._switch_dps:
  132. return await self.async_turn_off()
  133. if self._speed_dps is None:
  134. return None
  135. # If there is a fixed list of values, snap to the closest one
  136. if self._speed_dps.values(self._device):
  137. percentage = min(
  138. self._speed_dps.values(self._device),
  139. key=lambda x: abs(x - percentage),
  140. )
  141. elif self._speed_dps.range(self._device):
  142. r = self._speed_dps.range(self._device)
  143. percentage = percentage_to_ranged_value(r, percentage)
  144. values_to_set = self._speed_dps.get_values_to_set(self._device, percentage)
  145. if not self.is_on and self._switch_dps:
  146. values_to_set.update(self._switch_dps.get_values_to_set(self._device, True))
  147. await self._device.async_set_properties(values_to_set)
  148. @property
  149. def preset_mode(self):
  150. """Return the current preset mode."""
  151. if self._preset_dps:
  152. return self._preset_dps.get_value(self._device)
  153. @property
  154. def preset_modes(self):
  155. """Return the list of presets that this device supports."""
  156. if self._preset_dps is None:
  157. return []
  158. return self._preset_dps.values(self._device)
  159. async def async_set_preset_mode(self, preset_mode):
  160. """Set the preset mode."""
  161. if self._preset_dps is None:
  162. raise NotImplementedError()
  163. await self._preset_dps.async_set_value(self._device, preset_mode)
  164. @property
  165. def current_direction(self):
  166. """Return the current direction [forward or reverse]."""
  167. if self._direction_dps:
  168. return self._direction_dps.get_value(self._device)
  169. async def async_set_direction(self, direction):
  170. """Set the direction of the fan."""
  171. if self._direction_dps is None:
  172. raise NotImplementedError()
  173. await self._direction_dps.async_set_value(self._device, direction)
  174. @property
  175. def oscillating(self):
  176. """Return whether or not the fan is oscillating."""
  177. if self._oscillate_dps:
  178. return self._oscillate_dps.get_value(self._device)
  179. async def async_oscillate(self, oscillating):
  180. """Oscillate the fan."""
  181. if self._oscillate_dps is None:
  182. raise NotImplementedError()
  183. await self._oscillate_dps.async_set_value(self._device, oscillating)