Ejemplo n.º 1
0
 async def async_step_user(self, user_input=None):
     errors = {}
     if user_input is not None:
         if user_input.get(CONF_HOST):
             self.host = user_input[CONF_HOST]
         token = user_input.get(CONF_TOKEN)
         device = MiioDevice(self.host, token)
         try:
             info = device.info()
         except:
             info = None
             errors['base'] = 'cannot_connect'
         _LOGGER.debug('Yeelink async_step_user %s', {
             'user_input': user_input,
             'info': info,
             'errors': errors,
         })
         if info is not None:
             unique_id = format_mac(info.mac_address)
             await self.async_set_unique_id(unique_id)
             self._abort_if_unique_id_configured()
             user_input['miio_info'] = dict(info.raw or {})
             return self.async_create_entry(
                 title=user_input.get(CONF_NAME),
                 data=user_input,
             )
     return self.async_show_form(
         step_id='user',
         data_schema=MIIO_CONFIG_SCHEMA,
         errors=errors,
     )
Ejemplo n.º 2
0
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Set up the sensor from config."""
    if DATA_KEY not in hass.data:
        hass.data[DATA_KEY] = {}

    host = config.get(CONF_HOST)
    token = config.get(CONF_TOKEN)

    _LOGGER.info("Initializing with host %s (token %s...)", host, token[:5])

    try:
        miio_device = Device(host, token)
        device_info = miio_device.info()
        model = device_info.model
        _LOGGER.info(
            "%s %s %s detected",
            model,
            device_info.firmware_version,
            device_info.hardware_version,
        )

        device = XiaomiMiioGenericDevice(miio_device, config, device_info)
    except DeviceException:
        raise PlatformNotReady

    hass.data[DATA_KEY][host] = device
    async_add_devices([device], update_before_add=True)

    @asyncio.coroutine
    def async_service_handler(service):
        """Map services to methods on XiaomiMiioDevice."""
        method = SERVICE_TO_METHOD.get(service.service)
        params = {
            key: value
            for key, value in service.data.items() if key != ATTR_ENTITY_ID
        }
        entity_ids = service.data.get(ATTR_ENTITY_ID)
        if entity_ids:
            devices = [
                device for device in hass.data[DATA_KEY].values()
                if device.entity_id in entity_ids
            ]
        else:
            devices = hass.data[DATA_KEY].values()

        update_tasks = []
        for device in devices:
            yield from getattr(device, method["method"])(**params)
            update_tasks.append(device.async_update_ha_state(True))

        if update_tasks:
            yield from asyncio.wait(update_tasks, loop=hass.loop)

    for service in SERVICE_TO_METHOD:
        schema = SERVICE_TO_METHOD[service].get("schema", SERVICE_SCHEMA)
        hass.services.async_register(DOMAIN,
                                     service,
                                     async_service_handler,
                                     schema=schema)
 def set_mode(**kwargs):
     """Set mode.设置自定义模式"""
     try:
         miio_device = Device(host, token)
         miio_device.send('set_mode',
                          [kwargs["id"], kwargs["heat"], kwargs["time"]])
     except DeviceException:
         raise PlatformNotReady
Ejemplo n.º 4
0
def test_unavailable_device_info_raises(mocker):
    send = mocker.patch("miio.Device.send", side_effect=PayloadDecodeException)
    d = Device("127.0.0.1", "68ffffffffffffffffffffffffffffff")

    with pytest.raises(DeviceInfoUnavailableException):
        d.info()

    assert send.call_count == 1
Ejemplo n.º 5
0
 def __init__(self, name, host, token):
     self._name = name
     self._device = Device(host, token)
     self._state = False
     self._state_attrs = {}
     device_info = self._device.info()
     self._unique_id = "{}-{}".format(device_info.model,
                                      device_info.mac_address)
Ejemplo n.º 6
0
class MrBondLight(Light):
    """Representation of MrBond Airer Light."""

    def __init__(self, name, host, token):
        """Initialize the light device."""
        self._name = name or host
        self._device = Device(host, token)
        self._state = None

    @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 is_on(self):
        """Return true if light is on."""
        return self._state

    async def async_turn_on(self, **kwargs):
        """Turn the light on."""
        if await self.try_command(self.on):
            self._state = True

    async def async_turn_off(self, **kwargs):
        """Turn the light off."""
        if await self.try_command(self.off):
            self._state = False

    async def async_update(self):
        """Fetch state from the device."""
        self._state = await self.try_command(self.status)

    async def try_command(self, func):
        """Call a miio device command handling error messages."""
        try:
            result = await self.hass.async_add_job(func)
            _LOGGER.debug("Response received from miio device: %s", result)
            return result
        except Exception as exc:
            #import traceback
            # _LOGGER.error(traceback.format_exc())
            _LOGGER.error("Error on command: %s", exc)
            return None

    def status(self):
        return self._device.send('get_prop', 'led') == ['1']

    def on(self):
        return self._device.send('set_led', [1]) == ['ok']

    def off(self):
        return self._device.send('set_led', [0]) == ['ok']
Ejemplo n.º 7
0
def test_unavailable_device_info_raises(mocker):
    """Make sure custom exception is raised if the info payload is invalid."""
    send = mocker.patch("miio.Device.send", side_effect=PayloadDecodeException)
    d = Device("127.0.0.1", "68ffffffffffffffffffffffffffffff")

    with pytest.raises(DeviceInfoUnavailableException):
        d.info()

    assert send.call_count == 1
Ejemplo n.º 8
0
 def __init__(self, name, host, token):
     self._name = name or host
     self._device = Device(host, token)
     self._status = {'dash_extra_forced': True,
                     'genie_deviceType': 'washmachine'}
     self._state = None
     self._skip_update = False
     self._dry_mode = 0
     self._appoint_time = 0
Ejemplo n.º 9
0
def test_missing_supported(mocker, caplog):
    """Make sure warning is logged if the device is unsupported for the class."""
    _ = mocker.patch("miio.Device.send")

    d = Device("127.0.0.1", "68ffffffffffffffffffffffffffffff")
    d._fetch_info()

    assert "Found an unsupported model" in caplog.text
    assert "for class 'Device'" in caplog.text
Ejemplo n.º 10
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Perform the setup for Xiaomi heaters."""
    host = config.get(CONF_HOST)
    name = config.get(CONF_NAME)
    token = config.get(CONF_TOKEN)
    model = config.get(CONF_MODEL)

    _LOGGER.info("Initializing Xiaomi heaters with host %s (token %s...)",
                 host, token[:5])

    devices = []
    unique_id = None

    try:
        device = Device(host, token)
        device_info = device.info()

        if model is None:

            model = device_info.model
            DEVICE_MODEL = model

        unique_id = "{}-{}".format(model, device_info.mac_address)
        _LOGGER.warning("%s %s %s detected", model,
                        device_info.firmware_version,
                        device_info.hardware_version)
        miHeater = MiHeater(device, name, model, unique_id, hass)
        devices.append(miHeater)
        add_devices(devices)

        async def set_room_temp(service):
            """Set room temp."""

            if DEVICE_MODEL == "zhimi.heater.mc2":
                aux = device.raw_command('get_properties', [{
                    "siid": 2,
                    "piid": 5
                }])
            elif DEVICE_MODEL == "zhimi.heater.zb1" or DEVICE_MODEL == "zhimi.heater.za2":
                aux = device.raw_command('get_properties', [{
                    "siid": 2,
                    "piid": 6
                }])
            else:
                _LOGGER.exception('Unsupported model: %s', DEVICE_MODEL)

            temperature = aux[0]["value"]
            await miHeater.async_set_temperature(temperature)

        hass.services.async_register(DOMAIN,
                                     SERVICE_SET_ROOM_TEMP,
                                     set_room_temp,
                                     schema=SET_ROOM_TEMP_SCHEMA)
    except DeviceException:
        _LOGGER.exception('Fail to setup Xiaomi heater')
        raise PlatformNotReady
