예제 #1
0
async def async_setup(hass, config):
    """Set up the Tradfri component."""
    conf = config.get(DOMAIN, {})
    host = conf.get(CONF_HOST)
    allow_tradfri_groups = conf.get(CONF_ALLOW_TRADFRI_GROUPS)
    known_hosts = await hass.async_add_job(load_json,
                                           hass.config.path(CONFIG_FILE))

    async def gateway_discovered(service, info,
                                 allow_groups=DEFAULT_ALLOW_TRADFRI_GROUPS):
        """Run when a gateway is discovered."""
        host = info['host']

        if host in known_hosts:
            # use fallbacks for old config style
            # identity was hard coded as 'homeassistant'
            identity = known_hosts[host].get('identity', 'homeassistant')
            key = known_hosts[host].get('key')
            await _setup_gateway(hass, config, host, identity, key,
                                 allow_groups)
        else:
            hass.async_add_job(request_configuration, hass, config, host)

    discovery.async_listen(hass, SERVICE_IKEA_TRADFRI, gateway_discovered)

    if host:
        await gateway_discovered(None,
                                 {'host': host},
                                 allow_tradfri_groups)
    return True
예제 #2
0
def async_setup(hass, config):
    """Set up the Tradfri component."""
    conf = config.get(DOMAIN, {})
    host = conf.get(CONF_HOST)
    key = conf.get(CONF_API_KEY)
    allow_tradfri_groups = conf.get(CONF_ALLOW_TRADFRI_GROUPS)

    @asyncio.coroutine
    def gateway_discovered(service, info):
        """Run when a gateway is discovered."""
        keys = yield from hass.async_add_job(_read_config, hass)
        host = info['host']

        if host in keys:
            yield from _setup_gateway(hass, config, host, keys[host]['key'],
                                      allow_tradfri_groups)
        else:
            hass.async_add_job(request_configuration, hass, config, host)

    discovery.async_listen(hass, SERVICE_IKEA_TRADFRI, gateway_discovered)

    if host is None:
        return True

    return (yield from _setup_gateway(hass, config, host, key,
                                      allow_tradfri_groups))
예제 #3
0
async def async_setup(hass, config):
    """Set up the Konnected platform."""
    cfg = config.get(DOMAIN)
    if cfg is None:
        cfg = {}

    access_token = cfg.get(CONF_ACCESS_TOKEN)
    if DOMAIN not in hass.data:
        hass.data[DOMAIN] = {
            CONF_ACCESS_TOKEN: access_token,
            CONF_API_HOST: cfg.get(CONF_API_HOST)
        }

    def device_discovered(service, info):
        """Call when a Konnected device has been discovered."""
        host = info.get(CONF_HOST)
        port = info.get(CONF_PORT)
        discovered = DiscoveredDevice(hass, host, port)
        if discovered.is_configured:
            discovered.setup()
        else:
            _LOGGER.warning(
                "Konnected device %s was discovered on the network"
                " but not specified in configuration.yaml",
                discovered.device_id)

    for device in cfg.get(CONF_DEVICES):
        ConfiguredDevice(hass, device).save_data()

    discovery.async_listen(hass, SERVICE_KONNECTED, device_discovered)

    hass.http.register_view(KonnectedView(access_token))

    return True
예제 #4
0
def async_setup(hass, config):
    """Set up the Tradfri component."""
    conf = config.get(DOMAIN, {})
    host = conf.get(CONF_HOST)
    key = conf.get(CONF_API_KEY)
    allow_tradfri_groups = conf.get(CONF_ALLOW_TRADFRI_GROUPS)

    @asyncio.coroutine
    def gateway_discovered(service, info):
        """Run when a gateway is discovered."""
        keys = yield from hass.async_add_job(_read_config, hass)
        host = info['host']

        if host in keys:
            yield from _setup_gateway(hass, config, host, keys[host]['key'],
                                      allow_tradfri_groups)
        else:
            hass.async_add_job(request_configuration, hass, config, host)

    discovery.async_listen(hass, SERVICE_IKEA_TRADFRI, gateway_discovered)

    if host is None:
        return True

    return (yield from _setup_gateway(hass, config, host, key,
                                      allow_tradfri_groups))
예제 #5
0
async def async_setup(hass, config):
    """Set up the Konnected platform."""
    cfg = config.get(DOMAIN)
    if cfg is None:
        cfg = {}

    access_token = cfg.get(CONF_ACCESS_TOKEN)
    if DOMAIN not in hass.data:
        hass.data[DOMAIN] = {CONF_ACCESS_TOKEN: access_token}

    def device_discovered(service, info):
        """Call when a Konnected device has been discovered."""
        _LOGGER.debug("Discovered a new Konnected device: %s", info)
        host = info.get(CONF_HOST)
        port = info.get(CONF_PORT)

        device = KonnectedDevice(hass, host, port, cfg)
        device.setup()

    discovery.async_listen(
        hass,
        SERVICE_KONNECTED,
        device_discovered)

    hass.http.register_view(KonnectedView(access_token))

    return True
예제 #6
0
async def async_setup(hass, config):
    """Set up the Konnected platform."""
    cfg = config.get(DOMAIN)
    if cfg is None:
        cfg = {}

    access_token = cfg.get(CONF_ACCESS_TOKEN)
    if DOMAIN not in hass.data:
        hass.data[DOMAIN] = {
            CONF_ACCESS_TOKEN: access_token,
            CONF_API_HOST: cfg.get(CONF_API_HOST)
        }

    def device_discovered(service, info):
        """Call when a Konnected device has been discovered."""
        _LOGGER.debug("Discovered a new Konnected device: %s", info)
        host = info.get(CONF_HOST)
        port = info.get(CONF_PORT)

        device = KonnectedDevice(hass, host, port, cfg)
        device.setup()

    discovery.async_listen(hass, SERVICE_KONNECTED, device_discovered)

    hass.http.register_view(KonnectedView(access_token))

    return True
