Exemplo n.º 1
0
    def miio_connect(self):
        if self.discovered: return True

        global ir

        if len(self.IP) > 0:
            try:
                Domoticz.Log(
                    'Attempt to connect to Chuangmi IR device with IP: {0} and token: {1}'
                    .format(self.IP, self.token))

                ir = ChuangmiIr(self.IP, self.token)
                info = ir.info()

                self.discovered = True
                Domoticz.Log('Connected.')
                return self.discovered

            except Exception as e:
                Domoticz.Log(
                    'Could not connect to {0} with IP {1}, check IP and Token.'
                    .format(Parameters['Name'], self.IP))
Exemplo n.º 2
0
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Set up the Xiaomi IR Remote (Chuangmi IR) platform."""
    from miio import ChuangmiIr, DeviceException

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

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

    # The Chuang Mi IR Remote Controller wants to be re-discovered every
    # 5 minutes. As long as polling is disabled the device should be
    # re-discovered (lazy_discover=False) in front of every command.
    device = ChuangmiIr(host, token, lazy_discover=False)

    # Check that we can communicate with device.
    try:
        device.info()
    except DeviceException as ex:
        _LOGGER.error("Token not accepted by device : %s", ex)
        return

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

    friendly_name = config.get(CONF_NAME,
                               "xiaomi_miio_" + host.replace('.', '_'))
    slot = config.get(CONF_SLOT)
    timeout = config.get(CONF_TIMEOUT)

    hidden = config.get(ATTR_HIDDEN)

    xiaomi_miio_remote = XiaomiMiioRemote(friendly_name, device, slot, timeout,
                                          hidden, config.get(CONF_COMMANDS))

    hass.data[DATA_KEY][host] = xiaomi_miio_remote

    async_add_devices([xiaomi_miio_remote])

    @asyncio.coroutine
    def async_service_handler(service):
        """Handle a learn command."""
        if service.service != SERVICE_LEARN:
            _LOGGER.error("We should not handle service: %s", service.service)
            return

        entity_id = service.data.get(ATTR_ENTITY_ID)
        entity = None
        for remote in hass.data[DATA_KEY].values():
            if remote.entity_id == entity_id:
                entity = remote

        if not entity:
            _LOGGER.error("entity_id: '%s' not found", entity_id)
            return

        device = entity.device

        slot = service.data.get(CONF_SLOT, entity.slot)

        yield from hass.async_add_job(device.learn, slot)

        timeout = service.data.get(CONF_TIMEOUT, entity.timeout)

        _LOGGER.info("Press the key you want Home Assistant to learn")
        start_time = utcnow()
        while (utcnow() - start_time) < timedelta(seconds=timeout):
            message = yield from hass.async_add_job(device.read, slot)
            _LOGGER.debug("Message recieved from device: '%s'", message)

            if 'code' in message and message['code']:
                log_msg = "Received command is: {}".format(message['code'])
                _LOGGER.info(log_msg)
                hass.components.persistent_notification.async_create(
                    log_msg, title='Xiaomi Miio Remote')
                return

            if ('error' in message
                    and message['error']['message'] == "learn timeout"):
                yield from hass.async_add_job(device.learn, slot)

            yield from asyncio.sleep(1, loop=hass.loop)

        _LOGGER.error("Timeout. No infrared command captured")
        hass.components.persistent_notification.async_create(
            "Timeout. No infrared command captured",
            title='Xiaomi Miio Remote')

    hass.services.async_register(DOMAIN,
                                 SERVICE_LEARN,
                                 async_service_handler,
                                 schema=LEARN_COMMAND_SCHEMA)
Exemplo n.º 3
0
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Set up the Xiaomi IR Remote (Chuangmi IR) platform."""
    from miio import ChuangmiIr, DeviceException

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

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

    # The Chuang Mi IR Remote Controller wants to be re-discovered every
    # 5 minutes. As long as polling is disabled the device should be
    # re-discovered (lazy_discover=False) in front of every command.
    device = ChuangmiIr(host, token, lazy_discover=False)

    # Check that we can communicate with device.
    try:
        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 as ex:
        _LOGGER.error("Device unavailable or token incorrect: %s", ex)
        raise PlatformNotReady

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

    friendly_name = config.get(CONF_NAME, "xiaomi_miio_" +
                               host.replace('.', '_'))
    slot = config.get(CONF_SLOT)
    timeout = config.get(CONF_TIMEOUT)

    hidden = config.get(ATTR_HIDDEN)

    xiaomi_miio_remote = XiaomiMiioRemote(friendly_name, device, unique_id,
                                          slot, timeout, hidden,
                                          config.get(CONF_COMMANDS))

    hass.data[DATA_KEY][host] = xiaomi_miio_remote

    async_add_devices([xiaomi_miio_remote])

    @asyncio.coroutine
    def async_service_handler(service):
        """Handle a learn command."""
        if service.service != SERVICE_LEARN:
            _LOGGER.error("We should not handle service: %s", service.service)
            return

        entity_id = service.data.get(ATTR_ENTITY_ID)
        entity = None
        for remote in hass.data[DATA_KEY].values():
            if remote.entity_id == entity_id:
                entity = remote

        if not entity:
            _LOGGER.error("entity_id: '%s' not found", entity_id)
            return

        device = entity.device

        slot = service.data.get(CONF_SLOT, entity.slot)

        yield from hass.async_add_job(device.learn, slot)

        timeout = service.data.get(CONF_TIMEOUT, entity.timeout)

        _LOGGER.info("Press the key you want Home Assistant to learn")
        start_time = utcnow()
        while (utcnow() - start_time) < timedelta(seconds=timeout):
            message = yield from hass.async_add_job(
                device.read, slot)
            _LOGGER.debug("Message received from device: '%s'", message)

            if 'code' in message and message['code']:
                log_msg = "Received command is: {}".format(message['code'])
                _LOGGER.info(log_msg)
                hass.components.persistent_notification.async_create(
                    log_msg, title='Xiaomi Miio Remote')
                return

            if ('error' in message and
                    message['error']['message'] == "learn timeout"):
                yield from hass.async_add_job(device.learn, slot)

            yield from asyncio.sleep(1, loop=hass.loop)

        _LOGGER.error("Timeout. No infrared command captured")
        hass.components.persistent_notification.async_create(
            "Timeout. No infrared command captured",
            title='Xiaomi Miio Remote')

    hass.services.async_register(DOMAIN, SERVICE_LEARN, async_service_handler,
                                 schema=LEARN_COMMAND_SCHEMA)
