fan.py 10.0 KB

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