예제 #7
0
async def async_setup(hass, config):
    """Set up services and configuration for deCONZ component."""
    result = False
    config_file = await hass.async_add_job(
        load_json, hass.config.path(CONFIG_FILE))

    async def async_deconz_discovered(service, discovery_info):
        """Call when deCONZ gateway has been found."""
        deconz_config = {}
        deconz_config[CONF_HOST] = discovery_info.get(CONF_HOST)
        deconz_config[CONF_PORT] = discovery_info.get(CONF_PORT)
        await async_request_configuration(hass, config, deconz_config)

    if config_file:
        result = await async_setup_deconz(hass, config, config_file)

    if not result and DOMAIN in config and CONF_HOST in config[DOMAIN]:
        deconz_config = config[DOMAIN]
        if CONF_API_KEY in deconz_config:
            result = await async_setup_deconz(hass, config, deconz_config)
        else:
            await async_request_configuration(hass, config, deconz_config)
            return True

    if not result:
        discovery.async_listen(hass, SERVICE_DECONZ, async_deconz_discovered)

    return True
예제 #8
0
async def async_setup(hass, config):
    """Set up the Apple TV component."""
    if DATA_APPLE_TV not in hass.data:
        hass.data[DATA_APPLE_TV] = {}

    async def async_service_handler(service):
        """Handle service calls."""
        entity_ids = service.data.get(ATTR_ENTITY_ID)

        if service.service == SERVICE_SCAN:
            hass.async_add_job(scan_for_apple_tvs, hass)
            return

        if entity_ids:
            devices = [
                device for device in hass.data[DATA_ENTITIES]
                if device.entity_id in entity_ids
            ]
        else:
            devices = hass.data[DATA_ENTITIES]

        for device in devices:
            if service.service != SERVICE_AUTHENTICATE:
                continue

            atv = device.atv
            credentials = await atv.airplay.generate_credentials()
            await atv.airplay.load_credentials(credentials)
            _LOGGER.debug('Generated new credentials: %s', credentials)
            await atv.airplay.start_authentication()
            hass.async_add_job(request_configuration, hass, config, atv,
                               credentials)

    async def atv_discovered(service, info):
        """Set up an Apple TV that was auto discovered."""
        await _setup_atv(
            hass, config, {
                CONF_NAME: info['name'],
                CONF_HOST: info['host'],
                CONF_LOGIN_ID: info['properties']['hG'],
                CONF_START_OFF: False
            })

    discovery.async_listen(hass, SERVICE_APPLE_TV, atv_discovered)

    tasks = [_setup_atv(hass, config, conf) for conf in config.get(DOMAIN, [])]
    if tasks:
        await asyncio.wait(tasks, loop=hass.loop)

    hass.services.async_register(DOMAIN,
                                 SERVICE_SCAN,
                                 async_service_handler,
                                 schema=APPLE_TV_SCAN_SCHEMA)

    hass.services.async_register(DOMAIN,
                                 SERVICE_AUTHENTICATE,
                                 async_service_handler,
                                 schema=APPLE_TV_AUTHENTICATE_SCHEMA)

    return True
예제 #9
0
def async_setup(hass, config):
    """Set up services and configuration for deCONZ component."""
    result = False
    config_file = yield from hass.async_add_job(load_json,
                                                hass.config.path(CONFIG_FILE))

    @asyncio.coroutine
    def async_deconz_discovered(service, discovery_info):
        """Call when deCONZ gateway has been found."""
        deconz_config = {}
        deconz_config[CONF_HOST] = discovery_info.get(CONF_HOST)
        deconz_config[CONF_PORT] = discovery_info.get(CONF_PORT)
        yield from async_request_configuration(hass, config, deconz_config)

    if config_file:
        result = yield from async_setup_deconz(hass, config, config_file)

    if not result and DOMAIN in config and CONF_HOST in config[DOMAIN]:
        deconz_config = config[DOMAIN]
        if CONF_API_KEY in deconz_config:
            result = yield from async_setup_deconz(hass, config, deconz_config)
        else:
            yield from async_request_configuration(hass, config, deconz_config)
            return True

    if not result:
        discovery.async_listen(hass, SERVICE_DECONZ, async_deconz_discovered)

    return True
예제 #10
0
async def async_setup(hass, config):
    """Set up the Freebox component."""
    conf = config.get(DOMAIN)

    async def discovery_dispatch(service, discovery_info):
        if conf is None:
            host = discovery_info.get("properties", {}).get("api_domain")
            port = discovery_info.get("properties", {}).get("https_port")
            _LOGGER.info("Discovered Freebox server: %s:%s", host, port)
            hass.async_create_task(
                hass.config_entries.flow.async_init(
                    DOMAIN,
                    context={"source": SOURCE_DISCOVERY},
                    data={
                        CONF_HOST: host,
                        CONF_PORT: port
                    },
                ))

    discovery.async_listen(hass, SERVICE_FREEBOX, discovery_dispatch)

    if conf is None:
        return True

    for freebox_conf in conf:
        hass.async_create_task(
            hass.config_entries.flow.async_init(
                DOMAIN,
                context={"source": SOURCE_IMPORT},
                data=freebox_conf,
            ))

    return True
예제 #11
0
async def async_setup(hass, config):
    """Set up the Tradfri component."""
    conf = config.get(DOMAIN, {})
    host = conf.get(CONF_HOST)
    allow_tradfri_groups = conf.get(CONF_ALLOW_TRADFRI_GROUPS)
    known_hosts = await hass.async_add_job(load_json,
                                           hass.config.path(CONFIG_FILE))

    async def gateway_discovered(service,
                                 info,
                                 allow_groups=DEFAULT_ALLOW_TRADFRI_GROUPS):
        """Run when a gateway is discovered."""
        host = info['host']

        if host in known_hosts:
            # use fallbacks for old config style
            # identity was hard coded as 'homeassistant'
            identity = known_hosts[host].get('identity', 'homeassistant')
            key = known_hosts[host].get('key')
            await _setup_gateway(hass, config, host, identity, key,
                                 allow_groups)
        else:
            hass.async_add_job(request_configuration, hass, config, host)

    discovery.async_listen(hass, SERVICE_IKEA_TRADFRI, gateway_discovered)

    if host:
        await gateway_discovered(None, {'host': host}, allow_tradfri_groups)
    return True
