climate.py 13 KB

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