fan.py 10 KB

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