climate.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. import asyncio
  2. import aiofiles
  3. import json
  4. import logging
  5. import os.path
  6. import voluptuous as vol
  7. from homeassistant.components.climate import ClimateEntity, PLATFORM_SCHEMA
  8. from homeassistant.components.climate.const import (
  9. ClimateEntityFeature, HVACMode, HVAC_MODES, ATTR_HVAC_MODE)
  10. from homeassistant.const import (
  11. CONF_NAME, STATE_ON, STATE_OFF, STATE_UNKNOWN, STATE_UNAVAILABLE, ATTR_TEMPERATURE,
  12. PRECISION_TENTHS, PRECISION_HALVES, PRECISION_WHOLE)
  13. from homeassistant.core import callback
  14. from homeassistant.helpers.event import async_track_state_change
  15. import homeassistant.helpers.config_validation as cv
  16. from homeassistant.helpers.restore_state import RestoreEntity
  17. from . import COMPONENT_ABS_DIR, Helper
  18. from .controller import get_controller
  19. _LOGGER = logging.getLogger(__name__)
  20. DEFAULT_NAME = "SmartIR Climate"
  21. DEFAULT_DELAY = 0.5
  22. CONF_UNIQUE_ID = 'unique_id'
  23. CONF_DEVICE_CODE = 'device_code'
  24. CONF_CONTROLLER_DATA = "controller_data"
  25. CONF_DELAY = "delay"
  26. CONF_TEMPERATURE_SENSOR = 'temperature_sensor'
  27. CONF_HUMIDITY_SENSOR = 'humidity_sensor'
  28. CONF_POWER_SENSOR = 'power_sensor'
  29. CONF_POWER_SENSOR_RESTORE_STATE = 'power_sensor_restore_state'
  30. SUPPORT_FLAGS = (
  31. ClimateEntityFeature.TURN_OFF |
  32. ClimateEntityFeature.TURN_ON |
  33. ClimateEntityFeature.TARGET_TEMPERATURE |
  34. ClimateEntityFeature.FAN_MODE
  35. )
  36. PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
  37. vol.Optional(CONF_UNIQUE_ID): cv.string,
  38. vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
  39. vol.Required(CONF_DEVICE_CODE): cv.positive_int,
  40. vol.Required(CONF_CONTROLLER_DATA): cv.string,
  41. vol.Optional(CONF_DELAY, default=DEFAULT_DELAY): cv.positive_float,
  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. vol.Optional(CONF_POWER_SENSOR_RESTORE_STATE, default=False): cv.boolean
  46. })
  47. async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
  48. """Set up the IR Climate platform."""
  49. _LOGGER.debug("Setting up the smartir platform")
  50. device_code = config.get(CONF_DEVICE_CODE)
  51. device_files_subdir = os.path.join('codes', 'climate')
  52. device_files_absdir = os.path.join(COMPONENT_ABS_DIR, device_files_subdir)
  53. if not os.path.isdir(device_files_absdir):
  54. os.makedirs(device_files_absdir)
  55. device_json_filename = str(device_code) + '.json'
  56. device_json_path = os.path.join(device_files_absdir, 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/"
  63. "codes/climate/{}.json")
  64. await Helper.downloader(codes_source.format(device_code), device_json_path)
  65. except Exception:
  66. _LOGGER.error("There was an error while downloading the device Json file. " \
  67. "Please check your internet connection or if the device code " \
  68. "exists on GitHub. If the problem still exists please " \
  69. "place the file manually in the proper directory.")
  70. return
  71. try:
  72. async with aiofiles.open(device_json_path, mode='r') as j:
  73. _LOGGER.debug(f"loading json file {device_json_path}")
  74. content = await j.read()
  75. device_data = json.loads(content)
  76. _LOGGER.debug(f"{device_json_path} file loaded")
  77. except Exception:
  78. _LOGGER.error("The device JSON file is invalid")
  79. return
  80. async_add_entities([SmartIRClimate(
  81. hass, config, device_data
  82. )])
  83. class SmartIRClimate(ClimateEntity, RestoreEntity):
  84. def __init__(self, hass, config, device_data):
  85. _LOGGER.debug(f"SmartIRClimate init started for device {config.get(CONF_NAME)} supported models {device_data['supportedModels']}")
  86. self.hass = hass
  87. self._unique_id = config.get(CONF_UNIQUE_ID)
  88. self._name = config.get(CONF_NAME)
  89. self._device_code = config.get(CONF_DEVICE_CODE)
  90. self._controller_data = config.get(CONF_CONTROLLER_DATA)
  91. self._delay = config.get(CONF_DELAY)
  92. self._temperature_sensor = config.get(CONF_TEMPERATURE_SENSOR)
  93. self._humidity_sensor = config.get(CONF_HUMIDITY_SENSOR)
  94. self._power_sensor = config.get(CONF_POWER_SENSOR)
  95. self._power_sensor_restore_state = config.get(CONF_POWER_SENSOR_RESTORE_STATE)
  96. self._manufacturer = device_data['manufacturer']
  97. self._supported_models = device_data['supportedModels']
  98. self._supported_controller = device_data['supportedController']
  99. self._commands_encoding = device_data['commandsEncoding']
  100. self._min_temperature = device_data['minTemperature']
  101. self._max_temperature = device_data['maxTemperature']
  102. self._precision = device_data['precision']
  103. valid_hvac_modes = [x for x in device_data['operationModes'] if x in HVAC_MODES]
  104. self._operation_modes = [HVACMode.OFF] + valid_hvac_modes
  105. self._fan_modes = device_data['fanModes']
  106. self._swing_modes = device_data.get('swingModes')
  107. self._commands = device_data['commands']
  108. self._target_temperature = self._min_temperature
  109. self._hvac_mode = HVACMode.OFF
  110. self._current_fan_mode = self._fan_modes[0]
  111. self._current_swing_mode = None
  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. #Supported features
  117. self._support_flags = SUPPORT_FLAGS
  118. self._support_swing = False
  119. if self._swing_modes:
  120. self._support_flags = self._support_flags | ClimateEntityFeature.SWING_MODE
  121. self._current_swing_mode = self._swing_modes[0]
  122. self._support_swing = True
  123. self._temp_lock = asyncio.Lock()
  124. self._on_by_remote = False
  125. #Init the IR/RF controller
  126. self._controller = get_controller(
  127. self.hass,
  128. self._supported_controller,
  129. self._commands_encoding,
  130. self._controller_data,
  131. self._delay)
  132. async def async_added_to_hass(self):
  133. """Run when entity about to be added."""
  134. await super().async_added_to_hass()
  135. _LOGGER.debug(f"async_added_to_hass {self} {self.name} {self.supported_features}")
  136. last_state = await self.async_get_last_state()
  137. if last_state is not None:
  138. self._hvac_mode = last_state.state
  139. self._current_fan_mode = last_state.attributes['fan_mode']
  140. self._current_swing_mode = last_state.attributes.get('swing_mode')
  141. self._target_temperature = last_state.attributes['temperature']
  142. if 'last_on_operation' in last_state.attributes:
  143. self._last_on_operation = last_state.attributes['last_on_operation']
  144. if self._temperature_sensor:
  145. async_track_state_change(self.hass, self._temperature_sensor,
  146. self._async_temp_sensor_changed)
  147. temp_sensor_state = self.hass.states.get(self._temperature_sensor)
  148. if temp_sensor_state and temp_sensor_state.state != STATE_UNKNOWN:
  149. self._async_update_temp(temp_sensor_state)
  150. if self._humidity_sensor:
  151. async_track_state_change(self.hass, self._humidity_sensor,
  152. self._async_humidity_sensor_changed)
  153. humidity_sensor_state = self.hass.states.get(self._humidity_sensor)
  154. if humidity_sensor_state and humidity_sensor_state.state != STATE_UNKNOWN:
  155. self._async_update_humidity(humidity_sensor_state)
  156. if self._power_sensor:
  157. async_track_state_change(self.hass, self._power_sensor,
  158. self._async_power_sensor_changed)
  159. @property
  160. def unique_id(self):
  161. """Return a unique ID."""
  162. return self._unique_id
  163. @property
  164. def name(self):
  165. """Return the name of the climate device."""
  166. return self._name
  167. @property
  168. def state(self):
  169. """Return the current state."""
  170. if self.hvac_mode != HVACMode.OFF:
  171. return self.hvac_mode
  172. return HVACMode.OFF
  173. @property
  174. def temperature_unit(self):
  175. """Return the unit of measurement."""
  176. return self._unit
  177. @property
  178. def min_temp(self):
  179. """Return the polling state."""
  180. return self._min_temperature
  181. @property
  182. def max_temp(self):
  183. """Return the polling state."""
  184. return self._max_temperature
  185. @property
  186. def target_temperature(self):
  187. """Return the temperature we try to reach."""
  188. return self._target_temperature
  189. @property
  190. def target_temperature_step(self):
  191. """Return the supported step of target temperature."""
  192. return self._precision
  193. @property
  194. def hvac_modes(self):
  195. """Return the list of available operation modes."""
  196. return self._operation_modes
  197. @property
  198. def hvac_mode(self):
  199. """Return hvac mode ie. heat, cool."""
  200. return self._hvac_mode
  201. @property
  202. def last_on_operation(self):
  203. """Return the last non-idle operation ie. heat, cool."""
  204. return self._last_on_operation
  205. @property
  206. def fan_modes(self):
  207. """Return the list of available fan modes."""
  208. return self._fan_modes
  209. @property
  210. def fan_mode(self):
  211. """Return the fan setting."""
  212. return self._current_fan_mode
  213. @property
  214. def swing_modes(self):
  215. """Return the swing modes currently supported for this device."""
  216. return self._swing_modes
  217. @property
  218. def swing_mode(self):
  219. """Return the current swing mode."""
  220. return self._current_swing_mode
  221. @property
  222. def current_temperature(self):
  223. """Return the current temperature."""
  224. return self._current_temperature
  225. @property
  226. def current_humidity(self):
  227. """Return the current humidity."""
  228. return self._current_humidity
  229. @property
  230. def supported_features(self):
  231. """Return the list of supported features."""
  232. return self._support_flags
  233. @property
  234. def extra_state_attributes(self):
  235. """Platform specific attributes."""
  236. return {
  237. 'last_on_operation': self._last_on_operation,
  238. 'device_code': self._device_code,
  239. 'manufacturer': self._manufacturer,
  240. 'supported_models': self._supported_models,
  241. 'supported_controller': self._supported_controller,
  242. 'commands_encoding': self._commands_encoding
  243. }
  244. async def async_set_temperature(self, **kwargs):
  245. """Set new target temperatures."""
  246. hvac_mode = kwargs.get(ATTR_HVAC_MODE)
  247. temperature = kwargs.get(ATTR_TEMPERATURE)
  248. if temperature is None:
  249. return
  250. if temperature < self._min_temperature or temperature > self._max_temperature:
  251. _LOGGER.warning('The temperature value is out of min/max range')
  252. return
  253. if self._precision == PRECISION_WHOLE:
  254. self._target_temperature = round(temperature)
  255. else:
  256. self._target_temperature = round(temperature, 1)
  257. if hvac_mode:
  258. await self.async_set_hvac_mode(hvac_mode)
  259. return
  260. if not self._hvac_mode.lower() == HVACMode.OFF:
  261. await self.send_command()
  262. self.async_write_ha_state()
  263. async def async_set_hvac_mode(self, hvac_mode):
  264. """Set operation mode."""
  265. self._hvac_mode = hvac_mode
  266. if not hvac_mode == HVACMode.OFF:
  267. self._last_on_operation = hvac_mode
  268. await self.send_command()
  269. self.async_write_ha_state()
  270. async def async_set_fan_mode(self, fan_mode):
  271. """Set fan mode."""
  272. self._current_fan_mode = fan_mode
  273. if not self._hvac_mode.lower() == HVACMode.OFF:
  274. await self.send_command()
  275. self.async_write_ha_state()
  276. async def async_set_swing_mode(self, swing_mode):
  277. """Set swing mode."""
  278. self._current_swing_mode = swing_mode
  279. if not self._hvac_mode.lower() == HVACMode.OFF:
  280. await self.send_command()
  281. self.async_write_ha_state()
  282. async def async_turn_off(self):
  283. """Turn off."""
  284. await self.async_set_hvac_mode(HVACMode.OFF)
  285. async def async_turn_on(self):
  286. """Turn on."""
  287. if self._last_on_operation is not None:
  288. await self.async_set_hvac_mode(self._last_on_operation)
  289. else:
  290. await self.async_set_hvac_mode(self._operation_modes[1])
  291. async def send_command(self):
  292. async with self._temp_lock:
  293. try:
  294. self._on_by_remote = False
  295. operation_mode = self._hvac_mode
  296. fan_mode = self._current_fan_mode
  297. swing_mode = self._current_swing_mode
  298. target_temperature = '{0:g}'.format(self._target_temperature)
  299. if operation_mode.lower() == HVACMode.OFF:
  300. await self._controller.send(self._commands['off'])
  301. return
  302. if 'on' in self._commands:
  303. await self._controller.send(self._commands['on'])
  304. await asyncio.sleep(self._delay)
  305. if self._support_swing == True:
  306. await self._controller.send(
  307. self._commands[operation_mode][fan_mode][swing_mode][target_temperature])
  308. else:
  309. await self._controller.send(
  310. self._commands[operation_mode][fan_mode][target_temperature])
  311. except Exception as e:
  312. _LOGGER.exception(e)
  313. async def _async_temp_sensor_changed(self, entity_id, old_state, new_state):
  314. """Handle temperature sensor changes."""
  315. if new_state is None:
  316. return
  317. self._async_update_temp(new_state)
  318. self.async_write_ha_state()
  319. async def _async_humidity_sensor_changed(self, entity_id, old_state, new_state):
  320. """Handle humidity sensor changes."""
  321. if new_state is None:
  322. return
  323. self._async_update_humidity(new_state)
  324. self.async_write_ha_state()
  325. async def _async_power_sensor_changed(self, entity_id, old_state, new_state):
  326. """Handle power sensor changes."""
  327. if new_state is None:
  328. return
  329. if old_state is not None and new_state.state == old_state.state:
  330. return
  331. if new_state.state == STATE_ON and self._hvac_mode == HVACMode.OFF:
  332. self._on_by_remote = True
  333. if self._power_sensor_restore_state == True and self._last_on_operation is not None:
  334. self._hvac_mode = self._last_on_operation
  335. else:
  336. self._hvac_mode = STATE_ON
  337. self.async_write_ha_state()
  338. if new_state.state == STATE_OFF:
  339. self._on_by_remote = False
  340. if self._hvac_mode != HVACMode.OFF:
  341. self._hvac_mode = HVACMode.OFF
  342. self.async_write_ha_state()
  343. @callback
  344. def _async_update_temp(self, state):
  345. """Update thermostat with latest state from temperature sensor."""
  346. try:
  347. if state.state != STATE_UNKNOWN and state.state != STATE_UNAVAILABLE:
  348. self._current_temperature = float(state.state)
  349. except ValueError as ex:
  350. _LOGGER.error("Unable to update from temperature sensor: %s", ex)
  351. @callback
  352. def _async_update_humidity(self, state):
  353. """Update thermostat with latest state from humidity sensor."""
  354. try:
  355. if state.state != STATE_UNKNOWN and state.state != STATE_UNAVAILABLE:
  356. self._current_humidity = float(state.state)
  357. except ValueError as ex:
  358. _LOGGER.error("Unable to update from humidity sensor: %s", ex)