fan.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. import asyncio
  2. import aiofiles
  3. import json
  4. import logging
  5. import os.path
  6. import voluptuous as vol
  7. from homeassistant.components.fan import (
  8. FanEntity, FanEntityFeature,
  9. PLATFORM_SCHEMA, DIRECTION_REVERSE, DIRECTION_FORWARD)
  10. from homeassistant.const import (
  11. CONF_NAME, STATE_OFF, STATE_ON, STATE_UNKNOWN)
  12. from homeassistant.core import callback
  13. from homeassistant.helpers.event import async_track_state_change
  14. import homeassistant.helpers.config_validation as cv
  15. from homeassistant.helpers.restore_state import RestoreEntity
  16. from homeassistant.util.percentage import (
  17. ordered_list_item_to_percentage,
  18. percentage_to_ordered_list_item
  19. )
  20. from . import COMPONENT_ABS_DIR, Helper
  21. from .controller import get_controller
  22. _LOGGER = logging.getLogger(__name__)
  23. DEFAULT_NAME = "SmartIR Fan"
  24. DEFAULT_DELAY = 0.5
  25. CONF_UNIQUE_ID = 'unique_id'
  26. CONF_DEVICE_CODE = 'device_code'
  27. CONF_CONTROLLER_DATA = "controller_data"
  28. CONF_DELAY = "delay"
  29. CONF_POWER_SENSOR = 'power_sensor'
  30. SPEED_OFF = "off"
  31. PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
  32. vol.Optional(CONF_UNIQUE_ID): cv.string,
  33. vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
  34. vol.Required(CONF_DEVICE_CODE): cv.positive_int,
  35. vol.Required(CONF_CONTROLLER_DATA): cv.string,
  36. vol.Optional(CONF_DELAY, default=DEFAULT_DELAY): cv.string,
  37. vol.Optional(CONF_POWER_SENSOR): cv.entity_id
  38. })
  39. async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
  40. """Set up the IR Fan platform."""
  41. device_code = config.get(CONF_DEVICE_CODE)
  42. device_files_subdir = os.path.join('codes', 'fan')
  43. device_files_absdir = os.path.join(COMPONENT_ABS_DIR, device_files_subdir)
  44. if not os.path.isdir(device_files_absdir):
  45. os.makedirs(device_files_absdir)
  46. device_json_filename = str(device_code) + '.json'
  47. device_json_path = os.path.join(device_files_absdir, device_json_filename)
  48. if not os.path.exists(device_json_path):
  49. _LOGGER.warning("Couldn't find the device Json file. The component will " \
  50. "try to download it from the GitHub repo.")
  51. try:
  52. codes_source = ("https://raw.githubusercontent.com/"
  53. "smartHomeHub/SmartIR/master/"
  54. "codes/fan/{}.json")
  55. await Helper.downloader(codes_source.format(device_code), device_json_path)
  56. except Exception:
  57. _LOGGER.error("There was an error while downloading the device Json file. " \
  58. "Please check your internet connection or if the device code " \
  59. "exists on GitHub. If the problem still exists please " \
  60. "place the file manually in the proper directory.")
  61. return
  62. try:
  63. async with aiofiles.open(device_json_path, mode='r') as j:
  64. _LOGGER.debug(f"loading json file {device_json_path}")
  65. content = await j.read()
  66. device_data = json.loads(content)
  67. _LOGGER.debug(f"{device_json_path} file loaded")
  68. except Exception:
  69. _LOGGER.error("The device JSON file is invalid")
  70. return
  71. async_add_entities([SmartIRFan(
  72. hass, config, device_data
  73. )])
  74. class SmartIRFan(FanEntity, RestoreEntity):
  75. def __init__(self, hass, config, device_data):
  76. self.hass = hass
  77. self._unique_id = config.get(CONF_UNIQUE_ID)
  78. self._name = config.get(CONF_NAME)
  79. self._device_code = config.get(CONF_DEVICE_CODE)
  80. self._controller_data = config.get(CONF_CONTROLLER_DATA)
  81. self._delay = config.get(CONF_DELAY)
  82. self._power_sensor = config.get(CONF_POWER_SENSOR)
  83. self._manufacturer = device_data['manufacturer']
  84. self._supported_models = device_data['supportedModels']
  85. self._supported_controller = device_data['supportedController']
  86. self._commands_encoding = device_data['commandsEncoding']
  87. self._speed_list = device_data['speed']
  88. self._commands = device_data['commands']
  89. self._speed = SPEED_OFF
  90. self._direction = None
  91. self._last_on_speed = None
  92. self._oscillating = None
  93. self._support_flags = FanEntityFeature.SET_SPEED
  94. if (DIRECTION_REVERSE in self._commands and \
  95. DIRECTION_FORWARD in self._commands):
  96. self._direction = DIRECTION_REVERSE
  97. self._support_flags = (
  98. self._support_flags | FanEntityFeature.DIRECTION)
  99. if ('oscillate' in self._commands):
  100. self._oscillating = False
  101. self._support_flags = (
  102. self._support_flags | FanEntityFeature.OSCILLATE)
  103. self._temp_lock = asyncio.Lock()
  104. self._on_by_remote = False
  105. #Init the IR/RF controller
  106. self._controller = get_controller(
  107. self.hass,
  108. self._supported_controller,
  109. self._commands_encoding,
  110. self._controller_data,
  111. self._delay)
  112. async def async_added_to_hass(self):
  113. """Run when entity about to be added."""
  114. await super().async_added_to_hass()
  115. last_state = await self.async_get_last_state()
  116. if last_state is not None:
  117. if 'speed' in last_state.attributes:
  118. self._speed = last_state.attributes['speed']
  119. #If _direction has a value the direction controls appears
  120. #in UI even if SUPPORT_DIRECTION is not provided in the flags
  121. if ('direction' in last_state.attributes and \
  122. self._support_flags & FanEntityFeature.DIRECTION):
  123. self._direction = last_state.attributes['direction']
  124. if 'last_on_speed' in last_state.attributes:
  125. self._last_on_speed = last_state.attributes['last_on_speed']
  126. if self._power_sensor:
  127. async_track_state_change(self.hass, self._power_sensor,
  128. self._async_power_sensor_changed)
  129. @property
  130. def unique_id(self):
  131. """Return a unique ID."""
  132. return self._unique_id
  133. @property
  134. def name(self):
  135. """Return the display name of the fan."""
  136. return self._name
  137. @property
  138. def state(self):
  139. """Return the current state."""
  140. if (self._on_by_remote or \
  141. self._speed != SPEED_OFF):
  142. return STATE_ON
  143. return SPEED_OFF
  144. @property
  145. def percentage(self):
  146. """Return speed percentage of the fan."""
  147. if (self._speed == SPEED_OFF):
  148. return 0
  149. return ordered_list_item_to_percentage(self._speed_list, self._speed)
  150. @property
  151. def speed_count(self):
  152. """Return the number of speeds the fan supports."""
  153. return len(self._speed_list)
  154. @property
  155. def oscillating(self):
  156. """Return the oscillation state."""
  157. return self._oscillating
  158. @property
  159. def current_direction(self):
  160. """Return the direction state."""
  161. return self._direction
  162. @property
  163. def last_on_speed(self):
  164. """Return the last non-idle speed."""
  165. return self._last_on_speed
  166. @property
  167. def supported_features(self):
  168. """Return the list of supported features."""
  169. return self._support_flags
  170. @property
  171. def extra_state_attributes(self):
  172. """Platform specific attributes."""
  173. return {
  174. 'last_on_speed': self._last_on_speed,
  175. 'device_code': self._device_code,
  176. 'manufacturer': self._manufacturer,
  177. 'supported_models': self._supported_models,
  178. 'supported_controller': self._supported_controller,
  179. 'commands_encoding': self._commands_encoding,
  180. }
  181. async def async_set_percentage(self, percentage: int):
  182. """Set the desired speed for the fan."""
  183. if (percentage == 0):
  184. self._speed = SPEED_OFF
  185. else:
  186. self._speed = percentage_to_ordered_list_item(
  187. self._speed_list, percentage)
  188. if not self._speed == SPEED_OFF:
  189. self._last_on_speed = self._speed
  190. await self.send_command()
  191. self.async_write_ha_state()
  192. async def async_oscillate(self, oscillating: bool) -> None:
  193. """Set oscillation of the fan."""
  194. self._oscillating = oscillating
  195. await self.send_command()
  196. self.async_write_ha_state()
  197. async def async_set_direction(self, direction: str):
  198. """Set the direction of the fan"""
  199. self._direction = direction
  200. if not self._speed.lower() == SPEED_OFF:
  201. await self.send_command()
  202. self.async_write_ha_state()
  203. async def async_turn_on(self, percentage: int = None, preset_mode: str = None, **kwargs):
  204. """Turn on the fan."""
  205. if percentage is None:
  206. percentage = ordered_list_item_to_percentage(
  207. self._speed_list, self._last_on_speed or self._speed_list[0])
  208. await self.async_set_percentage(percentage)
  209. async def async_turn_off(self):
  210. """Turn off the fan."""
  211. await self.async_set_percentage(0)
  212. async def send_command(self):
  213. async with self._temp_lock:
  214. self._on_by_remote = False
  215. speed = self._speed
  216. direction = self._direction or 'default'
  217. oscillating = self._oscillating
  218. if speed.lower() == SPEED_OFF:
  219. command = self._commands['off']
  220. elif oscillating:
  221. command = self._commands['oscillate']
  222. else:
  223. command = self._commands[direction][speed]
  224. try:
  225. await self._controller.send(command)
  226. except Exception as e:
  227. _LOGGER.exception(e)
  228. async def _async_power_sensor_changed(self, entity_id, old_state, new_state):
  229. """Handle power sensor changes."""
  230. if new_state is None:
  231. return
  232. if new_state.state == old_state.state:
  233. return
  234. if new_state.state == STATE_ON and self._speed == SPEED_OFF:
  235. self._on_by_remote = True
  236. self._speed = None
  237. self.async_write_ha_state()
  238. if new_state.state == STATE_OFF:
  239. self._on_by_remote = False
  240. if self._speed != SPEED_OFF:
  241. self._speed = SPEED_OFF
  242. self.async_write_ha_state()