climate.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. import asyncio
  2. import json
  3. import logging
  4. import os.path
  5. import voluptuous as vol
  6. from homeassistant.core import callback, split_entity_id
  7. """
  8. from homeassistant.components.climate import ClimateDevice, PLATFORM_SCHEMA
  9. from homeassistant.components.climate.const import (
  10. STATE_HEAT, STATE_COOL, STATE_AUTO, STATE_DRY,
  11. SUPPORT_OPERATION_MODE, SUPPORT_TARGET_TEMPERATURE, SUPPORT_FAN_MODE,
  12. SUPPORT_ON_OFF)
  13. """
  14. from homeassistant.components.climate import (
  15. STATE_HEAT, STATE_COOL, STATE_AUTO, STATE_DRY, ClimateDevice,
  16. SUPPORT_OPERATION_MODE, SUPPORT_TARGET_TEMPERATURE, SUPPORT_FAN_MODE,
  17. SUPPORT_ON_OFF, PLATFORM_SCHEMA)
  18. from homeassistant.const import (
  19. STATE_OFF, STATE_ON, ATTR_TEMPERATURE, CONF_NAME, STATE_UNKNOWN,
  20. PRECISION_HALVES, PRECISION_TENTHS, PRECISION_WHOLE)
  21. from homeassistant.helpers.event import async_track_state_change
  22. import homeassistant.helpers.config_validation as cv
  23. from homeassistant.helpers.restore_state import RestoreEntity
  24. _LOGGER = logging.getLogger(__name__)
  25. VERSION = '1.0.0'
  26. DEFAULT_NAME = 'SmartIR'
  27. CONF_DEVICE_CODE = 'device_code'
  28. CONF_CONTROLLER_SEND_SERVICE = "controller_send_service"
  29. CONF_TEMPERATURE_SENSOR = 'temperature_sensor'
  30. CONF_HUMIDITY_SENSOR = 'humidity_sensor'
  31. CONF_POWER_SENSOR = 'power_sensor'
  32. SUPPORT_FLAGS = (
  33. SUPPORT_TARGET_TEMPERATURE |
  34. SUPPORT_OPERATION_MODE |
  35. SUPPORT_FAN_MODE |
  36. SUPPORT_ON_OFF
  37. )
  38. PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
  39. vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
  40. vol.Required(CONF_DEVICE_CODE): cv.positive_int,
  41. vol.Required(CONF_CONTROLLER_SEND_SERVICE): cv.entity_id,
  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. })
  46. async def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
  47. """Set up the IR Climate platform."""
  48. name = config.get(CONF_NAME)
  49. device_code = config.get(CONF_DEVICE_CODE)
  50. controller_send_service = config.get(CONF_CONTROLLER_SEND_SERVICE)
  51. temperature_sensor = config.get(CONF_TEMPERATURE_SENSOR)
  52. humidity_sensor = config.get(CONF_HUMIDITY_SENSOR)
  53. power_sensor = config.get(CONF_POWER_SENSOR)
  54. abspath = os.path.dirname(os.path.abspath(__file__))
  55. device_json_file = "{}/codes/climate/{}.json".format(abspath, device_code)
  56. if not os.path.exists(device_json_file):
  57. _LOGGER.error("The device JSON file was not found. [%s]", device_json_file)
  58. return
  59. with open(device_json_file) as j:
  60. try:
  61. device_data = json.load(j)
  62. except:
  63. _LOGGER.error("The device JSON file is invalid")
  64. return
  65. async_add_devices([IRClimate(
  66. hass, name, device_code, device_data, controller_send_service,
  67. temperature_sensor, humidity_sensor, power_sensor
  68. )])
  69. class IRClimate(ClimateDevice, RestoreEntity):
  70. def __init__(self, hass, name, device_code, device_data,
  71. controller_send_service, temperature_sensor,
  72. humidity_sensor, power_sensor):
  73. self.hass = hass
  74. self._name = name
  75. self._device_code = device_code
  76. self._controller_send_service = controller_send_service
  77. self._temperature_sensor = temperature_sensor
  78. self._humidity_sensor = humidity_sensor
  79. self._power_sensor = power_sensor
  80. self._manufacturer = device_data['manufacturer']
  81. self._supported_models = device_data['supportedModels']
  82. self._supported_controller = device_data['supportedController']
  83. self._min_temperature = device_data['minTemperature']
  84. self._max_temperature = device_data['maxTemperature']
  85. self._precision = device_data['precision']
  86. self._operation_modes = [STATE_OFF] + device_data['operationModes']
  87. self._fan_modes = device_data['fanModes']
  88. self._commands = device_data['commands']
  89. self._target_temperature = self._min_temperature
  90. self._current_operation = STATE_OFF
  91. self._current_fan_mode = self._fan_modes[0]
  92. self._last_on_operation = None
  93. self._current_temperature = None
  94. self._current_humidity = None
  95. self._unit = hass.config.units.temperature_unit
  96. self._support_flags = SUPPORT_FLAGS
  97. self._temp_lock = asyncio.Lock()
  98. self._on_by_remote = False
  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. self._target_temperature = last_state.attributes['temperature']
  105. self._current_operation = last_state.attributes['operation_mode']
  106. self._current_fan_mode = last_state.attributes['fan_mode']
  107. if 'last_on_operation' in last_state.attributes:
  108. self._last_on_operation = last_state.attributes['last_on_operation']
  109. if self._temperature_sensor:
  110. async_track_state_change(self.hass, self._temperature_sensor,
  111. self._async_temp_sensor_changed)
  112. temp_sensor_state = self.hass.states.get(self._temperature_sensor)
  113. if temp_sensor_state and temp_sensor_state.state != STATE_UNKNOWN:
  114. self._async_update_temp(temp_sensor_state)
  115. if self._humidity_sensor:
  116. async_track_state_change(self.hass, self._humidity_sensor,
  117. self._async_humidity_sensor_changed)
  118. humidity_sensor_state = self.hass.states.get(self._humidity_sensor)
  119. if humidity_sensor_state and humidity_sensor_state.state != STATE_UNKNOWN:
  120. self._async_update_humidity(humidity_sensor_state)
  121. if self._power_sensor:
  122. async_track_state_change(self.hass, self._power_sensor,
  123. self._async_power_sensor_changed)
  124. @property
  125. def state(self):
  126. """Return the current state."""
  127. if self._on_by_remote:
  128. return STATE_ON
  129. if self.current_operation != STATE_OFF:
  130. return self.current_operation
  131. return STATE_OFF
  132. @property
  133. def should_poll(self):
  134. """Return the polling state."""
  135. return False
  136. @property
  137. def name(self):
  138. """Return the name of the climate device."""
  139. return self._name
  140. @property
  141. def temperature_unit(self):
  142. """Return the unit of measurement."""
  143. return self._unit
  144. @property
  145. def min_temp(self):
  146. """Return the polling state."""
  147. return self._min_temperature
  148. @property
  149. def max_temp(self):
  150. """Return the polling state."""
  151. return self._max_temperature
  152. @property
  153. def target_temperature(self):
  154. """Return the temperature we try to reach."""
  155. return self._target_temperature
  156. @property
  157. def target_temperature_step(self):
  158. """Return the supported step of target temperature."""
  159. return self._precision
  160. @property
  161. def precision(self):
  162. """Return the precision of the system."""
  163. return self._precision
  164. @property
  165. def operation_list(self):
  166. """Return the list of available operation modes."""
  167. return self._operation_modes
  168. @property
  169. def current_operation(self):
  170. """Return current operation ie. heat, cool."""
  171. return self._current_operation
  172. @property
  173. def last_on_operation(self):
  174. """Return the last non-idle operation ie. heat, cool."""
  175. return self._last_on_operation
  176. @property
  177. def fan_list(self):
  178. """Return the list of available fan modes."""
  179. return self._fan_modes
  180. @property
  181. def current_fan_mode(self):
  182. """Return the fan setting."""
  183. return self._current_fan_mode
  184. @property
  185. def current_temperature(self):
  186. """Return the current temperature."""
  187. return self._current_temperature
  188. @property
  189. def current_humidity(self):
  190. """Return the current humidity."""
  191. return self._current_humidity
  192. @property
  193. def is_on(self):
  194. return None
  195. @property
  196. def supported_features(self):
  197. """Return the list of supported features."""
  198. return self._support_flags
  199. @property
  200. def device_state_attributes(self) -> dict:
  201. """Platform specific attributes."""
  202. return {
  203. 'last_on_operation': self._last_on_operation,
  204. 'device_code': self._device_code,
  205. 'manufacturer': self._manufacturer,
  206. 'supported_models': self._supported_models,
  207. 'supported_controller': self._supported_controller,
  208. }
  209. async def async_set_temperature(self, **kwargs):
  210. """Set new target temperatures."""
  211. temperature = kwargs.get(ATTR_TEMPERATURE)
  212. if temperature is None:
  213. return
  214. if temperature < self._min_temperature or temperature > self._max_temperature:
  215. _LOGGER.warning('The temperature value is out of min/max range')
  216. return
  217. if self._precision == PRECISION_WHOLE:
  218. self._target_temperature = round(temperature)
  219. else:
  220. self._target_temperature = round(temperature, 1)
  221. if not self._current_operation.lower() == STATE_OFF:
  222. await self.send_command()
  223. await self.async_update_ha_state()
  224. async def async_set_operation_mode(self, operation_mode):
  225. """Set operation mode."""
  226. self._current_operation = operation_mode
  227. if not operation_mode == STATE_OFF:
  228. self._last_on_operation = operation_mode
  229. await self.send_command()
  230. await self.async_update_ha_state()
  231. async def async_set_fan_mode(self, fan_mode):
  232. """Set fan mode."""
  233. self._current_fan_mode = fan_mode
  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_turn_off(self):
  238. """Turn off."""
  239. await self.async_set_operation_mode(STATE_OFF)
  240. async def async_turn_on(self):
  241. """Turn on."""
  242. if self._last_on_operation is not None:
  243. await self.async_set_operation_mode(self._last_on_operation)
  244. else:
  245. await self.async_set_operation_mode(self._operation_modes[1])
  246. async def send_command(self):
  247. async with self._temp_lock:
  248. self._on_by_remote = False
  249. supported_controller = self._supported_controller
  250. operation_mode = self._current_operation
  251. fan_mode = self._current_fan_mode
  252. target_temperature = '{0:g}'.format(self._target_temperature)
  253. if operation_mode.lower() == STATE_OFF:
  254. command = self._commands['off']
  255. else:
  256. command = self._commands[operation_mode][fan_mode][target_temperature]
  257. service_domain = split_entity_id(self._controller_send_service)[0]
  258. service_name = split_entity_id(self._controller_send_service)[1]
  259. if supported_controller.lower() == 'broadlink':
  260. service_data = {
  261. 'packet': [command]
  262. }
  263. else:
  264. _LOGGER.error("The controller provided in the JSON file is not supported")
  265. return
  266. await self.hass.services.async_call(service_domain, service_name, service_data)
  267. async def _async_temp_sensor_changed(self, entity_id, old_state, new_state):
  268. """Handle temperature sensor changes."""
  269. if new_state is None:
  270. return
  271. self._async_update_temp(new_state)
  272. await self.async_update_ha_state()
  273. async def _async_humidity_sensor_changed(self, entity_id, old_state, new_state):
  274. """Handle humidity sensor changes."""
  275. if new_state is None:
  276. return
  277. self._async_update_humidity(new_state)
  278. await self.async_update_ha_state()
  279. async def _async_power_sensor_changed(self, entity_id, old_state, new_state):
  280. """Handle power sensor changes."""
  281. if new_state is None:
  282. return
  283. if new_state.state == STATE_OFF and self._current_operation != STATE_OFF:
  284. self._current_operation = STATE_OFF
  285. await self.async_update_ha_state()
  286. if new_state.state == STATE_ON and self._current_operation == STATE_OFF:
  287. self._on_by_remote = True
  288. await self.async_update_ha_state()
  289. @callback
  290. def _async_update_temp(self, state):
  291. """Update thermostat with latest state from temperature sensor."""
  292. try:
  293. if state.state != STATE_UNKNOWN:
  294. self._current_temperature = float(state.state)
  295. except ValueError as ex:
  296. _LOGGER.error("Unable to update from temperature sensor: %s", ex)
  297. @callback
  298. def _async_update_humidity(self, state):
  299. """Update thermostat with latest state from humidity sensor."""
  300. try:
  301. if state.state != STATE_UNKNOWN:
  302. self._current_humidity = float(state.state)
  303. except ValueError as ex:
  304. _LOGGER.error("Unable to update from humidity sensor: %s", ex)