예제 #12
0
def async_setup(hass, config):
    """Set up the Apple TV component."""
    if DATA_APPLE_TV not in hass.data:
        hass.data[DATA_APPLE_TV] = {}

    @asyncio.coroutine
    def async_service_handler(service):
        """Handler for service calls."""
        entity_ids = service.data.get(ATTR_ENTITY_ID)

        if entity_ids:
            devices = [device for device in hass.data[DATA_ENTITIES]
                       if device.entity_id in entity_ids]
        else:
            devices = hass.data[DATA_ENTITIES]

        for device in devices:
            atv = device.atv
            if service.service == SERVICE_AUTHENTICATE:
                credentials = yield from atv.airplay.generate_credentials()
                yield from atv.airplay.load_credentials(credentials)
                _LOGGER.debug('Generated new credentials: %s', credentials)
                yield from atv.airplay.start_authentication()
                hass.async_add_job(request_configuration,
                                   hass, config, atv, credentials)
            elif service.service == SERVICE_SCAN:
                hass.async_add_job(scan_for_apple_tvs, hass)

    @asyncio.coroutine
    def atv_discovered(service, info):
        """Setup an Apple TV that was auto discovered."""
        yield from _setup_atv(hass, {
            CONF_NAME: info['name'],
            CONF_HOST: info['host'],
            CONF_LOGIN_ID: info['properties']['hG'],
            CONF_START_OFF: False
        })

    discovery.async_listen(hass, SERVICE_APPLE_TV, atv_discovered)

    tasks = [_setup_atv(hass, conf) for conf in config.get(DOMAIN, [])]
    if tasks:
        yield from asyncio.wait(tasks, loop=hass.loop)

    descriptions = yield from hass.async_add_job(
        load_yaml_config_file, os.path.join(
            os.path.dirname(__file__), 'services.yaml'))

    hass.services.async_register(
        DOMAIN, SERVICE_SCAN, async_service_handler,
        descriptions.get(SERVICE_SCAN),
        schema=APPLE_TV_SCAN_SCHEMA)

    hass.services.async_register(
        DOMAIN, SERVICE_AUTHENTICATE, async_service_handler,
        descriptions.get(SERVICE_AUTHENTICATE),
        schema=APPLE_TV_AUTHENTICATE_SCHEMA)

    return True
예제 #13
0
async def async_setup(hass, config):
    """Set up the Hue platform."""
    conf = config.get(DOMAIN)
    if conf is None:
        conf = {}

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

    async def async_bridge_discovered(service, discovery_info):
        """Dispatcher for Hue discovery events."""
        # Ignore emulated hue
        if "HASS Bridge" in discovery_info.get('name', ''):
            return

        await async_setup_bridge(
            hass, discovery_info['host'],
            'phue-{}.conf'.format(discovery_info['serial']))

    discovery.async_listen(hass, SERVICE_HUE, async_bridge_discovered)

    # User has configured bridges
    if CONF_BRIDGES in conf:
        bridges = conf[CONF_BRIDGES]

    # Component is part of config but no bridges specified, discover.
    elif DOMAIN in config:
        # discover from nupnp
        websession = aiohttp_client.async_get_clientsession(hass)

        async with websession.get(API_NUPNP) as req:
            hosts = await req.json()

        # Run through config schema to populate defaults
        bridges = [
            BRIDGE_CONFIG_SCHEMA({
                CONF_HOST:
                entry['internalipaddress'],
                CONF_FILENAME:
                '.hue_{}.conf'.format(entry['id']),
            }) for entry in hosts
        ]

    else:
        # Component not specified in config, we're loaded via discovery
        bridges = []

    if not bridges:
        return True

    await asyncio.wait([
        async_setup_bridge(hass, bridge[CONF_HOST], bridge[CONF_FILENAME],
                           bridge[CONF_ALLOW_UNREACHABLE],
                           bridge[CONF_ALLOW_HUE_GROUPS]) for bridge in bridges
    ])

    return True
예제 #14
0
async def async_setup(hass, config):
    """Set up the Apple TV component."""
    if DATA_APPLE_TV not in hass.data:
        hass.data[DATA_APPLE_TV] = {}

    async def async_service_handler(service):
        """Handle service calls."""
        entity_ids = service.data.get(ATTR_ENTITY_ID)

        if service.service == SERVICE_SCAN:
            hass.async_add_job(scan_for_apple_tvs, hass)
            return

        if entity_ids:
            devices = [device for device in hass.data[DATA_ENTITIES]
                       if device.entity_id in entity_ids]
        else:
            devices = hass.data[DATA_ENTITIES]

        for device in devices:
            if service.service != SERVICE_AUTHENTICATE:
                continue

            atv = device.atv
            credentials = await atv.airplay.generate_credentials()
            await atv.airplay.load_credentials(credentials)
            _LOGGER.debug('Generated new credentials: %s', credentials)
            await atv.airplay.start_authentication()
            hass.async_add_job(request_configuration,
                               hass, config, atv, credentials)

    async def atv_discovered(service, info):
        """Set up an Apple TV that was auto discovered."""
        await _setup_atv(hass, config, {
            CONF_NAME: info['name'],
            CONF_HOST: info['host'],
            CONF_LOGIN_ID: info['properties']['hG'],
            CONF_START_OFF: False
        })

    discovery.async_listen(hass, SERVICE_APPLE_TV, atv_discovered)

    tasks = [_setup_atv(hass, config, conf) for conf in config.get(DOMAIN, [])]
    if tasks:
        await asyncio.wait(tasks, loop=hass.loop)

    hass.services.async_register(
        DOMAIN, SERVICE_SCAN, async_service_handler,
        schema=APPLE_TV_SCAN_SCHEMA)

    hass.services.async_register(
        DOMAIN, SERVICE_AUTHENTICATE, async_service_handler,
        schema=APPLE_TV_AUTHENTICATE_SCHEMA)

    return True
