climate.py 14 KB

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