Ejemplo n.º 11
0
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Set up the switch from config."""
    from miio import Device, DeviceException

    host = config.get(CONF_HOST)
    name = config.get(CONF_NAME)
    token = config.get(CONF_TOKEN)
    model = config.get(CONF_MODEL)

    _LOGGER.info("Initializing with host %s (token %s...)", host, token[:5])

    devices = []

    if model is None:
        try:
            miio_device = Device(host, token)
            device_info = miio_device.info()
            model = device_info.model
            _LOGGER.info("%s %s %s detected",
                         model,
                         device_info.firmware_version,
                         device_info.hardware_version)
        except DeviceException:
            raise PlatformNotReady

    if model in ['chuangmi.plug.v1']:
        from miio import PlugV1
        plug = PlugV1(host, token)

        # The device has two switchable channels (mains and a USB port).
        # A switch device per channel will be created.
        for channel_usb in [True, False]:
            device = ChuangMiPlugV1Switch(
                name, plug, model, channel_usb)
            devices.append(device)

    elif model in ['qmi.powerstrip.v1',
                   'zimi.powerstrip.v2']:
        from miio import PowerStrip
        plug = PowerStrip(host, token)
        device = XiaomiPowerStripSwitch(name, plug, model)
        devices.append(device)
    elif model in ['chuangmi.plug.m1',
                   'chuangmi.plug.v2']:
        from miio import Plug
        plug = Plug(host, token)
        device = XiaomiPlugGenericSwitch(name, plug, model)
        devices.append(device)
    else:
        _LOGGER.error(
            'Unsupported device found! Please create an issue at '
            'https://github.com/rytilahti/python-miio/issues '
            'and provide the following data: %s', model)
        return False

    async_add_devices(devices, update_before_add=True)
 def set_work(**kwargs):
     """Set work."""
     try:
         miio_device = Device(host, token)
         miio_device.send('set_work', [
             kwargs["status"], kwargs["id"], kwargs["keep_temp"],
             kwargs["keep_time"], kwargs["timestamp"]
         ])
     except DeviceException:
         raise PlatformNotReady
Ejemplo n.º 13
0
def test_model_autodetection(mocker):
    """Make sure info() gets called if the model is unknown."""
    info = mocker.patch("miio.Device._fetch_info")
    _ = mocker.patch("miio.Device.send")

    d = Device("127.0.0.1", "68ffffffffffffffffffffffffffffff")

    d.raw_command("cmd", {})

    info.assert_called()
Ejemplo n.º 14
0
def is_gw3(host: str, token: str) -> Optional[str]:
    try:
        device = Device(host, token)
        info = device.info()
        if info.model != 'lumi.gateway.mgl03':
            raise Exception(f"Wrong device model: {info.model}")
    except Exception as e:
        return str(e)

    return None
Ejemplo n.º 15
0
def test_get_properties_splitting(mocker, max_properties):
    properties = [i for i in range(20)]

    send = mocker.patch("miio.Device.send")
    d = Device("127.0.0.1", "68ffffffffffffffffffffffffffffff")
    d.get_properties(properties, max_properties=max_properties)

    if max_properties is None:
        max_properties = len(properties)
    assert send.call_count == math.ceil(len(properties) / max_properties)
Ejemplo n.º 16
0
def setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Perform the setup for Xiaomi heaters."""
    from miio import Device, DeviceException
    if DATA_KEY not in hass.data:
        hass.data[DATA_KEY] = {}

    host = config.get(CONF_HOST)
    name = config.get(CONF_NAME)
    token = config.get(CONF_TOKEN)

    _LOGGER.info("Initializing Xiaomi heaters with host %s (token %s...)", host, token[:5])

    try:
        device = Device(host, token)

        device_info = device.info()
        model = device_info.model
        unique_id = "{}-{}".format(model, device_info.mac_address)
        _LOGGER.info("%s %s %s detected",
                     model,
                     device_info.firmware_version,
                     device_info.hardware_version)
    except DeviceException:
        _LOGGER.exception('Fail to setup Xiaomi heater')
        raise PlatformNotReady
    miHeater = MiHeater(device, name, unique_id, hass)
    hass.data[DATA_KEY][host] = miHeater
    async_add_devices([miHeater], update_before_add=True)

    async def async_service_handler(service):
        """Map services to methods on XiaomiAirConditioningCompanion."""
        method = SERVICE_TO_METHOD.get(service.service)
        params = {key: value for key, value in service.data.items()
                  if key != ATTR_ENTITY_ID}
        entity_ids = service.data.get(ATTR_ENTITY_ID)
        if entity_ids:
            devices = [device for device in hass.data[DATA_KEY].values() if
                       device.entity_id in entity_ids]
        else:
            devices = hass.data[DATA_KEY].values()

        update_tasks = []
        for device in devices:
            if not hasattr(device, method['method']):
                continue
            await getattr(device, method['method'])(**params)
            update_tasks.append(device.async_update_ha_state(True))

        if update_tasks:
            await asyncio.wait(update_tasks, loop=hass.loop)

    for service in SERVICE_TO_METHOD:
        schema = SERVICE_TO_METHOD[service].get('schema', SERVICE_SCHEMA)
        hass.services.async_register(
            DOMAIN, service, async_service_handler, schema=schema)