예제 #15
0
async def async_setup(hass, config):
    """Set up the Hue platform."""
    conf = config.get(DOMAIN)
    if conf is None:
        conf = {}

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

    async def async_bridge_discovered(service, discovery_info):
        """Dispatcher for Hue discovery events."""
        # Ignore emulated hue
        if "HASS Bridge" in discovery_info.get('name', ''):
            return

        await async_setup_bridge(
            hass, discovery_info['host'],
            'phue-{}.conf'.format(discovery_info['serial']))

    discovery.async_listen(hass, SERVICE_HUE, async_bridge_discovered)

    # User has configured bridges
    if CONF_BRIDGES in conf:
        bridges = conf[CONF_BRIDGES]

    # Component is part of config but no bridges specified, discover.
    elif DOMAIN in config:
        # discover from nupnp
        websession = aiohttp_client.async_get_clientsession(hass)

        async with websession.get(API_NUPNP) as req:
            hosts = await req.json()

        # Run through config schema to populate defaults
        bridges = [BRIDGE_CONFIG_SCHEMA({
            CONF_HOST: entry['internalipaddress'],
            CONF_FILENAME: '.hue_{}.conf'.format(entry['id']),
        }) for entry in hosts]

    else:
        # Component not specified in config, we're loaded via discovery
        bridges = []

    if not bridges:
        return True

    await asyncio.wait([
        async_setup_bridge(
            hass, bridge[CONF_HOST], bridge[CONF_FILENAME],
            bridge[CONF_ALLOW_UNREACHABLE], bridge[CONF_ALLOW_HUE_GROUPS]
        ) for bridge in bridges
    ])

    return True
예제 #16
0
async def async_setup(hass, config):
    """Set up the SABnzbd component."""
    async def sabnzbd_discovered(service, info):
        """Handle service discovery."""
        ssl = info.get("properties", {}).get("https", "0") == "1"
        await async_configure_sabnzbd(hass, info, ssl)

    discovery.async_listen(hass, SERVICE_SABNZBD, sabnzbd_discovered)

    if (conf := config.get(DOMAIN)) is not None:
        use_ssl = conf[CONF_SSL]
        name = conf.get(CONF_NAME)
        api_key = conf.get(CONF_API_KEY)
        await async_configure_sabnzbd(hass, conf, use_ssl, name, api_key)
예제 #17
0
async def async_setup(hass, config):
    """Setup the SABnzbd component."""
    async def sabnzbd_discovered(service, info):
        """Handle service discovery."""
        ssl = info.get('properties', {}).get('https', '0') == '1'
        await async_configure_sabnzbd(hass, info, ssl)

    discovery.async_listen(hass, SERVICE_SABNZBD, sabnzbd_discovered)

    conf = config.get(DOMAIN)
    if conf is not None:
        use_ssl = conf.get(CONF_SSL)
        name = conf.get(CONF_NAME)
        api_key = conf.get(CONF_API_KEY)
        await async_configure_sabnzbd(hass, conf, use_ssl, name, api_key)
    return True
예제 #18
0
async def async_setup(hass, config):
    """Setup the SABnzbd component."""
    async def sabnzbd_discovered(service, info):
        """Handle service discovery."""
        ssl = info.get('properties', {}).get('https', '0') == '1'
        await async_configure_sabnzbd(hass, info, ssl)

    discovery.async_listen(hass, SERVICE_SABNZBD, sabnzbd_discovered)

    conf = config.get(DOMAIN)
    if conf is not None:
        use_ssl = conf.get(CONF_SSL)
        name = conf.get(CONF_NAME)
        api_key = conf.get(CONF_API_KEY)
        await async_configure_sabnzbd(hass, conf, use_ssl, name, api_key)
    return True
예제 #19
0
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
    """Set up the SABnzbd component."""
    async def sabnzbd_discovered(service: str,
                                 info: DiscoveryInfoType | None) -> None:
        """Handle service discovery."""
        if not info:
            return
        ssl = info.get("properties", {}).get("https", "0") == "1"
        await async_configure_sabnzbd(hass, info, ssl)

    discovery.async_listen(hass, SERVICE_SABNZBD, sabnzbd_discovered)

    if (conf := config.get(DOMAIN)) is not None:
        use_ssl = conf[CONF_SSL]
        name = conf.get(CONF_NAME)
        api_key = conf.get(CONF_API_KEY)
        await async_configure_sabnzbd(hass, conf, use_ssl, name, api_key)
예제 #20
0
async def async_setup(hass, config):
    """Set up the Freebox component."""
    conf = config.get(DOMAIN)

    async def discovery_dispatch(service, discovery_info):
        if conf is None:
            host = discovery_info.get("properties", {}).get("api_domain")
            port = discovery_info.get("properties", {}).get("https_port")
            _LOGGER.info("Discovered Freebox server: %s:%s", host, port)
            await async_setup_freebox(hass, config, host, port)

    discovery.async_listen(hass, SERVICE_FREEBOX, discovery_dispatch)

    if conf is not None:
        host = conf.get(CONF_HOST)
        port = conf.get(CONF_PORT)
        await async_setup_freebox(hass, config, host, port)

    return True
예제 #21
0
async def async_setup(hass, config):
    """Set up the Freebox component."""
    conf = config.get(DOMAIN)

    async def discovery_dispatch(service, discovery_info):
        if conf is None:
            host = discovery_info.get('properties', {}).get('api_domain')
            port = discovery_info.get('properties', {}).get('https_port')
            _LOGGER.info("Discovered Freebox server: %s:%s", host, port)
            await async_setup_freebox(hass, config, host, port)

    discovery.async_listen(hass, SERVICE_FREEBOX, discovery_dispatch)

    if conf is not None:
        host = conf.get(CONF_HOST)
        port = conf.get(CONF_PORT)
        await async_setup_freebox(hass, config, host, port)

    return True
