示例#1
0
def setup(hass, config):
    """Set up OctoPrint API."""
    if not validate_config(config, {DOMAIN: [CONF_API_KEY],
                                    DOMAIN: [CONF_HOST]},
                           _LOGGER):
        return False

    base_url = config[DOMAIN][CONF_HOST] + "/api/"
    api_key = config[DOMAIN][CONF_API_KEY]

    global OCTOPRINT
    try:
        OCTOPRINT = OctoPrintAPI(base_url, api_key)
        OCTOPRINT.get("printer")
        OCTOPRINT.get("job")
    except requests.exceptions.RequestException as conn_err:
        _LOGGER.error("Error setting up OctoPrint API: %r", conn_err)
        return False

    for component, discovery_service in (
            ('sensor', DISCOVER_SENSORS),
            ('binary_sensor', DISCOVER_BINARY_SENSORS)):
        discovery.discover(hass, discovery_service, component=component,
                           hass_config=config)

    return True
示例#2
0
 def component1_setup(hass, config):
     """Setup mock component."""
     print('component1 setup')
     discovery.discover(hass,
                        'test_component2',
                        component='test_component2')
     return True
示例#3
0
 def component1_setup(hass, config):
     """Set up mock component."""
     discovery.discover(hass, "test_component2", {}, "test_component2",
                        {})
     discovery.discover(hass, "test_component3", {}, "test_component3",
                        {})
     return True
示例#4
0
    def test_listen(self, mock_setup_component):
        """Test discovery listen/discover combo."""
        calls_single = []
        calls_multi = []

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

        def callback_multi(service, info):
            """Service discovered callback."""
            calls_multi.append((service, info))

        discovery.listen(self.hass, 'test service', callback_single)
        discovery.listen(self.hass, ['test service', 'another service'],
                         callback_multi)

        discovery.discover(self.hass, 'test service', 'discovery info',
                           'test_component')
        self.hass.pool.block_till_done()

        discovery.discover(self.hass, 'another service', 'discovery info',
                           'test_component')
        self.hass.pool.block_till_done()

        assert mock_setup_component.called
        assert mock_setup_component.call_args[0] == \
            (self.hass, 'test_component', None)
        assert len(calls_single) == 1
        assert calls_single[0] == ('test service', 'discovery info')

        assert len(calls_single) == 1
        assert len(calls_multi) == 2
        assert ['test service', 'another service'] == [info[0] for info
                                                       in calls_multi]
示例#5
0
def wemo_startup_scan(hass, config):
    """Run device discovery once the component has been initialized."""
    import pywemo

    _LOGGER.info("Scanning for WeMo devices.")
    devices = [(device.host, device) for device in pywemo.discover_devices()]

    # Add static devices from the config file.
    devices.extend((address, None)
                   for address in config.get(DOMAIN, {}).get(CONF_STATIC, []))

    for address, device in devices:
        port = pywemo.ouimeaux_device.probe_wemo(address)
        if not port:
            _LOGGER.warning('Unable to probe wemo at %s', address)
            continue
        _LOGGER.info('Adding wemo at %s:%i', address, port)

        url = 'http://%s:%i/setup.xml' % (address, port)
        if device is None:
            device = pywemo.discovery.device_from_description(url, None)

        discovery_info = (device.name, device.model_name, url, device.mac,
                          device.serialnumber)
        discovery.discover(hass, SERVICE_WEMO, discovery_info)
示例#6
0
 def component1_setup(hass, config):
     """Setup mock component."""
     discovery.discover(hass, 'test_component2',
                        component='test_component2')
     discovery.discover(hass, 'test_component3',
                        component='test_component3')
     return True