async def async_setup_platform(hass,
                               config,
                               async_add_entities,
                               discovery_info=None):
    """Set up the Xiaomi Whale Smart Toilet device platform."""
    if DATA_KEY not in hass.data:
        hass.data[DATA_KEY] = {}

    host = config.get(CONF_HOST)
    name = config.get(CONF_NAME)
    token = config.get(CONF_TOKEN)
    model = config.get(CONF_MODEL)

    # Create handler
    _LOGGER.info("Initializing with host %s (token %s...)", host, token[:5])

    try:
        miio_device = Device(host, token)
        device_info = miio_device.info()
        model = device_info.model or model or MODEL_TOILETLID_XJX_TOILET_PRO
        unique_id = "{}-{}".format(model, device_info.mac_address)
    except DeviceException:
        raise PlatformNotReady

    toiletlid = Toiletlid(host, token, model=model)
    device = ToiletlidEntity(name, toiletlid, model, unique_id)
    hass.data[DATA_KEY][host] = device

    async_add_entities([device], update_before_add=True)

    async def async_service_handler(service):
        """Map services to methods on Xiaomi Whale Smart Toilet."""
        method = SERVICE_TO_METHOD.get(service.service)
        params = service.data.copy()
        entity_ids = params.pop(ATTR_ENTITY_ID, hass.data[DATA_KEY].values())
        update_tasks = []

        for device in filter(lambda x: x.entity_id in entity_ids,
                             hass.data[DATA_KEY].values()):
            if not hasattr(device, method["method"]):
                continue
            await getattr(device, method["method"])(**params)
            update_tasks.append(device.async_update_ha_state(True))

        if update_tasks:
            await asyncio.wait(update_tasks)

    for toiletlid_service in SERVICE_TO_METHOD:
        schema = SERVICE_TO_METHOD[toiletlid_service].get(
            "schema", TOILETLID_SERVICE_SCHEMA)
        hass.services.async_register(DOMAIN,
                                     toiletlid_service,
                                     async_service_handler,
                                     schema=schema)
Ejemplo n.º 18
0
def test_forced_model(mocker):
    """Make sure info() does not get called automatically if model is given."""
    info = mocker.patch("miio.Device.info")
    _ = mocker.patch("miio.Device.send")

    DUMMY_MODEL = "dummy.model"

    d = Device("127.0.0.1", "68ffffffffffffffffffffffffffffff", model=DUMMY_MODEL)
    d.raw_command("dummy", {})

    assert d.model == DUMMY_MODEL
    info.assert_not_called()