예제 #22
0
async def test_listen(hass, mock_setup_component):
    """Test discovery listen/discover combo."""
    calls_single = []

    @callback
    def callback_single(service, info):
        """Service discovered callback."""
        calls_single.append((service, info))

    discovery.async_listen(hass, "test service", callback_single)

    await discovery.async_discover(
        hass,
        "test service",
        "discovery info",
        "test_component",
        {},
    )
    await hass.async_block_till_done()

    assert mock_setup_component.called
    assert mock_setup_component.call_args[0] == (hass, "test_component", {})
    assert len(calls_single) == 1
    assert calls_single[0] == ("test service", "discovery info")
예제 #23
0
async def async_setup(hass, config):
    """Set up the Konnected platform."""
    cfg = config.get(DOMAIN)
    if cfg is None:
        cfg = {}

    access_token = cfg.get(CONF_ACCESS_TOKEN)
    if DOMAIN not in hass.data:
        hass.data[DOMAIN] = {
            CONF_ACCESS_TOKEN: access_token,
            CONF_API_HOST: cfg.get(CONF_API_HOST)
        }

    def device_discovered(service, info):
        """Call when a Konnected device has been discovered."""
        host = info.get(CONF_HOST)
        port = info.get(CONF_PORT)
        discovered = DiscoveredDevice(hass, host, port)
        if discovered.is_configured:
            discovered.setup()
        else:
            _LOGGER.warning("Konnected device %s was discovered on the network"
                            " but not specified in configuration.yaml",
                            discovered.device_id)

    for device in cfg.get(CONF_DEVICES):
        ConfiguredDevice(hass, device).save_data()

    discovery.async_listen(
        hass,
        SERVICE_KONNECTED,
        device_discovered)

    hass.http.register_view(KonnectedView(access_token))

    return True
예제 #24
0
def async_setup(hass, config):
    """Set up the Apple TV component."""
    if DATA_APPLE_TV not in hass.data:
        hass.data[DATA_APPLE_TV] = {}

    @asyncio.coroutine
    def async_service_handler(service):
        """Handler for service calls."""
        entity_ids = service.data.get(ATTR_ENTITY_ID)

        if entity_ids:
            devices = [
                device for device in hass.data[DATA_ENTITIES]
                if device.entity_id in entity_ids
            ]
        else:
            devices = hass.data[DATA_ENTITIES]

        for device in devices:
            atv = device.atv
            if service.service == SERVICE_AUTHENTICATE:
                credentials = yield from atv.airplay.generate_credentials()
                yield from atv.airplay.load_credentials(credentials)
                _LOGGER.debug('Generated new credentials: %s', credentials)
                yield from atv.airplay.start_authentication()
                hass.async_add_job(request_configuration, hass, config, atv,
                                   credentials)
            elif service.service == SERVICE_SCAN:
                hass.async_add_job(scan_for_apple_tvs, hass)

    @asyncio.coroutine
    def atv_discovered(service, info):
        """Setup an Apple TV that was auto discovered."""
        yield from _setup_atv(
            hass, {
                CONF_NAME: info['name'],
                CONF_HOST: info['host'],
                CONF_LOGIN_ID: info['properties']['hG'],
                CONF_START_OFF: False
            })

    discovery.async_listen(hass, SERVICE_APPLE_TV, atv_discovered)

    tasks = [_setup_atv(hass, conf) for conf in config.get(DOMAIN, [])]
    if tasks:
        yield from asyncio.wait(tasks, loop=hass.loop)

    descriptions = yield from hass.async_add_job(
        load_yaml_config_file,
        os.path.join(os.path.dirname(__file__), 'services.yaml'))

    hass.services.async_register(DOMAIN,
                                 SERVICE_SCAN,
                                 async_service_handler,
                                 descriptions.get(SERVICE_SCAN),
                                 schema=APPLE_TV_SCAN_SCHEMA)

    hass.services.async_register(DOMAIN,
                                 SERVICE_AUTHENTICATE,
                                 async_service_handler,
                                 descriptions.get(SERVICE_AUTHENTICATE),
                                 schema=APPLE_TV_AUTHENTICATE_SCHEMA)

    return True