Exemplo n.º 4
0
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Set up the Xiaomi IR Remote (Chuangmi IR) platform."""
    from miio import ChuangmiIr, DeviceException

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

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

    # Check that we can communicate with device.
    try:
        device.info()
    except DeviceException as ex:
        _LOGGER.error("Token not accepted by device : %s", ex)
        return

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

    friendly_name = config.get(CONF_NAME, "xiaomi_miio_" +
                               host.replace('.', '_'))
    slot = config.get(CONF_SLOT)
    timeout = config.get(CONF_TIMEOUT)

    hidden = config.get(ATTR_HIDDEN)

    xiaomi_miio_remote = XiaomiMiioRemote(
        friendly_name, device, slot, timeout,
        hidden, config.get(CONF_COMMANDS))

    hass.data[PLATFORM][host] = xiaomi_miio_remote

    async_add_devices([xiaomi_miio_remote])

    @asyncio.coroutine
    def async_service_handler(service):
        """Handle a learn command."""
        if service.service != SERVICE_LEARN:
            _LOGGER.error("We should not handle service: %s", service.service)
            return

        entity_id = service.data.get(ATTR_ENTITY_ID)
        entity = None
        for remote in hass.data[PLATFORM].values():
            if remote.entity_id == entity_id:
                entity = remote

        if not entity:
            _LOGGER.error("entity_id: '%s' not found", entity_id)
            return

        device = entity.device

        slot = service.data.get(CONF_SLOT, entity.slot)

        yield from hass.async_add_job(device.learn, slot)

        timeout = service.data.get(CONF_TIMEOUT, entity.timeout)

        _LOGGER.info("Press the key you want Home Assistant to learn")
        start_time = utcnow()
        while (utcnow() - start_time) < timedelta(seconds=timeout):
            message = yield from hass.async_add_job(
                device.read, slot)
            _LOGGER.debug("Message recieved from device: '%s'", message)

            if 'code' in message and message['code']:
                log_msg = "Received command is: {}".format(message['code'])
                _LOGGER.info(log_msg)
                hass.components.persistent_notification.async_create(
                    log_msg, title='Xiaomi Miio Remote')
                return

            if ('error' in message and
                    message['error']['message'] == "learn timeout"):
                yield from hass.async_add_job(device.learn, slot)

            yield from asyncio.sleep(1, loop=hass.loop)

        _LOGGER.error("Timeout. No infrared command captured")
        hass.components.persistent_notification.async_create(
            "Timeout. No infrared command captured",
            title='Xiaomi Miio Remote')

    hass.services.async_register(DOMAIN, SERVICE_LEARN, async_service_handler,
                                 schema=LEARN_COMMAND_SCHEMA)
Exemplo n.º 5
0
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
    """Set up the Xiaomi IR Remote (Chuangmi IR) platform."""
    from miio import ChuangmiIr, DeviceException

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

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

    # The Chuang Mi IR Remote Controller wants to be re-discovered every
    # 5 minutes. As long as polling is disabled the device should be
    # re-discovered (lazy_discover=False) in front of every command.
    device = ChuangmiIr(host, token, lazy_discover=False)

    # Check that we can communicate with device.
    try:
        device_info = 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:
        _LOGGER.error("Device unavailable or token incorrect: %s", ex)
        raise PlatformNotReady

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

    friendly_name = config.get(CONF_NAME, "xiaomi_miio_" + host.replace(".", "_"))
    slot = config.get(CONF_SLOT)
    timeout = config.get(CONF_TIMEOUT)

    hidden = config.get(ATTR_HIDDEN)

    xiaomi_miio_remote = XiaomiMiioRemote(
        friendly_name,
        device,
        unique_id,
        slot,
        timeout,
        hidden,
        config.get(CONF_COMMANDS),
    )

    hass.data[DATA_KEY][host] = xiaomi_miio_remote

    async_add_entities([xiaomi_miio_remote])

    async def async_service_handler(service):
        """Handle a learn command."""
        if service.service != SERVICE_LEARN:
            _LOGGER.error("We should not handle service: %s", service.service)
            return

        entity_id = service.data.get(ATTR_ENTITY_ID)
        entity = None
        for remote in hass.data[DATA_KEY].values():
            if remote.entity_id == entity_id:
                entity = remote

        if not entity:
            _LOGGER.error("entity_id: '%s' not found", entity_id)
            return

        device = entity.device

        slot = service.data.get(CONF_SLOT, entity.slot)

        await hass.async_add_executor_job(device.learn, slot)

        timeout = service.data.get(CONF_TIMEOUT, entity.timeout)

        _LOGGER.info("Press the key you want Home Assistant to learn")
        start_time = utcnow()
        while (utcnow() - start_time) < timedelta(seconds=timeout):
            message = await hass.async_add_executor_job(device.read, slot)
            _LOGGER.debug("Message received from device: '%s'", message)

            if "code" in message and message["code"]:
                log_msg = "Received command is: {}".format(message["code"])
                _LOGGER.info(log_msg)
                hass.components.persistent_notification.async_create(
                    log_msg, title="Xiaomi Miio Remote"
                )
                return

            if "error" in message and message["error"]["message"] == "learn timeout":
                await hass.async_add_executor_job(device.learn, slot)

            await asyncio.sleep(1)

        _LOGGER.error("Timeout. No infrared command captured")
        hass.components.persistent_notification.async_create(
            "Timeout. No infrared command captured", title="Xiaomi Miio Remote"
        )

    hass.services.async_register(
        DOMAIN, SERVICE_LEARN, async_service_handler, schema=LEARN_COMMAND_SCHEMA
    )
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    """Set up the Broadlink IR Climate platform."""
    name = config.get(CONF_NAME)
    host = config.get(CONF_HOST)
    token = config.get(CONF_TOKEN)

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

    from miio import ChuangmiIr, DeviceException
    # The Chuang Mi IR Remote Controller wants to be re-discovered every
    # 5 minutes. As long as polling is disabled the device should be
    # re-discovered (lazy_discover=False) in front of every command.
    device = ChuangmiIr(host, token, lazy_discover=False)

    # Check that we can communicate with device.
    try:
        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 as ex:
        _LOGGER.error("Device unavailable or token incorrect: %s", ex)
        raise PlatformNotReady

    min_temp = config.get(CONF_MIN_TEMP)
    max_temp = config.get(CONF_MAX_TEMP)
    target_temp = config.get(CONF_TARGET_TEMP)
    temp_sensor_entity_id = config.get(CONF_TEMP_SENSOR)
    operation_list = config.get(CONF_CUSTOMIZE).get(
        CONF_OPERATIONS, []) or DEFAULT_OPERATION_LIST
    operation_list.append(STATE_OFF)
    fan_list = config.get(CONF_CUSTOMIZE).get(CONF_FAN_MODES,
                                              []) or DEFAULT_FAN_MODE_LIST
    default_operation = config.get(CONF_DEFAULT_OPERATION)
    default_fan_mode = config.get(CONF_DEFAULT_FAN_MODE)

    default_operation_from_idle = config.get(CONF_DEFAULT_OPERATION_FROM_IDLE)

    ircodes_ini_file = config.get(CONF_IRCODES_INI)

    if ircodes_ini_file.startswith("/"):
        ircodes_ini_file = ircodes_ini_file[1:]

    ircodes_ini_path = hass.config.path(ircodes_ini_file)

    if os.path.exists(ircodes_ini_path):
        ircodes_ini = ConfigParser()
        ircodes_ini.read(ircodes_ini_path)
    else:
        _LOGGER.error("The ini file was not found. (" + ircodes_ini_path + ")")
        return

    async_add_devices([
        XiaomiIRClimate(hass, name, device, ircodes_ini, min_temp, max_temp,
                        target_temp, temp_sensor_entity_id, operation_list,
                        fan_list, default_operation, default_fan_mode,
                        default_operation_from_idle)
    ])
Exemplo n.º 7
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the smart mi fan platform."""
    from miio import ChuangmiIr, DeviceException
    host = config.get(CONF_HOST)
    token = config.get(CONF_TOKEN)
    devices = config.get(CONF_SWITCHES, {})
    retries = config.get(CONF_RETRIES)
    persistent_notification = loader.get_component('persistent_notification')

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

    try:
        # The Chuang Mi IR Remote Controller wants to be re-discovered every
        # 5 minutes. As long as polling is disabled the device should be
        # re-discovered (lazy_discover=False) in front of every command.
        ir_remote = ChuangmiIr(host, token, lazy_discover=False)
        device_info = ir_remote.info()
    except DeviceException:
        _LOGGER.info("Connection failed.")
        raise PlatformNotReady

    @asyncio.coroutine
    def _learn_command(call):

        key = randint(1, 1000000)
        ir_remote.learn(key)

        _LOGGER.info(
            "Press the key to capture of your remote control")
        start_time = utcnow()
        while (utcnow() - start_time) < timedelta(seconds=DEFAULT_TIMEOUT):
            res = ir_remote.read(key)
            if res["code"]:
                log_msg = 'Captured infrared command: %s' % res["code"]
                _LOGGER.info(log_msg)
                persistent_notification.async_create(
                    hass, log_msg, title='Chuang Mi IR Remote Controller')
                return
            yield from asyncio.sleep(1, loop=hass.loop)

        log_msg = 'Timeout. No infrared command captured.'
        _LOGGER.error(log_msg)
        persistent_notification.async_create(
            hass, log_msg, title='Chuang Mi IR Remote Controller')

    @asyncio.coroutine
    def _send_command(call):
        command = str(call.data.get(ATTR_COMMAND))
        if command:
            for retry in range(retries):
                try:
                    ir_remote.play_raw(command, 38400)
                    break
                except (timeout, ValueError):
                    _LOGGER.error("Transmit infrared command failed.")
        else:
            _LOGGER.debug("Empty infrared command skipped.")

    hass.services.register(
        DOMAIN, SERVICE_LEARN + '_' + host.replace('.', '_'), _learn_command)

    hass.services.register(
        DOMAIN, SERVICE_SEND + '_' + host.replace('.', '_'), _send_command)

    switches = []
    for object_id, device_config in devices.items():
        switches.append(
            ChuangMiInfraredSwitch(
                ir_remote,
                device_config.get(CONF_NAME, object_id),
                device_config.get(CONF_COMMAND_ON),
                device_config.get(CONF_COMMAND_OFF),
                device_info
            )
        )

    add_devices(switches)