fan.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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)
  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. Helper.downloader(codes_source.format(device_code), device_json_path)
  49. except:
  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:
  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._support_flags = SUPPORT_SET_SPEED
  82. if (DIRECTION_REVERSE in self._commands and \
  83. DIRECTION_FORWARD in self._commands):
  84. self._direction = DIRECTION_REVERSE
  85. self._support_flags = (
  86. self._support_flags | SUPPORT_DIRECTION)
  87. self._temp_lock = asyncio.Lock()
  88. self._on_by_remote = False
  89. #Init the IR/RF controller
  90. self._controller = Controller(
  91. self.hass,
  92. self._supported_controller,
  93. self._commands_encoding,
  94. self._controller_data)
  95. async def async_added_to_hass(self):
  96. """Run when entity about to be added."""
  97. await super().async_added_to_hass()
  98. last_state = await self.async_get_last_state()
  99. if last_state is not None:
  100. if 'speed' in last_state.attributes:
  101. self._speed = last_state.attributes['speed']
  102. #If _direction has a value the direction controls appears
  103. #in UI even if SUPPORT_DIRECTION is not provided in the flags
  104. if ('direction' in last_state.attributes and \
  105. self._support_flags & SUPPORT_DIRECTION):
  106. self._direction = last_state.attributes['direction']
  107. if 'last_on_speed' in last_state.attributes:
  108. self._last_on_speed = last_state.attributes['last_on_speed']
  109. if self._power_sensor:
  110. async_track_state_change(self.hass, self._power_sensor,
  111. self._async_power_sensor_changed)
  112. @property
  113. def unique_id(self):
  114. """Return a unique ID."""
  115. return self._unique_id
  116. @property
  117. def name(self):
  118. """Return the display name of the fan."""
  119. return self._name
  120. @property
  121. def state(self):
  122. """Return the current state."""
  123. if (self._on_by_remote or \
  124. self.speed != SPEED_OFF):
  125. return STATE_ON
  126. return SPEED_OFF
  127. @property
  128. def speed_list(self):
  129. """Get the list of available speeds."""
  130. return self._speed_list
  131. @property
  132. def speed(self):
  133. """Return the current speed."""
  134. return self._speed
  135. @property
  136. def oscillating(self):
  137. """Return the oscillation state."""
  138. return None
  139. @property
  140. def direction(self):
  141. """Return the oscillation state."""
  142. return self._direction
  143. @property
  144. def last_on_speed(self):
  145. """Return the last non-idle speed."""
  146. return self._last_on_speed
  147. @property
  148. def supported_features(self):
  149. """Return the list of supported features."""
  150. return self._support_flags
  151. @property
  152. def device_state_attributes(self) -> dict:
  153. """Platform specific attributes."""
  154. return {
  155. 'last_on_speed': self._last_on_speed,
  156. 'device_code': self._device_code,
  157. 'manufacturer': self._manufacturer,
  158. 'supported_models': self._supported_models,
  159. 'supported_controller': self._supported_controller,
  160. 'commands_encoding': self._commands_encoding,
  161. }
  162. async def async_set_speed(self, speed: str):
  163. """Set the speed of the fan."""
  164. self._speed = speed
  165. if not speed == SPEED_OFF:
  166. self._last_on_speed = speed
  167. await self.send_command()
  168. await self.async_update_ha_state()
  169. async def async_set_direction(self, direction: str):
  170. """Set the direction of the fan"""
  171. self._direction = direction
  172. if not self._speed.lower() == SPEED_OFF:
  173. await self.send_command()
  174. await self.async_update_ha_state()
  175. async def async_turn_on(self, speed: str = None, **kwargs):
  176. """Turn on the fan."""
  177. if speed is None:
  178. speed = self._last_on_speed or self._speed_list[1]
  179. await self.async_set_speed(speed)
  180. async def async_turn_off(self):
  181. """Turn off the fan."""
  182. await self.async_set_speed(SPEED_OFF)
  183. async def send_command(self):
  184. async with self._temp_lock:
  185. self._on_by_remote = False
  186. speed = self._speed
  187. direction = self._direction or 'default'
  188. if speed.lower() == SPEED_OFF:
  189. command = self._commands['off']
  190. else:
  191. command = self._commands[direction][speed]
  192. try:
  193. await self._controller.send(command)
  194. except Exception as e:
  195. _LOGGER.exception(e)
  196. async def _async_power_sensor_changed(self, entity_id, old_state, new_state):
  197. """Handle power sensor changes."""
  198. if new_state is None:
  199. return
  200. if new_state.state == STATE_ON and self._speed == SPEED_OFF:
  201. self._on_by_remote = True
  202. self._speed = None
  203. await self.async_update_ha_state()
  204. if new_state.state == STATE_OFF:
  205. self._on_by_remote = False
  206. if self._speed != SPEED_OFF:
  207. self._speed = SPEED_OFF
  208. await self.async_update_ha_state()