climate.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. import asyncio
  2. import json
  3. import logging
  4. import os.path
  5. import voluptuous as vol
  6. from homeassistant.components.climate import ClimateEntity, PLATFORM_SCHEMA
  7. from homeassistant.components.climate.const import (
  8. HVAC_MODE_OFF, HVAC_MODE_HEAT, HVAC_MODE_COOL,
  9. HVAC_MODE_DRY, HVAC_MODE_FAN_ONLY, HVAC_MODE_AUTO,
  10. SUPPORT_TARGET_TEMPERATURE, SUPPORT_FAN_MODE,
  11. HVAC_MODES, ATTR_HVAC_MODE)
  12. from homeassistant.const import (
  13. CONF_NAME, STATE_ON, STATE_OFF, STATE_UNKNOWN, ATTR_TEMPERATURE,
  14. PRECISION_TENTHS, PRECISION_HALVES, PRECISION_WHOLE)
  15. from homeassistant.core import callback
  16. from homeassistant.helpers.event import async_track_state_change
  17. import homeassistant.helpers.config_validation as cv
  18. from homeassistant.helpers.restore_state import RestoreEntity
  19. from . import COMPONENT_ABS_DIR, Helper
  20. from .controller import get_controller
  21. _LOGGER = logging.getLogger(__name__)
  22. DEFAULT_NAME = "SmartIR Climate"
  23. DEFAULT_DELAY = 0.5
  24. CONF_UNIQUE_ID = 'unique_id'
  25. CONF_DEVICE_CODE = 'device_code'
  26. CONF_CONTROLLER_DATA = "controller_data"
  27. CONF_DELAY = "delay"
  28. CONF_TEMPERATURE_SENSOR = 'temperature_sensor'
  29. CONF_HUMIDITY_SENSOR = 'humidity_sensor'
  30. CONF_POWER_SENSOR = 'power_sensor'
  31. CONF_POWER_SENSOR_RESTORE_STATE = 'power_sensor_restore_state'
  32. SUPPORT_FLAGS = (
  33. SUPPORT_TARGET_TEMPERATURE |
  34. SUPPORT_FAN_MODE
  35. )
  36. PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
  37. vol.Optional(CONF_UNIQUE_ID): cv.string,
  38. vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
  39. vol.Required(CONF_DEVICE_CODE): cv.positive_int,
  40. vol.Required(CONF_CONTROLLER_DATA): cv.string,
  41. vol.Optional(CONF_DELAY, default=DEFAULT_DELAY): cv.string,
  42. vol.Optional(CONF_TEMPERATURE_SENSOR): cv.entity_id,
  43. vol.Optional(CONF_HUMIDITY_SENSOR): cv.entity_id,
  44. vol.Optional(CONF_POWER_SENSOR): cv.entity_id,
  45. vol.Optional(CONF_POWER_SENSOR_RESTORE_STATE, default=False): cv.boolean
  46. })
  47. async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
  48. """Set up the IR Climate platform."""
  49. device_code = config.get(CONF_DEVICE_CODE)
  50. device_files_subdir = os.path.join('codes', 'climate')
  51. device_files_absdir = os.path.join(COMPONENT_ABS_DIR, device_files_subdir)
  52. if not os.path.isdir(device_files_absdir):
  53. os.makedirs(device_files_absdir)
  54. device_json_filename = str(device_code) + '.json'
  55. device_json_path = os.path.join(device_files_absdir, device_json_filename)
  56. if not os.path.exists(device_json_path):
  57. _LOGGER.warning("Couldn't find the device Json file. The component will " \
  58. "try to download it from the GitHub repo.")
  59. try:
  60. codes_source = ("https://raw.githubusercontent.com/"
  61. "smartHomeHub/SmartIR/master/"
  62. "codes/climate/{}.json")
  63. await Helper.downloader(codes_source.format(device_code), device_json_path)
  64. except Exception:
  65. _LOGGER.error("There was an error while downloading the device Json file. " \
  66. "Please check your internet connection or if the device code " \
  67. "exists on GitHub. If the problem still exists please " \
  68. "place the file manually in the proper directory.")
  69. return
  70. with open(device_json_path) as j:
  71. try:
  72. device_data = json.load(j)
  73. except Exception:
  74. _LOGGER.error("The device Json file is invalid")
  75. return
  76. async_add_entities([SmartIRClimate(
  77. hass, config, device_data
  78. )])
  79. class SmartIRClimate(ClimateEntity, RestoreEntity):
  80. def __init__(self, hass, config, device_data):
  81. self.hass = hass
  82. self._unique_id = config.get(CONF_UNIQUE_ID)
  83. self._name = config.get(CONF_NAME)
  84. self._device_code = config.get(CONF_DEVICE_CODE)
  85. self._controller_data = config.get(CONF_CONTROLLER_DATA)
  86. self._delay = config.get(CONF_DELAY)
  87. self._temperature_sensor = config.get(CONF_TEMPERATURE_SENSOR)
  88. self._humidity_sensor = config.get(CONF_HUMIDITY_SENSOR)
  89. self._power_sensor = config.get(CONF_POWER_SENSOR)
  90. self._power_sensor_restore_state = config.get(CONF_POWER_SENSOR_RESTORE_STATE)
  91. self._manufacturer = device_data['manufacturer']
  92. self._supported_models = device_data['supportedModels']
  93. self._supported_controller = device_data['supportedController']
  94. self._commands_encoding = device_data['commandsEncoding']
  95. self._min_temperature = device_data['minTemperature']
  96. self._max_temperature = device_data['maxTemperature']
  97. self._precision = device_data['precision']
  98. valid_hvac_modes = [x for x in device_data['operationModes'] if x in HVAC_MODES]
  99. self._operation_modes = [HVAC_MODE_OFF] + valid_hvac_modes
  100. self._fan_modes = device_data['fanModes']
  101. self._commands = device_data['commands']
  102. self._target_temperature = self._min_temperature
  103. self._hvac_mode = HVAC_MODE_OFF
  104. self._current_fan_mode = self._fan_modes[0]
  105. self._last_on_operation = None
  106. self._current_temperature = None
  107. self._current_humidity = None
  108. self._unit = hass.config.units.temperature_unit
  109. self._support_flags = SUPPORT_FLAGS
  110. self._temp_lock = asyncio.Lock()
  111. self._on_by_remote = False
  112. #Init the IR/RF controller
  113. self._controller = get_controller(
  114. self.hass,
  115. self._supported_controller,
  116. self._commands_encoding,
  117. self._controller_data,
  118. self._delay)
  119. async def async_added_to_hass(self):
  120. """Run when entity about to be added."""
  121. await super().async_added_to_hass()
  122. last_state = await self.async_get_last_state()
  123. if last_state is not None:
  124. self._hvac_mode = last_state.state
  125. self._current_fan_mode = last_state.attributes['fan_mode']
  126. self._target_temperature = last_state.attributes['temperature']
  127. if 'last_on_operation' in last_state.attributes:
  128. self._last_on_operation = last_state.attributes['last_on_operation']
  129. if self._temperature_sensor:
  130. async_track_state_change(self.hass, self._temperature_sensor,
  131. self._async_temp_sensor_changed)
  132. temp_sensor_state = self.hass.states.get(self._temperature_sensor)
  133. if temp_sensor_state and temp_sensor_state.state != STATE_UNKNOWN:
  134. self._async_update_temp(temp_sensor_state)
  135. if self._humidity_sensor:
  136. async_track_state_change(self.hass, self._humidity_sensor,
  137. self._async_humidity_sensor_changed)
  138. humidity_sensor_state = self.hass.states.get(self._humidity_sensor)
  139. if humidity_sensor_state and humidity_sensor_state.state != STATE_UNKNOWN:
  140. self._async_update_humidity(humidity_sensor_state)
  141. if self._power_sensor:
  142. async_track_state_change(self.hass, self._power_sensor,
  143. self._async_power_sensor_changed)
  144. @property
  145. def unique_id(self):
  146. """Return a unique ID."""
  147. return self._unique_id
  148. @property
  149. def name(self):
  150. """Return the name of the climate device."""
  151. return self._name
  152. @property
  153. def state(self):
  154. """Return the current state."""
  155. if self.hvac_mode != HVAC_MODE_OFF:
  156. return self.hvac_mode
  157. return HVAC_MODE_OFF
  158. @property
  159. def temperature_unit(self):
  160. """Return the unit of measurement."""
  161. return self._unit
  162. @property
  163. def min_temp(self):
  164. """Return the polling state."""
  165. return self._min_temperature
  166. @property
  167. def max_temp(self):
  168. """Return the polling state."""
  169. return self._max_temperature
  170. @property
  171. def target_temperature(self):
  172. """Return the temperature we try to reach."""
  173. return self._target_temperature
  174. @property
  175. def target_temperature_step(self):
  176. """Return the supported step of target temperature."""
  177. return self._precision
  178. @property
  179. def hvac_modes(self):
  180. """Return the list of available operation modes."""
  181. return self._operation_modes
  182. @property
  183. def hvac_mode(self):
  184. """Return hvac mode ie. heat, cool."""
  185. return self._hvac_mode
  186. @property
  187. def last_on_operation(self):
  188. """Return the last non-idle operation ie. heat, cool."""
  189. return self._last_on_operation
  190. @property
  191. def fan_modes(self):
  192. """Return the list of available fan modes."""
  193. return self._fan_modes
  194. @property
  195. def fan_mode(self):
  196. """Return the fan setting."""
  197. return self._current_fan_mode
  198. @property
  199. def current_temperature(self):
  200. """Return the current temperature."""
  201. return self._current_temperature
  202. @property
  203. def current_humidity(self):
  204. """Return the current humidity."""
  205. return self._current_humidity
  206. @property
  207. def supported_features(self):
  208. """Return the list of supported features."""
  209. return self._support_flags
  210. @property
  211. def device_state_attributes(self) -> dict:
  212. """Platform specific attributes."""
  213. return {
  214. 'last_on_operation': self._last_on_operation,
  215. 'device_code': self._device_code,
  216. 'manufacturer': self._manufacturer,
  217. 'supported_models': self._supported_models,
  218. 'supported_controller': self._supported_controller,
  219. 'commands_encoding': self._commands_encoding
  220. }
  221. async def async_set_temperature(self, **kwargs):
  222. """Set new target temperatures."""
  223. hvac_mode = kwargs.get(ATTR_HVAC_MODE)
  224. temperature = kwargs.get(ATTR_TEMPERATURE)
  225. if temperature is None:
  226. return
  227. if temperature < self._min_temperature or temperature > self._max_temperature:
  228. _LOGGER.warning('The temperature value is out of min/max range')
  229. return
  230. if self._precision == PRECISION_WHOLE:
  231. self._target_temperature = round(temperature)
  232. else:
  233. self._target_temperature = round(temperature, 1)
  234. if hvac_mode:
  235. await self.async_set_hvac_mode(hvac_mode)
  236. return
  237. if not self._hvac_mode.lower() == HVAC_MODE_OFF:
  238. await self.send_command()
  239. await self.async_update_ha_state()
  240. async def async_set_hvac_mode(self, hvac_mode):
  241. """Set operation mode."""
  242. self._hvac_mode = hvac_mode
  243. if not hvac_mode == HVAC_MODE_OFF:
  244. self._last_on_operation = hvac_mode
  245. await self.send_command()
  246. await self.async_update_ha_state()
  247. async def async_set_fan_mode(self, fan_mode):
  248. """Set fan mode."""
  249. self._current_fan_mode = fan_mode
  250. if not self._hvac_mode.lower() == HVAC_MODE_OFF:
  251. await self.send_command()
  252. await self.async_update_ha_state()
  253. async def async_turn_off(self):
  254. """Turn off."""
  255. await self.async_set_hvac_mode(HVAC_MODE_OFF)
  256. async def async_turn_on(self):
  257. """Turn on."""
  258. if self._last_on_operation is not None:
  259. await self.async_set_hvac_mode(self._last_on_operation)
  260. else:
  261. await self.async_set_hvac_mode(self._operation_modes[1])
  262. async def send_command(self):
  263. async with self._temp_lock:
  264. try:
  265. self._on_by_remote = False
  266. operation_mode = self._hvac_mode
  267. fan_mode = self._current_fan_mode
  268. target_temperature = '{0:g}'.format(self._target_temperature)
  269. if operation_mode.lower() == HVAC_MODE_OFF:
  270. await self._controller.send(self._commands['off'])
  271. return
  272. if 'on' in self._commands:
  273. await self._controller.send(self._commands['on'])
  274. await asyncio.sleep(self._delay)
  275. await self._controller.send(
  276. self._commands[operation_mode][fan_mode][target_temperature])
  277. except Exception as e:
  278. _LOGGER.exception(e)
  279. async def _async_temp_sensor_changed(self, entity_id, old_state, new_state):
  280. """Handle temperature sensor changes."""
  281. if new_state is None:
  282. return
  283. self._async_update_temp(new_state)
  284. await self.async_update_ha_state()
  285. async def _async_humidity_sensor_changed(self, entity_id, old_state, new_state):
  286. """Handle humidity sensor changes."""
  287. if new_state is None:
  288. return
  289. self._async_update_humidity(new_state)
  290. await self.async_update_ha_state()
  291. async def _async_power_sensor_changed(self, entity_id, old_state, new_state):
  292. """Handle power sensor changes."""
  293. if new_state is None:
  294. return
  295. if new_state.state == old_state.state:
  296. return
  297. if new_state.state == STATE_ON and self._hvac_mode == HVAC_MODE_OFF:
  298. self._on_by_remote = True
  299. if self._power_sensor_restore_state == True and self._last_on_operation is not None:
  300. self._hvac_mode = self._last_on_operation
  301. else:
  302. self._hvac_mode = STATE_ON
  303. await self.async_update_ha_state()
  304. if new_state.state == STATE_OFF:
  305. self._on_by_remote = False
  306. if self._hvac_mode != HVAC_MODE_OFF:
  307. self._hvac_mode = HVAC_MODE_OFF
  308. await self.async_update_ha_state()
  309. @callback
  310. def _async_update_temp(self, state):
  311. """Update thermostat with latest state from temperature sensor."""
  312. try:
  313. if state.state != STATE_UNKNOWN:
  314. self._current_temperature = float(state.state)
  315. except ValueError as ex:
  316. _LOGGER.error("Unable to update from temperature sensor: %s", ex)
  317. @callback
  318. def _async_update_humidity(self, state):
  319. """Update thermostat with latest state from humidity sensor."""
  320. try:
  321. if state.state != STATE_UNKNOWN:
  322. self._current_humidity = float(state.state)
  323. except ValueError as ex:
  324. _LOGGER.error("Unable to update from humidity sensor: %s", ex)