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