Exemplo n.º 1
0
async def main():
    with open("config.json") as file:
        config = json.load(file)
    light = PhilipsBulb(config["host"], config["token"])
    device = XiaomiPhilipsBulb(config["name"], light, config["model"], None)

    await asyncio.gather(device.async_update())
Exemplo n.º 2
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)
    def onStart(self):
        Domoticz.Debug("onStart called")
        if Parameters['Mode2'] == 'Debug': Domoticz.Debugging(1)

        if self.UNIT_LAMP not in Devices:
            Domoticz.Device(Name='Lamp',
                            Unit=self.UNIT_LAMP,
                            Type=241,
                            Subtype=8,
                            Switchtype=7,
                            Used=1).Create()

        if ((Parameters['Mode3'] == 'Show')
                and (self.UNIT_SCENES not in Devices)):
            Options = {
                "Scenes": "|||||",
                "LevelNames": "Off|Bright|TV|Warm|Midnight",
                "LevelOffHidden": "true",
                "SelectorStyle": "0"
            }
            Domoticz.Device(Name="Scenes",
                            Unit=self.UNIT_SCENES,
                            Type=244,
                            Subtype=62,
                            Switchtype=18,
                            Options=Options,
                            Used=1).Create()

        global Lamp
        Lamp = PhilipsBulb(Parameters['Address'], Parameters['Mode1'])

        self.pollTime = random.randrange(5, 16)
        self.nextTimeSync = 0

        DumpConfigToLog()
        Domoticz.Heartbeat(20)

        Domoticz.Debug('Plugin started.')
        Domoticz.Log('Poll time is every {0} minute'.format(self.pollTime))
Exemplo n.º 4
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)
Exemplo n.º 5
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)
Exemplo n.º 6
0
async def async_setup_entry(hass, config_entry, async_add_entities):
    """Set up the Xiaomi light from a config entry."""
    entities = []

    if config_entry.data[CONF_FLOW_TYPE] == CONF_GATEWAY:
        gateway = hass.data[DOMAIN][config_entry.entry_id][CONF_GATEWAY]
        # Gateway light
        if gateway.model not in [
                GATEWAY_MODEL_AC_V1,
                GATEWAY_MODEL_AC_V2,
                GATEWAY_MODEL_AC_V3,
        ]:
            entities.append(
                XiaomiGatewayLight(gateway, config_entry.title,
                                   config_entry.unique_id))
        # Gateway sub devices
        sub_devices = gateway.devices
        coordinator = hass.data[DOMAIN][config_entry.entry_id][KEY_COORDINATOR]
        for sub_device in sub_devices.values():
            if sub_device.device_type == "LightBulb":
                entities.append(
                    XiaomiGatewayBulb(coordinator, sub_device, config_entry))

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

        host = config_entry.data[CONF_HOST]
        token = config_entry.data[CONF_TOKEN]
        name = config_entry.title
        model = config_entry.data[CONF_MODEL]
        unique_id = config_entry.unique_id

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

        if model in MODELS_LIGHT_EYECARE:
            light = PhilipsEyecare(host, token)
            entity = XiaomiPhilipsEyecareLamp(name, light, config_entry,
                                              unique_id)
            entities.append(entity)
            hass.data[DATA_KEY][host] = entity

            entities.append(
                XiaomiPhilipsEyecareLampAmbientLight(name, light, config_entry,
                                                     unique_id))
            # The ambient light doesn't expose additional services.
            # A hass.data[DATA_KEY] entry isn't needed.
        elif model in MODELS_LIGHT_CEILING:
            light = Ceil(host, token)
            entity = XiaomiPhilipsCeilingLamp(name, light, config_entry,
                                              unique_id)
            entities.append(entity)
            hass.data[DATA_KEY][host] = entity
        elif model in MODELS_LIGHT_MOON:
            light = PhilipsMoonlight(host, token)
            entity = XiaomiPhilipsMoonlightLamp(name, light, config_entry,
                                                unique_id)
            entities.append(entity)
            hass.data[DATA_KEY][host] = entity
        elif model in MODELS_LIGHT_BULB:
            light = PhilipsBulb(host, token)
            entity = XiaomiPhilipsBulb(name, light, config_entry, unique_id)
            entities.append(entity)
            hass.data[DATA_KEY][host] = entity
        elif model in MODELS_LIGHT_MONO:
            light = PhilipsBulb(host, token)
            entity = XiaomiPhilipsGenericLight(name, light, config_entry,
                                               unique_id)
            entities.append(entity)
            hass.data[DATA_KEY][host] = entity
        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

        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
            }
            if entity_ids := service.data.get(ATTR_ENTITY_ID):
                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)