예제 #25
0
def async_setup(hass: HomeAssistantType, config: ConfigType):
    """Setup device tracker."""
    yaml_path = hass.config.path(YAML_DEVICES)

    try:
        conf = config.get(DOMAIN, [])
    except vol.Invalid as ex:
        async_log_exception(ex, DOMAIN, config, hass)
        return False
    else:
        conf = conf[0] if len(conf) > 0 else {}
        consider_home = conf.get(CONF_CONSIDER_HOME,
                                 timedelta(seconds=DEFAULT_CONSIDER_HOME))
        track_new = conf.get(CONF_TRACK_NEW, DEFAULT_TRACK_NEW)

    devices = yield from async_load_config(yaml_path, hass, consider_home)
    tracker = DeviceTracker(hass, consider_home, track_new, devices)

    # update tracked devices
    update_tasks = [device.async_update_ha_state() for device in devices
                    if device.track]
    if update_tasks:
        yield from asyncio.wait(update_tasks, loop=hass.loop)

    @asyncio.coroutine
    def async_setup_platform(p_type, p_config, disc_info=None):
        """Setup a device tracker platform."""
        platform = yield from async_prepare_setup_platform(
            hass, config, DOMAIN, p_type)
        if platform is None:
            return

        try:
            if hasattr(platform, 'get_scanner'):
                scanner = yield from hass.loop.run_in_executor(
                    None, platform.get_scanner, hass, {DOMAIN: p_config})

                if scanner is None:
                    _LOGGER.error('Error setting up platform %s', p_type)
                    return

                yield from async_setup_scanner_platform(
                    hass, p_config, scanner, tracker.async_see)
                return

            ret = yield from hass.loop.run_in_executor(
                None, platform.setup_scanner, hass, p_config, tracker.see)
            if not ret:
                _LOGGER.error('Error setting up platform %s', p_type)
        except Exception:  # pylint: disable=broad-except
            _LOGGER.exception('Error setting up platform %s', p_type)

    setup_tasks = [async_setup_platform(p_type, p_config) for p_type, p_config
                   in config_per_platform(config, DOMAIN)]
    if setup_tasks:
        yield from asyncio.wait(setup_tasks, loop=hass.loop)

    yield from tracker.async_setup_group()

    @callback
    def async_device_tracker_discovered(service, info):
        """Called when a device tracker platform is discovered."""
        hass.async_add_job(
            async_setup_platform(DISCOVERY_PLATFORMS[service], {}, info))

    discovery.async_listen(
        hass, DISCOVERY_PLATFORMS.keys(), async_device_tracker_discovered)

    # Clean up stale devices
    async_track_utc_time_change(
        hass, tracker.async_update_stale, second=range(0, 60, 5))

    @asyncio.coroutine
    def async_see_service(call):
        """Service to see a device."""
        args = {key: value for key, value in call.data.items() if key in
                (ATTR_MAC, ATTR_DEV_ID, ATTR_HOST_NAME, ATTR_LOCATION_NAME,
                 ATTR_GPS, ATTR_GPS_ACCURACY, ATTR_BATTERY, ATTR_ATTRIBUTES)}
        yield from tracker.async_see(**args)

    descriptions = yield from hass.loop.run_in_executor(
        None, load_yaml_config_file,
        os.path.join(os.path.dirname(__file__), 'services.yaml')
    )
    hass.services.async_register(
        DOMAIN, SERVICE_SEE, async_see_service, descriptions.get(SERVICE_SEE))

    return True
예제 #26
0
def async_setup(hass: HomeAssistantType, config: ConfigType):
    """Setup device tracker."""
    yaml_path = hass.config.path(YAML_DEVICES)

    try:
        conf = config.get(DOMAIN, [])
    except vol.Invalid as ex:
        async_log_exception(ex, DOMAIN, config, hass)
        return False
    else:
        conf = conf[0] if len(conf) > 0 else {}
        consider_home = conf.get(CONF_CONSIDER_HOME, DEFAULT_CONSIDER_HOME)
        track_new = conf.get(CONF_TRACK_NEW, DEFAULT_TRACK_NEW)

    devices = yield from async_load_config(yaml_path, hass, consider_home)
    tracker = DeviceTracker(hass, consider_home, track_new, devices)

    @asyncio.coroutine
    def async_setup_platform(p_type, p_config, disc_info=None):
        """Setup a device tracker platform."""
        platform = yield from async_prepare_setup_platform(
            hass, config, DOMAIN, p_type)
        if platform is None:
            return

        _LOGGER.info("Setting up %s.%s", DOMAIN, p_type)
        try:
            scanner = None
            setup = None
            if hasattr(platform, 'async_get_scanner'):
                scanner = yield from platform.async_get_scanner(
                    hass, {DOMAIN: p_config})
            elif hasattr(platform, 'get_scanner'):
                scanner = yield from hass.loop.run_in_executor(
                    None, platform.get_scanner, hass, {DOMAIN: p_config})
            elif hasattr(platform, 'async_setup_scanner'):
                setup = yield from platform.async_setup_scanner(
                    hass, p_config, tracker.async_see, disc_info)
            elif hasattr(platform, 'setup_scanner'):
                setup = yield from hass.loop.run_in_executor(
                    None, platform.setup_scanner, hass, p_config, tracker.see,
                    disc_info)
            else:
                raise HomeAssistantError("Invalid device_tracker platform.")

            if scanner:
                async_setup_scanner_platform(hass, p_config, scanner,
                                             tracker.async_see, p_type)
                return

            if not setup:
                _LOGGER.error('Error setting up platform %s', p_type)
                return

        except Exception:  # pylint: disable=broad-except
            _LOGGER.exception('Error setting up platform %s', p_type)

    setup_tasks = [
        async_setup_platform(p_type, p_config)
        for p_type, p_config in config_per_platform(config, DOMAIN)
    ]
    if setup_tasks:
        yield from asyncio.wait(setup_tasks, loop=hass.loop)

    yield from tracker.async_setup_group()

    @callback
    def async_device_tracker_discovered(service, info):
        """Called when a device tracker platform is discovered."""
        hass.async_add_job(
            async_setup_platform(DISCOVERY_PLATFORMS[service], {}, info))

    discovery.async_listen(hass, DISCOVERY_PLATFORMS.keys(),
                           async_device_tracker_discovered)

    @asyncio.coroutine
    def async_platform_discovered(platform, info):
        """Callback to load a platform."""
        yield from async_setup_platform(platform, {}, disc_info=info)

    discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered)

    # Clean up stale devices
    async_track_utc_time_change(hass,
                                tracker.async_update_stale,
                                second=range(0, 60, 5))

    @asyncio.coroutine
    def async_see_service(call):
        """Service to see a device."""
        args = {
            key: value
            for key, value in call.data.items()
            if key in (ATTR_MAC, ATTR_DEV_ID, ATTR_HOST_NAME,
                       ATTR_LOCATION_NAME, ATTR_GPS, ATTR_GPS_ACCURACY,
                       ATTR_BATTERY, ATTR_ATTRIBUTES)
        }
        yield from tracker.async_see(**args)

    descriptions = yield from hass.loop.run_in_executor(
        None, load_yaml_config_file,
        os.path.join(os.path.dirname(__file__), 'services.yaml'))
    hass.services.async_register(DOMAIN, SERVICE_SEE, async_see_service,
                                 descriptions.get(SERVICE_SEE))

    # restore
    yield from tracker.async_setup_tracked_device()
    return True