示例#7
0
def setup(hass, config):
    """Common setup for WeMo devices."""
    import pywemo

    global SUBSCRIPTION_REGISTRY
    SUBSCRIPTION_REGISTRY = pywemo.SubscriptionRegistry()
    SUBSCRIPTION_REGISTRY.start()

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

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_wemo)

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

        # Only register a device once
        if serial in KNOWN_DEVICES:
            return
        _LOGGER.debug('Discovered unique 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.listen(hass, SERVICE_WEMO, discovery_dispatch)

    _LOGGER.info("Scanning for WeMo devices.")
    devices = [(device.host, device) for device in pywemo.discover_devices()]

    # Add static devices from the config file.
    devices.extend((address, None)
                   for address in config.get(DOMAIN, {}).get(CONF_STATIC, []))

    for address, device in devices:
        port = pywemo.ouimeaux_device.probe_wemo(address)
        if not port:
            _LOGGER.warning('Unable to probe wemo at %s', address)
            continue
        _LOGGER.info('Adding wemo at %s:%i', address, port)

        url = 'http://%s:%i/setup.xml' % (address, port)
        if device is None:
            device = pywemo.discovery.device_from_description(url, None)

        discovery_info = (device.name, device.model_name, url, device.mac,
                          device.serialnumber)
        discovery.discover(hass, SERVICE_WEMO, discovery_info)
    return True
示例#8
0
def setup(hass, config):
    """Common setup for WeMo devices."""
    import pywemo

    global SUBSCRIPTION_REGISTRY
    SUBSCRIPTION_REGISTRY = pywemo.SubscriptionRegistry()
    SUBSCRIPTION_REGISTRY.start()

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

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_wemo)

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

        # Only register a device once
        if serial in KNOWN_DEVICES:
            return
        _LOGGER.debug('Discovered unique 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.listen(hass, SERVICE_WEMO, discovery_dispatch)

    _LOGGER.info("Scanning for WeMo devices.")
    devices = [(device.host, device) for device in pywemo.discover_devices()]

    # Add static devices from the config file.
    devices.extend((address, None)
                   for address in config.get(DOMAIN, {}).get(CONF_STATIC, []))

    for address, device in devices:
        port = pywemo.ouimeaux_device.probe_wemo(address)
        if not port:
            _LOGGER.warning('Unable to probe wemo at %s', address)
            continue
        _LOGGER.info('Adding wemo at %s:%i', address, port)

        url = 'http://%s:%i/setup.xml' % (address, port)
        if device is None:
            device = pywemo.discovery.device_from_description(url, None)

        discovery_info = (device.name, device.model_name, url, device.mac,
                          device.serialnumber)
        discovery.discover(hass, SERVICE_WEMO, discovery_info)
    return True
示例#9
0
    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',
                              '{}:{}'.format(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):
            _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.discover(hass, SERVICE_WEMO, discovery_info)

        _LOGGER.debug("WeMo device discovery has finished")
示例#10
0
    def new_service_listener(service, info):
        """Called when a new service is found."""
        with lock:
            logger.info("Found new service: %s %s", service, info)

            comp_plat = SERVICE_HANDLERS.get(service)

            # We do not know how to handle this service.
            if not comp_plat:
                return

            component, platform = comp_plat

            if platform is None:
                discover(hass, service, info, component, config)
            else:
                load_platform(hass, component, platform, info, config)
示例#11
0
    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',
                    '{}:{}'.format(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):
            _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.discover(hass, SERVICE_WEMO, discovery_info)

        _LOGGER.debug("WeMo device discovery has finished")
示例#12
0
    def new_service_listener(service, info):
        """Called when a new service is found."""
        with lock:
            logger.info("Found new service: %s %s", service, info)

            comp_plat = SERVICE_HANDLERS.get(service)

            # We do not know how to handle this service.
            if not comp_plat:
                return

            component, platform = comp_plat

            if platform is None:
                discover(hass, service, info, component, config)
            else:
                load_platform(hass, component, platform, info, config)
示例#13
0
def setup(hass, config):
    """Set up OctoPrint API."""
    base_url = 'http://{}/api/'.format(config[DOMAIN][CONF_HOST])
    api_key = config[DOMAIN][CONF_API_KEY]

    global OCTOPRINT
    try:
        OCTOPRINT = OctoPrintAPI(base_url, api_key)
        OCTOPRINT.get('printer')
        OCTOPRINT.get('job')
    except requests.exceptions.RequestException as conn_err:
        _LOGGER.error("Error setting up OctoPrint API: %r", conn_err)
        return False

    for component, discovery_service in (
            ('sensor', DISCOVER_SENSORS),
            ('binary_sensor', DISCOVER_BINARY_SENSORS)):
        discovery.discover(hass, discovery_service, component=component,
                           hass_config=config)

    return True
示例#14
0
def setup(hass, config):
    """Set up OctoPrint API."""
    base_url = 'http://{}/api/'.format(config[DOMAIN][CONF_HOST])
    api_key = config[DOMAIN][CONF_API_KEY]

    global OCTOPRINT
    try:
        OCTOPRINT = OctoPrintAPI(base_url, api_key)
        OCTOPRINT.get('printer')
        OCTOPRINT.get('job')
    except requests.exceptions.RequestException as conn_err:
        _LOGGER.error("Error setting up OctoPrint API: %r", conn_err)
        return False

    for component, discovery_service in (('sensor', DISCOVER_SENSORS),
                                         ('binary_sensor',
                                          DISCOVER_BINARY_SENSORS)):
        discovery.discover(hass,
                           discovery_service,
                           component=component,
                           hass_config=config)

    return True
示例#15
0
def setup(hass, config):
    """Set up for WeMo devices."""
    import pywemo

    global SUBSCRIPTION_REGISTRY
    SUBSCRIPTION_REGISTRY = pywemo.SubscriptionRegistry()
    SUBSCRIPTION_REGISTRY.start()

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

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_wemo)

    def discovery_dispatch(service, discovery_info):
        """Dispatcher for 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:
            return
        _LOGGER.debug('Discovered unique 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.listen(hass, SERVICE_WEMO, discovery_dispatch)

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

    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 'http://{}:{}/setup.xml'.format(host, port)

    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 %s',
                '{}:{}'.format(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 %s (%s)', url, err)
            continue

        devices.append((url, device))

    if config.get(DOMAIN, {}).get(CONF_DISCOVERY):
        _LOGGER.debug("Scanning for WeMo devices.")
        devices.extend(
            (setup_url_for_device(device), device)
            for device in pywemo.discover_devices())

    for url, device in devices:
        _LOGGER.debug('Adding wemo 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.discover(hass, SERVICE_WEMO, discovery_info)
    return True
示例#16
0
def setup(hass, config):
    """Set up for WeMo devices."""
    import pywemo

    global SUBSCRIPTION_REGISTRY
    SUBSCRIPTION_REGISTRY = pywemo.SubscriptionRegistry()
    SUBSCRIPTION_REGISTRY.start()

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

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_wemo)

    def discovery_dispatch(service, discovery_info):
        """Dispatcher for 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:
            return
        _LOGGER.debug('Discovered unique 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.listen(hass, SERVICE_WEMO, discovery_dispatch)

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

    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 'http://{}:{}/setup.xml'.format(host, port)

    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 %s',
                          '{}:{}'.format(host, port) if port else host)
            return False

        try:
            device = pywemo.discovery.device_from_description(url, None)
        except (requests.exceptions.ConnectionError,
                requests.exceptions.Timeout) as err:
            _LOGGER.error('Unable to access %s (%s)', url, err)
            return False

        devices.append((url, device))

    _LOGGER.info("Scanning for WeMo devices.")
    devices.extend((setup_url_for_device(device), device)
                   for device in pywemo.discover_devices())

    for url, device in devices:
        _LOGGER.info('Adding wemo 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.discover(hass, SERVICE_WEMO, discovery_info)
    return True
 def component1_setup(hass, config):
     """Setup mock component."""
     discovery.discover(hass, 'test_component2')
     return True