Ejemplo n.º 19
0
def setup(hass, config):
    """初始化小米净水器组件"""

    if DOMAIN not in hass.data:
        hass.data[DOMAIN] = {}

    host = config[DOMAIN][CONF_HOST]
    token = config[DOMAIN][CONF_TOKEN]
    name = config[DOMAIN][CONF_NAME]
    model = config[DOMAIN].get(CONF_MODEL)
    scan_interval = config[DOMAIN][CONF_SCAN_INTERVAL]

    if DATA_KEY not in hass.data:
        hass.data[DATA_KEY] = {}
        hass.data[DATA_KEY][host] = {}

    try:
        miio_device = Device(host, token)
        device_info = miio_device.info()
        model = device_info.model
        _LOGGER.info("发现净水器设备,型号[%s],软件版本[%s],硬件版本[%s]", model,
                     device_info.firmware_version,
                     device_info.hardware_version)
    except DeviceException:
        raise PlatformNotReady

    if model in SUPPORTED_MODELS:
        water_purifier = MiWaterPurifier(miio_device, name)
        _LOGGER.info("实例化小米净水器[%s]", name)
        hass.data[DOMAIN][host] = water_purifier
        for component in ['sensor']:
            discovery.load_platform(hass, component, DOMAIN, {}, config)
    else:
        _LOGGER.error("未支持设备型号[%s]", model)
        return False

    def update(event_time):
        """更新设备状态"""
        try:
            water_purifier.update()
            state = water_purifier.state
            hass.data[DATA_KEY][host][DATA_STATE] = state
            dispatcher_send(hass, '{}_updated'.format(DOMAIN), host)
        except DeviceException as ex:
            dispatcher_send(hass, '{}_unavailable'.format(DOMAIN), host)
            _LOGGER.error("获取净化器状态时异常[%s]", ex)

    update(utcnow())
    track_time_interval(hass, update, scan_interval)

    return True
def main():
    print('this message is from main function')
    device = Device(host, token)
    data = {}
    print('send get prop')
    #    params = {"tds_out", "temperature", "f1_totalflow", "f1_totaltime", "f1_usedflow", "f1_usedtime", "f2_totalflow", "f2_totaltime", "f2_usedflow", "f2_usedtime", "run_status", "rinse", "tds_warn_thd", "tds_out_avg" }
    properties = AVAILABLE_PROPERTIES_COMMON
    _props_per_request = 1
    _props = properties.copy()
    values = []
    while _props:
        status = device.send("get_prop", _props[:_props_per_request])
        _props[:] = _props[_props_per_request:]
        print('send get prop finished ', status)
Ejemplo n.º 21
0
    def __init__(self, host: str, token: str):
        super().__init__(daemon=True)

        self.host = host
        self.miio = Device(host, token)

        self.mqtt = Client()
        self.mqtt.on_connect = self.on_connect
        self.mqtt.on_disconnect = self.on_disconnect
        self.mqtt.on_message = self.on_message
        self.mqtt.connect_async(host)

        if isinstance(self.log, str):
            self.log = utils.get_logger(self.log)
Ejemplo n.º 22
0
async def async_setup_platform(hass,
                               config,
                               async_add_entities,
                               discovery_info=None):
    """Perform the setup for Xiaomi Airpurifier."""
    if DATA_KEY not in hass.data:
        hass.data[DATA_KEY] = {}

    host = config.get(CONF_HOST)
    name = config.get(CONF_NAME)
    token = config.get(CONF_TOKEN)

    _LOGGER.info(
        "Initializing Xiaomi airpurifier pro H with host %s (token %s...)",
        host, token[:5])

    devices = []
    try:
        device = Device(host, token)
        airPurifierproH = AirPurifierproH(device, name)
    except DeviceException:
        _LOGGER.exception('Fail to setup Xiaomi airpurifier pro H')
        raise PlatformNotReady

    hass.data[DATA_KEY][host] = airPurifierproH
    async_add_entities([airPurifierproH], update_before_add=True)

    async def async_service_handler(service):
        """Map services to methods on XiaomiAirPurifier."""
        method = SERVICE_TO_METHOD.get(service.service)
        params = {
            key: value
            for key, value in service.data.items() if key != ATTR_ENTITY_ID
        }
        entity_ids = service.data.get(ATTR_ENTITY_ID)
        if entity_ids:
            devices = [
                device for device in hass.data[DATA_KEY].values()
                if device.entity_id in entity_ids
            ]
        else:
            devices = hass.data[DATA_KEY].values()

        update_tasks = []
        for device in devices:
            if not hasattr(device, method["method"]):
                continue
            await getattr(device, method["method"])(**params)
            update_tasks.append(device.async_update_ha_state(True))

        if update_tasks:
            await asyncio.wait(update_tasks)

    for air_purifier_service in SERVICE_TO_METHOD:
        schema = SERVICE_TO_METHOD[air_purifier_service].get(
            "schema", AIRPURIFIER_SERVICE_SCHEMA)
        hass.services.async_register(DOMAIN,
                                     air_purifier_service,
                                     async_service_handler,
                                     schema=schema)
Ejemplo n.º 23
0
async def async_setup_entry(hass, config, async_add_entities, discovery_info=None):
    """Perform the setup for Xiaomi heaters."""
    if DATA_KEY not in hass.data:
        hass.data[DATA_KEY] = {}

    host = config.get(CONF_HOST)
    name = config.get(CONF_NAME)
    token = config.get(CONF_TOKEN)

    _LOGGER.info(
        "Initializing Xiaomi heaters with host %s (token %s...)", host, token[:5])
    unique_id = None

    try:
        miio_device = Device(host, token)
        device_info = await hass.async_add_executor_job(miio_device.info)
        model = device_info.model
        unique_id = f"{model}-{device_info.mac_address}"
        _LOGGER.info(
            "%s %s %s detected",
            model,
            device_info.firmware_version,
            device_info.hardware_version,
        )
    except DeviceException as ex:
        raise PlatformNotReady from ex
    
    device = MiHeater(name, miio_device, model, unique_id)
    hass.data[DATA_KEY][host] = device
    async_add_entities([device], update_before_add=True)
