climate.py 16 KB

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