climate.py 15 KB

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