4
0

climate.py 15 KB

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