fan.py 8.9 KB

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