fan.py 9.3 KB

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