fan.py 9.5 KB

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