예제 #27
0
async def async_setup(hass, config):
    """Set up the Konnected platform."""
    cfg = config.get(DOMAIN)
    if cfg is None:
        cfg = {}

    access_token = cfg.get(CONF_ACCESS_TOKEN)
    if DOMAIN not in hass.data:
        hass.data[DOMAIN] = {
            CONF_ACCESS_TOKEN: access_token,
            CONF_API_HOST: cfg.get(CONF_API_HOST),
        }

    def setup_device(host, port):
        """Set up a Konnected device at `host` listening on `port`."""
        discovered = DiscoveredDevice(hass, host, port)
        if discovered.is_configured:
            discovered.setup()
        else:
            _LOGGER.warning(
                "Konnected device %s was discovered on the network"
                " but not specified in configuration.yaml",
                discovered.device_id,
            )

    def device_discovered(service, info):
        """Call when a Konnected device has been discovered."""
        host = info.get(CONF_HOST)
        port = info.get(CONF_PORT)
        setup_device(host, port)

    async def manual_discovery(event):
        """Init devices on the network with manually assigned addresses."""
        specified = [
            dev for dev in cfg.get(CONF_DEVICES)
            if dev.get(CONF_HOST) and dev.get(CONF_PORT)
        ]

        while specified:
            for dev in specified:
                _LOGGER.debug(
                    "Discovering Konnected device %s at %s:%s",
                    dev.get(CONF_ID),
                    dev.get(CONF_HOST),
                    dev.get(CONF_PORT),
                )
                try:
                    await hass.async_add_executor_job(setup_device,
                                                      dev.get(CONF_HOST),
                                                      dev.get(CONF_PORT))
                    specified.remove(dev)
                except konnected.Client.ClientError as err:
                    _LOGGER.error(err)
                    await asyncio.sleep(10)  # try again in 10 seconds

    # Initialize devices specified in the configuration on boot
    for device in cfg.get(CONF_DEVICES):
        ConfiguredDevice(hass, device, config).save_data()

    discovery.async_listen(hass, SERVICE_KONNECTED, device_discovered)

    hass.http.register_view(KonnectedView(access_token))
    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, manual_discovery)

    return True
예제 #28
0
def async_setup(hass: HomeAssistantType, config: ConfigType):
    """Set up the device tracker."""
    yaml_path = hass.config.path(YAML_DEVICES)

    conf = config.get(DOMAIN, [])
    conf = conf[0] if conf else {}
    consider_home = conf.get(CONF_CONSIDER_HOME, DEFAULT_CONSIDER_HOME)
    track_new = conf.get(CONF_TRACK_NEW, DEFAULT_TRACK_NEW)

    devices = yield from async_load_config(yaml_path, hass, consider_home)
    tracker = DeviceTracker(hass, consider_home, track_new, devices)

    @asyncio.coroutine
    def async_setup_platform(p_type, p_config, disc_info=None):
        """Set up a device tracker platform."""
        platform = yield from async_prepare_setup_platform(
            hass, config, DOMAIN, p_type)
        if platform is None:
            return

        _LOGGER.info("Setting up %s.%s", DOMAIN, p_type)
        try:
            scanner = None
            setup = None
            if hasattr(platform, 'async_get_scanner'):
                scanner = yield from platform.async_get_scanner(
                    hass, {DOMAIN: p_config})
            elif hasattr(platform, 'get_scanner'):
                scanner = yield from hass.async_add_job(
                    platform.get_scanner, hass, {DOMAIN: p_config})
            elif hasattr(platform, 'async_setup_scanner'):
                setup = yield from platform.async_setup_scanner(
                    hass, p_config, tracker.async_see, disc_info)
            elif hasattr(platform, 'setup_scanner'):
                setup = yield from hass.async_add_job(
                    platform.setup_scanner, hass, p_config, tracker.see,
                    disc_info)
            else:
                raise HomeAssistantError("Invalid device_tracker platform.")

            if scanner:
                async_setup_scanner_platform(
                    hass, p_config, scanner, tracker.async_see, p_type)
                return

            if not setup:
                _LOGGER.error("Error setting up platform %s", p_type)
                return

        except Exception:  # pylint: disable=broad-except
            _LOGGER.exception("Error setting up platform %s", p_type)

    setup_tasks = [async_setup_platform(p_type, p_config) for p_type, p_config
                   in config_per_platform(config, DOMAIN)]
    if setup_tasks:
        yield from asyncio.wait(setup_tasks, loop=hass.loop)

    tracker.async_setup_group()

    @callback
    def async_device_tracker_discovered(service, info):
        """Handle the discovery of device tracker platforms."""
        hass.async_add_job(
            async_setup_platform(DISCOVERY_PLATFORMS[service], {}, info))

    discovery.async_listen(
        hass, DISCOVERY_PLATFORMS.keys(), async_device_tracker_discovered)

    @asyncio.coroutine
    def async_platform_discovered(platform, info):
        """Load a platform."""
        yield from async_setup_platform(platform, {}, disc_info=info)

    discovery.async_listen_platform(hass, DOMAIN, async_platform_discovered)

    # Clean up stale devices
    async_track_utc_time_change(
        hass, tracker.async_update_stale, second=range(0, 60, 5))

    @asyncio.coroutine
    def async_see_service(call):
        """Service to see a device."""
        args = {key: value for key, value in call.data.items() if key in
                (ATTR_MAC, ATTR_DEV_ID, ATTR_HOST_NAME, ATTR_LOCATION_NAME,
                 ATTR_GPS, ATTR_GPS_ACCURACY, ATTR_BATTERY, ATTR_ATTRIBUTES)}
        yield from tracker.async_see(**args)

    descriptions = yield from hass.async_add_job(
        load_yaml_config_file,
        os.path.join(os.path.dirname(__file__), 'services.yaml')
    )
    hass.services.async_register(
        DOMAIN, SERVICE_SEE, async_see_service, descriptions.get(SERVICE_SEE))

    # restore
    yield from tracker.async_setup_tracked_device()
    return True
