fan.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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 Event, EventStateChangedData, callback
  13. from homeassistant.helpers.event import async_track_state_change_event
  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 = (
  94. FanEntityFeature.SET_SPEED
  95. | FanEntityFeature.TURN_OFF
  96. | FanEntityFeature.TURN_ON)
  97. if (DIRECTION_REVERSE in self._commands and \
  98. DIRECTION_FORWARD in self._commands):
  99. self._direction = DIRECTION_REVERSE
  100. self._support_flags = (
  101. self._support_flags | FanEntityFeature.DIRECTION)
  102. if ('oscillate' in self._commands):
  103. self._oscillating = False
  104. self._support_flags = (
  105. self._support_flags | FanEntityFeature.OSCILLATE)
  106. self._temp_lock = asyncio.Lock()
  107. self._on_by_remote = False
  108. #Init the IR/RF controller
  109. self._controller = get_controller(
  110. self.hass,
  111. self._supported_controller,
  112. self._commands_encoding,
  113. self._controller_data,
  114. self._delay)
  115. async def async_added_to_hass(self):
  116. """Run when entity about to be added."""
  117. await super().async_added_to_hass()
  118. last_state = await self.async_get_last_state()
  119. if last_state is not None:
  120. if 'speed' in last_state.attributes:
  121. self._speed = last_state.attributes['speed']
  122. #If _direction has a value the direction controls appears
  123. #in UI even if SUPPORT_DIRECTION is not provided in the flags
  124. if ('direction' in last_state.attributes and \
  125. self._support_flags & FanEntityFeature.DIRECTION):
  126. self._direction = last_state.attributes['direction']
  127. if 'last_on_speed' in last_state.attributes:
  128. self._last_on_speed = last_state.attributes['last_on_speed']
  129. if self._power_sensor:
  130. async_track_state_change_event(self.hass, self._power_sensor,
  131. self._async_power_sensor_changed)
  132. @property
  133. def unique_id(self):
  134. """Return a unique ID."""
  135. return self._unique_id
  136. @property
  137. def name(self):
  138. """Return the display name of the fan."""
  139. return self._name
  140. @property
  141. def state(self):
  142. """Return the current state."""
  143. if (self._on_by_remote or \
  144. self._speed != SPEED_OFF):
  145. return STATE_ON
  146. return SPEED_OFF
  147. @property
  148. def percentage(self):
  149. """Return speed percentage of the fan."""
  150. if (self._speed == SPEED_OFF):
  151. return 0
  152. return ordered_list_item_to_percentage(self._speed_list, self._speed)
  153. @property
  154. def speed_count(self):
  155. """Return the number of speeds the fan supports."""
  156. return len(self._speed_list)
  157. @property
  158. def oscillating(self):
  159. """Return the oscillation state."""
  160. return self._oscillating
  161. @property
  162. def current_direction(self):
  163. """Return the direction state."""
  164. return self._direction
  165. @property
  166. def last_on_speed(self):
  167. """Return the last non-idle speed."""
  168. return self._last_on_speed
  169. @property
  170. def supported_features(self):
  171. """Return the list of supported features."""
  172. return self._support_flags
  173. @property
  174. def extra_state_attributes(self):
  175. """Platform specific attributes."""
  176. return {
  177. 'last_on_speed': self._last_on_speed,
  178. 'device_code': self._device_code,
  179. 'manufacturer': self._manufacturer,
  180. 'supported_models': self._supported_models,
  181. 'supported_controller': self._supported_controller,
  182. 'commands_encoding': self._commands_encoding,
  183. }
  184. async def async_set_percentage(self, percentage: int):
  185. """Set the desired speed for the fan."""
  186. if (percentage == 0):
  187. self._speed = SPEED_OFF
  188. else:
  189. self._speed = percentage_to_ordered_list_item(
  190. self._speed_list, percentage)
  191. if not self._speed == SPEED_OFF:
  192. self._last_on_speed = self._speed
  193. await self.send_command()
  194. self.async_write_ha_state()
  195. async def async_oscillate(self, oscillating: bool) -> None:
  196. """Set oscillation of the fan."""
  197. self._oscillating = oscillating
  198. await self.send_command()
  199. self.async_write_ha_state()
  200. async def async_set_direction(self, direction: str):
  201. """Set the direction of the fan"""
  202. self._direction = direction
  203. if not self._speed.lower() == SPEED_OFF:
  204. await self.send_command()
  205. self.async_write_ha_state()
  206. async def async_turn_on(self, percentage: int = None, preset_mode: str = None, **kwargs):
  207. """Turn on the fan."""
  208. if percentage is None:
  209. percentage = ordered_list_item_to_percentage(
  210. self._speed_list, self._last_on_speed or self._speed_list[0])
  211. await self.async_set_percentage(percentage)
  212. async def async_turn_off(self):
  213. """Turn off the fan."""
  214. await self.async_set_percentage(0)
  215. async def send_command(self):
  216. async with self._temp_lock:
  217. self._on_by_remote = False
  218. speed = self._speed
  219. direction = self._direction or 'default'
  220. oscillating = self._oscillating
  221. if speed.lower() == SPEED_OFF:
  222. command = self._commands['off']
  223. elif oscillating:
  224. command = self._commands['oscillate']
  225. else:
  226. command = self._commands[direction][speed]
  227. try:
  228. await self._controller.send(command)
  229. except Exception as e:
  230. _LOGGER.exception(e)
  231. @callback
  232. async def _async_power_sensor_changed(self, event: Event[EventStateChangedData]) -> None:
  233. """Handle power sensor changes."""
  234. entity_id = event.data["entity_id"]
  235. old_state = event.data["old_state"]
  236. new_state = event.data["new_state"]
  237. if new_state is None:
  238. return
  239. if new_state.state == old_state.state:
  240. return
  241. if new_state.state == STATE_ON and self._speed == SPEED_OFF:
  242. self._on_by_remote = True
  243. self._speed = None
  244. self.async_write_ha_state()
  245. if new_state.state == STATE_OFF:
  246. self._on_by_remote = False
  247. if self._speed != SPEED_OFF:
  248. self._speed = SPEED_OFF
  249. self.async_write_ha_state()