climate.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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. STATE_HEAT, STATE_COOL, STATE_AUTO, STATE_DRY,
  9. SUPPORT_OPERATION_MODE, SUPPORT_TARGET_TEMPERATURE, SUPPORT_FAN_MODE,
  10. SUPPORT_ON_OFF)
  11. from homeassistant.const import (
  12. CONF_NAME, STATE_OFF, STATE_ON, STATE_UNKNOWN, ATTR_TEMPERATURE,
  13. PRECISION_TENTHS, PRECISION_HALVES, PRECISION_WHOLE)
  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 . import COMPONENT_ABS_DIR, Helper
  19. from .controller import Controller
  20. _LOGGER = logging.getLogger(__name__)
  21. DEFAULT_NAME = "SmartIR Climate"
  22. CONF_UNIQUE_ID = 'unique_id'
  23. CONF_DEVICE_CODE = 'device_code'
  24. CONF_CONTROLLER_DATA = "controller_data"
  25. CONF_TEMPERATURE_SENSOR = 'temperature_sensor'
  26. CONF_HUMIDITY_SENSOR = 'humidity_sensor'
  27. CONF_POWER_SENSOR = 'power_sensor'
  28. SUPPORT_FLAGS = (
  29. SUPPORT_TARGET_TEMPERATURE |
  30. SUPPORT_OPERATION_MODE |
  31. SUPPORT_FAN_MODE |
  32. SUPPORT_ON_OFF
  33. )
  34. PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
  35. vol.Optional(CONF_UNIQUE_ID): cv.string,
  36. vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
  37. vol.Required(CONF_DEVICE_CODE): cv.positive_int,
  38. vol.Required(CONF_CONTROLLER_DATA): cv.string,
  39. vol.Optional(CONF_TEMPERATURE_SENSOR): cv.entity_id,
  40. vol.Optional(CONF_HUMIDITY_SENSOR): cv.entity_id,
  41. vol.Optional(CONF_POWER_SENSOR): cv.entity_id
  42. })
  43. async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
  44. """Set up the IR Climate platform."""
  45. device_code = config.get(CONF_DEVICE_CODE)
  46. device_files_subdir = os.path.join('codes', 'climate')
  47. device_files_absdir = os.path.join(COMPONENT_ABS_DIR, device_files_subdir)
  48. if not os.path.isdir(device_files_absdir):
  49. os.makedirs(device_files_absdir)
  50. device_json_filename = str(device_code) + '.json'
  51. device_json_path = os.path.join(device_files_absdir, device_json_filename)
  52. if not os.path.exists(device_json_path):
  53. _LOGGER.warning("Couldn't find the device Json file. The component will " \
  54. "try to download it from the GitHub repo.")
  55. try:
  56. codes_source = ("https://raw.githubusercontent.com/"
  57. "smartHomeHub/SmartIR/master/"
  58. "codes/climate/{}.json")
  59. Helper.downloader(codes_source.format(device_code), device_json_path)
  60. except:
  61. _LOGGER.error("There was an error while downloading the device Json file. " \
  62. "Please check your internet connection or the device code " \
  63. "exists on GitHub. If the problem still exists please " \
  64. "place the file manually in the proper location.")
  65. return
  66. with open(device_json_path) as j:
  67. try:
  68. device_data = json.load(j)
  69. except:
  70. _LOGGER.error("The device Json file is invalid")
  71. return
  72. async_add_entities([SmartIRClimate(
  73. hass, config, device_data
  74. )])
  75. class SmartIRClimate(ClimateDevice, RestoreEntity):
  76. def __init__(self, hass, config, device_data):
  77. self.hass = hass
  78. self._unique_id = config.get(CONF_UNIQUE_ID)
  79. self._name = config.get(CONF_NAME)
  80. self._device_code = config.get(CONF_DEVICE_CODE)
  81. self._controller_data = config.get(CONF_CONTROLLER_DATA)
  82. self._temperature_sensor = config.get(CONF_TEMPERATURE_SENSOR)
  83. self._humidity_sensor = config.get(CONF_HUMIDITY_SENSOR)
  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._min_temperature = device_data['minTemperature']
  90. self._max_temperature = device_data['maxTemperature']
  91. self._precision = device_data['precision']
  92. self._operation_modes = [STATE_OFF] + device_data['operationModes']
  93. self._fan_modes = device_data['fanModes']
  94. self._commands = device_data['commands']
  95. self._target_temperature = self._min_temperature
  96. self._current_operation = STATE_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._target_temperature = last_state.attributes['temperature']
  117. self._current_operation = last_state.attributes['operation_mode']
  118. self._current_fan_mode = last_state.attributes['fan_mode']
  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.current_operation != STATE_OFF:
  150. return self.current_operation
  151. return STATE_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 operation_list(self):
  174. """Return the list of available operation modes."""
  175. return self._operation_modes
  176. @property
  177. def current_operation(self):
  178. """Return current operation ie. heat, cool."""
  179. return self._current_operation
  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_list(self):
  186. """Return the list of available fan modes."""
  187. return self._fan_modes
  188. @property
  189. def current_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 is_on(self):
  202. return None
  203. @property
  204. def supported_features(self):
  205. """Return the list of supported features."""
  206. return self._support_flags
  207. @property
  208. def device_state_attributes(self) -> dict:
  209. """Platform specific attributes."""
  210. return {
  211. 'last_on_operation': self._last_on_operation,
  212. 'device_code': self._device_code,
  213. 'manufacturer': self._manufacturer,
  214. 'supported_models': self._supported_models,
  215. 'supported_controller': self._supported_controller,
  216. 'commands_encoding': self._commands_encoding,
  217. }
  218. async def async_set_temperature(self, **kwargs):
  219. """Set new target temperatures."""
  220. temperature = kwargs.get(ATTR_TEMPERATURE)
  221. if temperature is None:
  222. return
  223. if temperature < self._min_temperature or temperature > self._max_temperature:
  224. _LOGGER.warning('The temperature value is out of min/max range')
  225. return
  226. if self._precision == PRECISION_WHOLE:
  227. self._target_temperature = round(temperature)
  228. else:
  229. self._target_temperature = round(temperature, 1)
  230. if not self._current_operation.lower() == STATE_OFF:
  231. await self.send_command()
  232. await self.async_update_ha_state()
  233. async def async_set_operation_mode(self, operation_mode):
  234. """Set operation mode."""
  235. self._current_operation = operation_mode
  236. if not operation_mode == STATE_OFF:
  237. self._last_on_operation = operation_mode
  238. await self.send_command()
  239. await self.async_update_ha_state()
  240. async def async_set_fan_mode(self, fan_mode):
  241. """Set fan mode."""
  242. self._current_fan_mode = fan_mode
  243. if not self._current_operation.lower() == STATE_OFF:
  244. await self.send_command()
  245. await self.async_update_ha_state()
  246. async def async_turn_off(self):
  247. """Turn off."""
  248. await self.async_set_operation_mode(STATE_OFF)
  249. async def async_turn_on(self):
  250. """Turn on."""
  251. if self._last_on_operation is not None:
  252. await self.async_set_operation_mode(self._last_on_operation)
  253. else:
  254. await self.async_set_operation_mode(self._operation_modes[1])
  255. async def send_command(self):
  256. async with self._temp_lock:
  257. self._on_by_remote = False
  258. operation_mode = self._current_operation
  259. fan_mode = self._current_fan_mode
  260. target_temperature = '{0:g}'.format(self._target_temperature)
  261. if operation_mode.lower() == STATE_OFF:
  262. command = self._commands['off']
  263. else:
  264. command = self._commands[operation_mode][fan_mode][target_temperature]
  265. try:
  266. await self._controller.send(command)
  267. except Exception as e:
  268. _LOGGER.exception(e)
  269. async def _async_temp_sensor_changed(self, entity_id, old_state, new_state):
  270. """Handle temperature sensor changes."""
  271. if new_state is None:
  272. return
  273. self._async_update_temp(new_state)
  274. await self.async_update_ha_state()
  275. async def _async_humidity_sensor_changed(self, entity_id, old_state, new_state):
  276. """Handle humidity sensor changes."""
  277. if new_state is None:
  278. return
  279. self._async_update_humidity(new_state)
  280. await self.async_update_ha_state()
  281. async def _async_power_sensor_changed(self, entity_id, old_state, new_state):
  282. """Handle power sensor changes."""
  283. if new_state is None:
  284. return
  285. if new_state.state == STATE_ON and self._current_operation == STATE_OFF:
  286. self._on_by_remote = True
  287. await self.async_update_ha_state()
  288. if new_state.state == STATE_OFF:
  289. self._on_by_remote = False
  290. if self._current_operation != STATE_OFF:
  291. self._current_operation = STATE_OFF
  292. await self.async_update_ha_state()
  293. @callback
  294. def _async_update_temp(self, state):
  295. """Update thermostat with latest state from temperature sensor."""
  296. try:
  297. if state.state != STATE_UNKNOWN:
  298. self._current_temperature = float(state.state)
  299. except ValueError as ex:
  300. _LOGGER.error("Unable to update from temperature sensor: %s", ex)
  301. @callback
  302. def _async_update_humidity(self, state):
  303. """Update thermostat with latest state from humidity sensor."""
  304. try:
  305. if state.state != STATE_UNKNOWN:
  306. self._current_humidity = float(state.state)
  307. except ValueError as ex:
  308. _LOGGER.error("Unable to update from humidity sensor: %s", ex)