ââ"
Support for Xiaomi Mi Air Humidifier
ââ"
import asyncio
from functools import partial
import logging
import os
import voluptuous as vol
from homeassistant.helpers.entity import ToggleEntity
from homeassistant.components.fan import (FanEntity, PLATFORM_SCHEMA,
SUPPORT_SET_SPEED, DOMAIN)
from homeassistant.config import load_yaml_config_file
from homeassistant.const import (CONF_NAME, CONF_HOST, CONF_TOKEN,
ATTR_ENTITY_ID, )
from homeassistant.exceptions import PlatformNotReady
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(name)
DEFAULT_NAME = âXiaomi Air Humidifierâ
PLATFORM = âxiaomi_airhumidifierâ
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_TOKEN): vol.All(cv.string, vol.Length(min=32, max=32)),
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
})
REQUIREMENTS = [âpython-miio==0.3.3â]
ATTR_TEMPERATURE = âtemperatureâ
ATTR_HUMIDITY = âhumidityâ
ATTR_MODE = âmodeâ
SUCCESS = [âokâ]
pylint: disable=unused-argument
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
âââSet up the air humidifier from config.â""
from miio import AirHumidifier, DeviceException
if PLATFORM not in hass.data:
hass.data[PLATFORM] = {}
host = config.get(CONF_HOST)
name = config.get(CONF_NAME)
token = config.get(CONF_TOKEN)
_LOGGER.info("Initializing with host %s (token %s...)", host, token[:5])
try:
air_humidifier = AirHumidifier(host, token)
xiaomi_air_humidifier = XiaomiAirHumidifier(name, air_humidifier)
hass.data[PLATFORM][host] = xiaomi_air_humidifier
except DeviceException:
raise PlatformNotReady
async_add_devices([xiaomi_air_humidifier], update_before_add=True)
class XiaomiAirHumidifier(FanEntity):
âââRepresentation of a Xiaomi Air Humidifier.â""
def __init__(self, name, air_humidifier):
"""Initialize the air humidifier."""
self._name = name
self._air_humidifier = air_humidifier
self._state = None
self._state_attrs = {
ATTR_TEMPERATURE: None,
ATTR_HUMIDITY: None,
ATTR_MODE: None,
}
@property
def supported_features(self):
"""Flag supported features."""
return SUPPORT_SET_SPEED
@property
def should_poll(self):
"""Poll the fan."""
return True
@property
def name(self):
"""Return the name of the device if any."""
return self._name
@property
def available(self):
"""Return true when state is known."""
return self._state is not None
@property
def device_state_attributes(self):
"""Return the state attributes of the device."""
return self._state_attrs
@property
def is_on(self):
"""Return true if fan is on."""
return self._state
@asyncio.coroutine
def _try_command(self, mask_error, func, *args, **kwargs):
"""Call a air humidifier command handling error messages."""
from miio import DeviceException
try:
result = yield from self.hass.async_add_job(
partial(func, *args, **kwargs))
_LOGGER.debug("Response received from air humidifier: %s", result)
return result == SUCCESS
except DeviceException as exc:
_LOGGER.error(mask_error, exc)
return False
@asyncio.coroutine
def async_turn_on(self: ToggleEntity, speed: str=None, **kwargs) -> None:
"""Turn the fan on."""
if speed:
# If operation mode was set the device must not be turned on.
yield from self.async_set_speed(speed)
return
yield from self._try_command(
"Turning the air humidifier on failed.", self._air_humidifier.on)
@asyncio.coroutine
def async_turn_off(self: ToggleEntity, **kwargs) -> None:
"""Turn the fan off."""
yield from self._try_command(
"Turning the air humidifier off failed.", self._air_humidifier.off)
@asyncio.coroutine
def async_update(self):
"""Fetch state from the device."""
from miio import DeviceException
try:
state = yield from self.hass.async_add_job(
self._air_humidifier.status)
_LOGGER.debug("Got new state: %s", state)
self._state = state.is_on
self._state_attrs = {
ATTR_TEMPERATURE: state.temperature,
ATTR_HUMIDITY: state.humidity,
ATTR_MODE: state.mode.value
}
except DeviceException as ex:
_LOGGER.error("Got exception while fetching the state: %s", ex)
@property
def speed_list(self: ToggleEntity) -> list:
"""Get the list of available speeds."""
from miio.airhumidifier import OperationMode
return [mode.name for mode in OperationMode]
@property
def speed(self):
"""Return the current speed."""
if self._state:
from miio.airhumidifier import OperationMode
return OperationMode(self._state_attrs[ATTR_MODE]).name
return None
@asyncio.coroutine
def async_set_speed(self: ToggleEntity, speed: str) -> None:
"""Set the speed of the fan."""
_LOGGER.debug("Setting the operation mode to: " + speed)
from miio.airhumidifier import OperationMode
yield from self._try_command(
"Setting operation mode of the air humidifier failed.",
self._air_humidifier.set_mode, OperationMode[speed])
from HA 0.61.0 the servicess are not working, so I removed all service in the code and using upper code as custom_components.
Also I wanna let you know that there is no LED Brigtness in Air Purifier Pro. I am also using it after removing the service"LED Brightness" in HA 0.61.1