예제 #29
0
async def async_setup_entry(hass, entry):
    """Set up a wemo config entry."""

    config = hass.data[DOMAIN]

    # Keep track of WeMo devices
    devices = []

    # Keep track of WeMo device subscriptions for push updates
    global SUBSCRIPTION_REGISTRY
    SUBSCRIPTION_REGISTRY = pywemo.SubscriptionRegistry()
    await hass.async_add_executor_job(SUBSCRIPTION_REGISTRY.start)

    def stop_wemo(event):
        """Shutdown Wemo subscriptions and subscription thread on exit."""
        _LOGGER.debug("Shutting down WeMo event subscriptions")
        SUBSCRIPTION_REGISTRY.stop()

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_wemo)

    def setup_url_for_device(device):
        """Determine setup.xml url for given device."""
        return f"http://{device.host}:{device.port}/setup.xml"

    def setup_url_for_address(host, port):
        """Determine setup.xml url for given host and port pair."""
        if not port:
            port = pywemo.ouimeaux_device.probe_wemo(host)

        if not port:
            return None

        return f"http://{host}:{port}/setup.xml"

    def discovery_dispatch(service, discovery_info):
        """Dispatcher for incoming WeMo discovery events."""
        # name, model, location, mac
        model_name = discovery_info.get("model_name")
        serial = discovery_info.get("serial")

        # Only register a device once
        if serial in KNOWN_DEVICES:
            _LOGGER.debug("Ignoring known device %s %s", service,
                          discovery_info)
            return

        _LOGGER.debug("Discovered unique WeMo device: %s", serial)
        KNOWN_DEVICES.append(serial)

        component = WEMO_MODEL_DISPATCH.get(model_name, "switch")

        discovery.load_platform(hass, component, DOMAIN, discovery_info,
                                config)

    discovery.async_listen(hass, SERVICE_WEMO, discovery_dispatch)

    def discover_wemo_devices(now):
        """Run discovery for WeMo devices."""
        _LOGGER.debug("Beginning WeMo device discovery...")
        _LOGGER.debug("Adding statically configured WeMo devices...")
        for host, port in config.get(DOMAIN, {}).get(CONF_STATIC, []):
            url = setup_url_for_address(host, port)

            if not url:
                _LOGGER.error(
                    "Unable to get description url for WeMo at: %s",
                    f"{host}:{port}" if port else host,
                )
                continue

            try:
                device = pywemo.discovery.device_from_description(url, None)
            except (
                    requests.exceptions.ConnectionError,
                    requests.exceptions.Timeout,
            ) as err:
                _LOGGER.error("Unable to access WeMo at %s (%s)", url, err)
                continue

            if not [
                    d[1] for d in devices
                    if d[1].serialnumber == device.serialnumber
            ]:
                devices.append((url, device))

        if config.get(DOMAIN, {}).get(CONF_DISCOVERY, DEFAULT_DISCOVERY):
            _LOGGER.debug("Scanning network for WeMo devices...")
            for device in pywemo.discover_devices():
                if not [
                        d[1] for d in devices
                        if d[1].serialnumber == device.serialnumber
                ]:
                    devices.append((setup_url_for_device(device), device))

        for url, device in devices:
            _LOGGER.debug("Adding WeMo device at %s:%i", device.host,
                          device.port)

            discovery_info = {
                "model_name": device.model_name,
                "serial": device.serialnumber,
                "mac_address": device.mac,
                "ssdp_description": url,
            }

            discovery_dispatch(SERVICE_WEMO, discovery_info)

        _LOGGER.debug("WeMo device discovery has finished")

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START,
                               discover_wemo_devices)

    return True
예제 #30
0
async def async_setup(hass, config):
    """Set up the Konnected platform."""
    import konnected

    cfg = config.get(DOMAIN)
    if cfg is None:
        cfg = {}

    access_token = cfg.get(CONF_ACCESS_TOKEN)
    if DOMAIN not in hass.data:
        hass.data[DOMAIN] = {
            CONF_ACCESS_TOKEN: access_token,
            CONF_API_HOST: cfg.get(CONF_API_HOST)
        }

    def setup_device(host, port):
        """Set up a Konnected device at `host` listening on `port`."""
        discovered = DiscoveredDevice(hass, host, port)
        if discovered.is_configured:
            discovered.setup()
        else:
            _LOGGER.warning("Konnected device %s was discovered on the network"
                            " but not specified in configuration.yaml",
                            discovered.device_id)

    def device_discovered(service, info):
        """Call when a Konnected device has been discovered."""
        host = info.get(CONF_HOST)
        port = info.get(CONF_PORT)
        setup_device(host, port)

    async def manual_discovery(event):
        """Init devices on the network with manually assigned addresses."""
        specified = [dev for dev in cfg.get(CONF_DEVICES) if
                     dev.get(CONF_HOST) and dev.get(CONF_PORT)]

        while specified:
            for dev in specified:
                _LOGGER.debug("Discovering Konnected device %s at %s:%s",
                              dev.get(CONF_ID),
                              dev.get(CONF_HOST),
                              dev.get(CONF_PORT))
                try:
                    await hass.async_add_executor_job(setup_device,
                                                      dev.get(CONF_HOST),
                                                      dev.get(CONF_PORT))
                    specified.remove(dev)
                except konnected.Client.ClientError as err:
                    _LOGGER.error(err)
                    await asyncio.sleep(10)  # try again in 10 seconds

    # Initialize devices specified in the configuration on boot
    for device in cfg.get(CONF_DEVICES):
        ConfiguredDevice(hass, device, config).save_data()

    discovery.async_listen(
        hass,
        SERVICE_KONNECTED,
        device_discovered)

    hass.http.register_view(KonnectedView(access_token))
    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, manual_discovery)

    return True