Ejemplo n.º 24
0
async def async_setup_platform(hass,
                               config,
                               async_add_entities,
                               discovery_info=None):
    """Set up the sensor from config."""

    host = config[CONF_HOST]
    token = config[CONF_TOKEN]
    name = config[CONF_NAME]

    _LOGGER.info("Initializing with host %s (token %s...)", host, token[:5])

    miio_device = Device(host, token)

    try:
        device_info = await hass.async_add_executor_job(miio_device.info)
    except DeviceException:
        raise PlatformNotReady

    model = device_info.model
    unique_id = f"{model}-{device_info.mac_address}"
    _LOGGER.debug(
        "%s %s %s detected",
        model,
        device_info.firmware_version,
        device_info.hardware_version,
    )
    device = AirMonitorB1(name, AirQualityMonitor(host, token, model=model),
                          unique_id)

    async_add_entities([device], update_before_add=True)
Ejemplo n.º 25
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Perform the setup for Yunmi Xiaomi water purifier."""
    host = config.get(CONF_HOST)
    name = config.get(CONF_NAME)
    token = config.get(CONF_TOKEN)

    _LOGGER.info(
        "Initializing Yunmi Xiaomi water purifier with host %s (token %s...)",
        host, token[:5])

    devices = []
    try:
        device = Device(host, token)
        waterPurifier = XiaomiWaterPurifier(device, name)
        devices.append(waterPurifier)
        devices.append(XiaomiWaterPurifierSensor(waterPurifier, RUN_STATUS))
        devices.append(XiaomiWaterPurifierSensor(waterPurifier, F1_REMAINING))
        devices.append(XiaomiWaterPurifierSensor(waterPurifier, F2_REMAINING))
        devices.append(XiaomiWaterPurifierSensor(waterPurifier, F3_REMAINING))
        devices.append(XiaomiWaterPurifierSensor(waterPurifier, TDS_IN))
        devices.append(XiaomiWaterPurifierSensor(waterPurifier, TDS_OUT))
        devices.append(XiaomiWaterPurifierSensor(waterPurifier, TEMPERATURE))
        devices.append(XiaomiWaterPurifierSensor(waterPurifier, RINSE))
        devices.append(XiaomiWaterPurifierSensor(waterPurifier, WATER_USED))
        devices.append(XiaomiWaterPurifierSensor(waterPurifier,
                                                 WATER_PURIFIED))
    except DeviceException:
        _LOGGER.exception('Fail to setup Yunmi Xiaomi water purifier')
        raise PlatformNotReady

    add_devices(devices)
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Perform the setup for Xiaomi water purifier."""

    host = config.get(CONF_HOST)
    name = config.get(CONF_NAME)
    token = config.get(CONF_TOKEN)

    _LOGGER.info("Initializing Xiaomi water purifier with host %s (token %s...)", host, token[:5])

    devices = []
    try:
        device = Device(host, token)
        waterPurifier = XiaomiWaterPurifier(device, name)
        devices.append(waterPurifier)
        devices.append(XiaomiWaterPurifierSensor(waterPurifier, TAP_WATER_QUALITY))
        devices.append(XiaomiWaterPurifierSensor(waterPurifier, FILTERED_WATER_QUALITY))
        devices.append(XiaomiWaterPurifierSensor(waterPurifier, PP_COTTON_FILTER_REMAINING))
        devices.append(XiaomiWaterPurifierSensor(waterPurifier, RO_FILTER_REMAINING))
        devices.append(XiaomiWaterPurifierSensor(waterPurifier, REAR_ACTIVE_CARBON_FILTER_REMAINING))
        devices.append(XiaomiWaterPurifierSensor(waterPurifier, TEMPERATURE))
#        devices.append(XiaomiWaterPurifierSensor(waterPurifier, RINSE))
#        devices.append(XiaomiWaterPurifierSensor(waterPurifier, TDS_WARN))
    except DeviceException:
        _LOGGER.exception('Fail to setup Xiaomi water purifier')
        raise PlatformNotReady

    add_devices(devices)
Ejemplo n.º 27
0
    async def async_connect_device(self, host, token):
        """Connect to the Xiaomi Device."""
        _LOGGER.debug("Initializing with host %s (token %s...)", host, token[:5])

        try:
            self._device = Device(host, token)
            # get the device info
            self._device_info = await self._hass.async_add_executor_job(
                self._device.info
            )
        except DeviceException as error:
            if isinstance(error.__cause__, ChecksumError):
                raise ConfigEntryAuthFailed(error) from error

            _LOGGER.error(
                "DeviceException during setup of xiaomi device with host %s: %s",
                host,
                error,
            )
            return False

        _LOGGER.debug(
            "%s %s %s detected",
            self._device_info.model,
            self._device_info.firmware_version,
            self._device_info.hardware_version,
        )
        return True
Ejemplo n.º 28
0
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Set up the light from config."""
    from miio import Device, DeviceException

    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])

    devices = []
    try:
        light = Device(host, token)
        device_info = light.info()
        _LOGGER.info("%s %s %s initialized",
                     device_info.model,
                     device_info.firmware_version,
                     device_info.hardware_version)

        if device_info.model == 'philips.light.sread1':
            from miio import PhilipsEyecare
            light = PhilipsEyecare(host, token)
            device = XiaomiPhilipsEyecareLamp(name, light, device_info)
            devices.append(device)
        elif device_info.model == 'philips.light.ceiling':
            from miio import Ceil
            light = Ceil(host, token)
            device = XiaomiPhilipsCeilingLamp(name, light, device_info)
            devices.append(device)
        elif device_info.model == 'philips.light.bulb':
            from miio import PhilipsBulb
            light = PhilipsBulb(host, token)
            device = XiaomiPhilipsLightBall(name, light, device_info)
            devices.append(device)
        else:
            _LOGGER.error(
                'Unsupported device found! Please create an issue at '
                'https://github.com/rytilahti/python-miio/issues '
                'and provide the following data: %s', device_info.model)

    except DeviceException:
        raise PlatformNotReady

    async_add_devices(devices, update_before_add=True)
Ejemplo n.º 29
0
def test_device_id_handshake(mocker):
    """Make sure send_handshake() gets called if did is unknown."""
    handshake = mocker.patch("miio.Device.send_handshake")
    _ = mocker.patch("miio.Device.send")

    d = Device("127.0.0.1", "68ffffffffffffffffffffffffffffff")

    d.device_id

    handshake.assert_called()
Ejemplo n.º 30
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    host = config.get(CONF_HOST)
    name = config.get(CONF_NAME)
    token = config.get(CONF_TOKEN)

    _LOGGER.info("Initializing Yeelink ven fan with host %s (token %s...)",
                 host, token[:5])

    devices = []
    try:
        device = Device(host, token)
        yeelinkvenfan = YeelinkVenFan(device, name)
        devices.append(yeelinkvenfan)
    except DeviceException:
        _LOGGER.exception('Fail to setup Yeelink ven fan')
        raise PlatformNotReady

    add_devices(devices)
    hass.data[YEELINKVEN_FAN_DEVICES] = devices

    def service_handle(service):
        params = {
            key: value
            for key, value in service.data.items() if key != ATTR_ENTITY_ID
        }
        entity_id = service.data[ATTR_ENTITY_ID]
        device = next((fan for fan in hass.data[YEELINKVEN_FAN_DEVICES]
                       if fan.entity_id == entity_id), None)
        if device is None:
            _LOGGER.warning("Unable to find Yeelink ven fan device %s",
                            str(entity_id))
            return

        if service.service == SERVICE_SET_ANGLE:
            device.set_angle(**params)

        if service.service == SERVICE_SET_ANION:
            device.set_anion(**params)

        if service.service == SERVICE_SET_INIT:
            device.set_init(**params)

    hass.services.register(DOMAIN,
                           SERVICE_SET_ANGLE,
                           service_handle,
                           schema=SERVICE_SCHEMA_ANGLE)
    hass.services.register(DOMAIN,
                           SERVICE_SET_ANION,
                           service_handle,
                           schema=SERVICE_SCHEMA_ANION)
    hass.services.register(DOMAIN,
                           SERVICE_SET_INIT,
                           service_handle,
                           schema=SERVICE_SCHEMA_INIT)
Ejemplo n.º 31
0
def test_device_id(mocker):
    """Make sure send_handshake() does not get called if did is already known."""
    handshake = mocker.patch("miio.Device.send_handshake")
    _ = mocker.patch("miio.Device.send")

    d = Device("127.0.0.1", "68ffffffffffffffffffffffffffffff")
    d._protocol._device_id = b"12345678"

    d.device_id

    handshake.assert_not_called()
Ejemplo n.º 32
0
async def async_setup_platform(hass, config, async_add_entities,
                               discovery_info=None):
    """Set up the switch from config."""
    from miio import Device, DeviceException
    if DATA_KEY not in hass.data:
        hass.data[DATA_KEY] = {}

    host = config.get(CONF_HOST)
    name = config.get(CONF_NAME)
    token = config.get(CONF_TOKEN)
    model = config.get(CONF_MODEL)

    _LOGGER.info("Initializing with host %s (token %s...)", host, token[:5])

    devices = []
    unique_id = None

    if model is None:
        try:
            miio_device = Device(host, token)
            device_info = miio_device.info()
            model = device_info.model
            unique_id = "{}-{}".format(model, device_info.mac_address)
            _LOGGER.info("%s %s %s detected",
                         model,
                         device_info.firmware_version,
                         device_info.hardware_version)
        except DeviceException:
            raise PlatformNotReady

    if model in ['chuangmi.plug.v1', 'chuangmi.plug.v3']:
        from miio import ChuangmiPlug
        plug = ChuangmiPlug(host, token, model=model)

        # The device has two switchable channels (mains and a USB port).
        # A switch device per channel will be created.
        for channel_usb in [True, False]:
            device = ChuangMiPlugSwitch(
                name, plug, model, unique_id, channel_usb)
            devices.append(device)
            hass.data[DATA_KEY][host] = device

    elif model in ['qmi.powerstrip.v1', 'zimi.powerstrip.v2']:
        from miio import PowerStrip
        plug = PowerStrip(host, token, model=model)
        device = XiaomiPowerStripSwitch(name, plug, model, unique_id)
        devices.append(device)
        hass.data[DATA_KEY][host] = device
    elif model in ['chuangmi.plug.m1', 'chuangmi.plug.v2']:
        from miio import ChuangmiPlug
        plug = ChuangmiPlug(host, token, model=model)
        device = XiaomiPlugGenericSwitch(name, plug, model, unique_id)
        devices.append(device)
        hass.data[DATA_KEY][host] = device
    else:
        _LOGGER.error(
            'Unsupported device found! Please create an issue at '
            'https://github.com/rytilahti/python-miio/issues '
            'and provide the following data: %s', model)
        return False

    async_add_entities(devices, update_before_add=True)

    async def async_service_handler(service):
        """Map services to methods on XiaomiPlugGenericSwitch."""
        method = SERVICE_TO_METHOD.get(service.service)
        params = {key: value for key, value in service.data.items()
                  if key != ATTR_ENTITY_ID}
        entity_ids = service.data.get(ATTR_ENTITY_ID)
        if entity_ids:
            devices = [device for device in hass.data[DATA_KEY].values() if
                       device.entity_id in entity_ids]
        else:
            devices = hass.data[DATA_KEY].values()

        update_tasks = []
        for device in devices:
            if not hasattr(device, method['method']):
                continue
            await getattr(device, method['method'])(**params)
            update_tasks.append(device.async_update_ha_state(True))

        if update_tasks:
            await asyncio.wait(update_tasks, loop=hass.loop)

    for plug_service in SERVICE_TO_METHOD:
        schema = SERVICE_TO_METHOD[plug_service].get('schema', SERVICE_SCHEMA)
        hass.services.async_register(
            DOMAIN, plug_service, async_service_handler, schema=schema)
Ejemplo n.º 33
0
async def async_setup_platform(hass, config, async_add_devices,
                               discovery_info=None):
    """Set up the miio fan device from config."""
    from miio import Device, DeviceException
    if DATA_KEY not in hass.data:
        hass.data[DATA_KEY] = {}

    host = config.get(CONF_HOST)
    name = config.get(CONF_NAME)
    token = config.get(CONF_TOKEN)
    model = config.get(CONF_MODEL)

    _LOGGER.info("Initializing with host %s (token %s...)", host, token[:5])
    unique_id = None

    if model is None:
        try:
            miio_device = Device(host, token)
            device_info = miio_device.info()
            model = device_info.model
            unique_id = "{}-{}".format(model, device_info.mac_address)
            _LOGGER.info("%s %s %s detected",
                         model,
                         device_info.firmware_version,
                         device_info.hardware_version)
        except DeviceException:
            raise PlatformNotReady

    if model.startswith('zhimi.airpurifier.'):
        from miio import AirPurifier
        air_purifier = AirPurifier(host, token)
        device = XiaomiAirPurifier(name, air_purifier, model, unique_id)
    elif model.startswith('zhimi.humidifier.'):
        from miio import AirHumidifier
        air_humidifier = AirHumidifier(host, token)
        device = XiaomiAirHumidifier(name, air_humidifier, model, unique_id)
    else:
        _LOGGER.error(
            'Unsupported device found! Please create an issue at '
            'https://github.com/syssi/xiaomi_airpurifier/issues '
            'and provide the following data: %s', model)
        return False

    hass.data[DATA_KEY][host] = device
    async_add_devices([device], update_before_add=True)

    async def async_service_handler(service):
        """Map services to methods on XiaomiAirPurifier."""
        method = SERVICE_TO_METHOD.get(service.service)
        params = {key: value for key, value in service.data.items()
                  if key != ATTR_ENTITY_ID}
        entity_ids = service.data.get(ATTR_ENTITY_ID)
        if entity_ids:
            devices = [device for device in hass.data[DATA_KEY].values() if
                       device.entity_id in entity_ids]
        else:
            devices = hass.data[DATA_KEY].values()

        update_tasks = []
        for device in devices:
            if not hasattr(device, method['method']):
                continue
            await getattr(device, method['method'])(**params)
            update_tasks.append(device.async_update_ha_state(True))

        if update_tasks:
            await asyncio.wait(update_tasks, loop=hass.loop)

    for air_purifier_service in SERVICE_TO_METHOD:
        schema = SERVICE_TO_METHOD[air_purifier_service].get(
            'schema', AIRPURIFIER_SERVICE_SCHEMA)
        hass.services.async_register(
            DOMAIN, air_purifier_service, async_service_handler, schema=schema)
Ejemplo n.º 34
0
async def async_setup_platform(hass, config, async_add_entities,
                               discovery_info=None):
    """Set up the light from config."""
    from miio import Device, DeviceException
    if DATA_KEY not in hass.data:
        hass.data[DATA_KEY] = {}

    host = config.get(CONF_HOST)
    name = config.get(CONF_NAME)
    token = config.get(CONF_TOKEN)
    model = config.get(CONF_MODEL)

    _LOGGER.info("Initializing with host %s (token %s...)", host, token[:5])

    devices = []
    unique_id = None

    if model is None:
        try:
            miio_device = Device(host, token)
            device_info = miio_device.info()
            model = device_info.model
            unique_id = "{}-{}".format(model, device_info.mac_address)
            _LOGGER.info("%s %s %s detected",
                         model,
                         device_info.firmware_version,
                         device_info.hardware_version)
        except DeviceException:
            raise PlatformNotReady

    if model == 'philips.light.sread1':
        from miio import PhilipsEyecare
        light = PhilipsEyecare(host, token)
        primary_device = XiaomiPhilipsEyecareLamp(
            name, light, model, unique_id)
        devices.append(primary_device)
        hass.data[DATA_KEY][host] = primary_device

        secondary_device = XiaomiPhilipsEyecareLampAmbientLight(
            name, light, model, unique_id)
        devices.append(secondary_device)
        # The ambient light doesn't expose additional services.
        # A hass.data[DATA_KEY] entry isn't needed.
    elif model in ['philips.light.ceiling', 'philips.light.zyceiling']:
        from miio import Ceil
        light = Ceil(host, token)
        device = XiaomiPhilipsCeilingLamp(name, light, model, unique_id)
        devices.append(device)
        hass.data[DATA_KEY][host] = device
    elif model == 'philips.light.moonlight':
        from miio import PhilipsMoonlight
        light = PhilipsMoonlight(host, token)
        device = XiaomiPhilipsMoonlightLamp(name, light, model, unique_id)
        devices.append(device)
        hass.data[DATA_KEY][host] = device
    elif model in ['philips.light.bulb',
                   'philips.light.candle',
                   'philips.light.candle2',
                   'philips.light.downlight']:
        from miio import PhilipsBulb
        light = PhilipsBulb(host, token)
        device = XiaomiPhilipsBulb(name, light, model, unique_id)
        devices.append(device)
        hass.data[DATA_KEY][host] = device
    elif model == 'philips.light.mono1':
        from miio import PhilipsBulb
        light = PhilipsBulb(host, token)
        device = XiaomiPhilipsGenericLight(name, light, model, unique_id)
        devices.append(device)
        hass.data[DATA_KEY][host] = device
    else:
        _LOGGER.error(
            'Unsupported device found! Please create an issue at '
            'https://github.com/syssi/philipslight/issues '
            'and provide the following data: %s', model)
        return False

    async_add_entities(devices, update_before_add=True)

    async def async_service_handler(service):
        """Map services to methods on Xiaomi Philips Lights."""
        method = SERVICE_TO_METHOD.get(service.service)
        params = {key: value for key, value in service.data.items()
                  if key != ATTR_ENTITY_ID}
        entity_ids = service.data.get(ATTR_ENTITY_ID)
        if entity_ids:
            target_devices = [dev for dev in hass.data[DATA_KEY].values()
                              if dev.entity_id in entity_ids]
        else:
            target_devices = hass.data[DATA_KEY].values()

        update_tasks = []
        for target_device in target_devices:
            if not hasattr(target_device, method['method']):
                continue
            await getattr(target_device, method['method'])(**params)
            update_tasks.append(target_device.async_update_ha_state(True))

        if update_tasks:
            await asyncio.wait(update_tasks, loop=hass.loop)

    for xiaomi_miio_service in SERVICE_TO_METHOD:
        schema = SERVICE_TO_METHOD[xiaomi_miio_service].get(
            'schema', XIAOMI_MIIO_SERVICE_SCHEMA)
        hass.services.async_register(
            DOMAIN, xiaomi_miio_service, async_service_handler, schema=schema)
Ejemplo n.º 35
0
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Set up the light from config."""
    from miio import Device, 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:
        light = Device(host, token)
        device_info = light.info()
        _LOGGER.info("%s %s %s initialized",
                     device_info.model,
                     device_info.firmware_version,
                     device_info.hardware_version)

        if device_info.model == 'philips.light.sread1':
            from miio import PhilipsEyecare
            light = PhilipsEyecare(host, token)
            device = XiaomiPhilipsEyecareLamp(name, light, device_info)
        elif device_info.model == 'philips.light.ceiling':
            from miio import Ceil
            light = Ceil(host, token)
            device = XiaomiPhilipsCeilingLamp(name, light, device_info)
        elif device_info.model == 'philips.light.bulb':
            from miio import PhilipsBulb
            light = PhilipsBulb(host, token)
            device = XiaomiPhilipsLightBall(name, light, device_info)
        else:
            _LOGGER.error(
                'Unsupported device found! Please create an issue at '
                'https://github.com/rytilahti/python-miio/issues '
                'and provide the following data: %s', device_info.model)
            return False

    except DeviceException:
        raise PlatformNotReady

    hass.data[PLATFORM][host] = device
    async_add_devices([device], update_before_add=True)

    @asyncio.coroutine
    def async_service_handler(service):
        """Map services to methods on Xiaomi Philips Lights."""
        method = SERVICE_TO_METHOD.get(service.service)
        params = {key: value for key, value in service.data.items()
                  if key != ATTR_ENTITY_ID}
        entity_ids = service.data.get(ATTR_ENTITY_ID)
        if entity_ids:
            target_devices = [dev for dev in hass.data[PLATFORM].values()
                              if dev.entity_id in entity_ids]
        else:
            target_devices = hass.data[PLATFORM].values()

        update_tasks = []
        for target_device in target_devices:
            yield from getattr(target_device, method['method'])(**params)
            update_tasks.append(target_device.async_update_ha_state(True))

        if update_tasks:
            yield from asyncio.wait(update_tasks, loop=hass.loop)

    for xiaomi_miio_service in SERVICE_TO_METHOD:
        schema = SERVICE_TO_METHOD[xiaomi_miio_service].get(
            'schema', XIAOMI_MIIO_SERVICE_SCHEMA)
        hass.services.async_register(
            DOMAIN, xiaomi_miio_service, async_service_handler, schema=schema)