Example #1
0
    def test_load_order_components(self):
        loader.set_component('mod1', MockModule('mod1', ['group']))
        loader.set_component('mod2', MockModule('mod2', ['mod1', 'sun']))
        loader.set_component('mod3', MockModule('mod3', ['mod2']))
        loader.set_component('mod4', MockModule('mod4', ['group']))

        self.assertEqual(['group', 'mod4', 'mod1', 'sun', 'mod2', 'mod3'],
                         loader.load_order_components(['mod4', 'mod3',
                                                       'mod2']))

        loader.set_component('mod1', MockModule('mod1'))
        loader.set_component('mod2', MockModule('mod2', ['group']))

        self.assertEqual(['mod1', 'group', 'mod2'],
                         loader.load_order_components(['mod2', 'mod1']))

        # Add a non existing one
        self.assertEqual(['mod1', 'group', 'mod2'],
                         loader.load_order_components(
                             ['mod2', 'nonexisting', 'mod1']))

        # Depend on a non existing one
        loader.set_component('mod1', MockModule('mod1', ['nonexisting']))

        self.assertEqual(['group', 'mod2'],
                         loader.load_order_components(['mod2', 'mod1']))
Example #2
0
    def test_load_order_components(self):
        loader.set_component('mod1', MockModule('mod1', ['group']))
        loader.set_component('mod2', MockModule('mod2', ['mod1', 'sun']))
        loader.set_component('mod3', MockModule('mod3', ['mod2']))
        loader.set_component('mod4', MockModule('mod4', ['group']))

        self.assertEqual(
            ['group', 'mod4', 'mod1', 'sun', 'mod2', 'mod3'],
            loader.load_order_components(['mod4', 'mod3', 'mod2']))

        loader.set_component('mod1', MockModule('mod1'))
        loader.set_component('mod2', MockModule('mod2', ['group']))

        self.assertEqual(
            ['mod1', 'group', 'mod2'],
            loader.load_order_components(['mod2', 'mod1']))

        # Add a non existing one
        self.assertEqual(
            ['mod1', 'group', 'mod2'],
            loader.load_order_components(['mod2', 'nonexisting', 'mod1']))

        # Depend on a non existing one
        loader.set_component('mod1', MockModule('mod1', ['nonexisting']))

        self.assertEqual(
            ['group', 'mod2'],
            loader.load_order_components(['mod2', 'mod1']))
Example #3
0
def from_config_dict(config, hass=None, config_dir=None, enable_log=True,
                     verbose=False, daemon=False, skip_pip=False,
                     log_rotate_days=None):
    """Try to configure Home Assistant from a config dict.

    Dynamically loads required components and its dependencies.
    """
    if hass is None:
        hass = core.HomeAssistant()
        if config_dir is not None:
            config_dir = os.path.abspath(config_dir)
            hass.config.config_dir = config_dir
            mount_local_lib_path(config_dir)

    try:
        process_ha_core_config(hass, config_util.CORE_CONFIG_SCHEMA(
            config.get(core.DOMAIN, {})))
    except vol.MultipleInvalid as ex:
        _LOGGER.error('Invalid config for [homeassistant]: %s', ex)
        return None

    process_ha_config_upgrade(hass)

    if enable_log:
        enable_logging(hass, verbose, daemon, log_rotate_days)

    hass.config.skip_pip = skip_pip
    if skip_pip:
        _LOGGER.warning('Skipping pip installation of required modules. '
                        'This may cause issues.')

    _ensure_loader_prepared(hass)

    # Make a copy because we are mutating it.
    # Convert it to defaultdict so components can always have config dict
    # Convert values to dictionaries if they are None
    config = defaultdict(
        dict, {key: value or {} for key, value in config.items()})

    # Filter out the repeating and common config section [homeassistant]
    components = set(key.split(' ')[0] for key in config.keys()
                     if key != core.DOMAIN)

    if not core_components.setup(hass, config):
        _LOGGER.error('Home Assistant core failed to initialize. '
                      'Further initialization aborted.')

        return hass

    _LOGGER.info('Home Assistant core initialized')

    # Give event decorators access to HASS
    event_decorators.HASS = hass
    service.HASS = hass

    # Setup the components
    for domain in loader.load_order_components(components):
        _setup_component(hass, domain, config)

    return hass
Example #4
0
def from_config_dict(config, hass=None):
    """
    Tries to configure Home Assistant from a config dict.

    Dynamically loads required components and its dependencies.
    """
    if hass is None:
        hass = homeassistant.HomeAssistant()

    enable_logging(hass)

    loader.prepare(hass)

    # Make a copy because we are mutating it.
    # Convert it to defaultdict so components can always have config dict
    config = defaultdict(dict, config)

    # Filter out the repeating and common config section [homeassistant]
    components = (key for key in config.keys()
                  if ' ' not in key and key != homeassistant.DOMAIN)

    if not core_components.setup(hass, config):
        _LOGGER.error("Home Assistant core failed to initialize. "
                      "Further initialization aborted.")

        return hass

    _LOGGER.info("Home Assistant core initialized")

    # Setup the components
    for domain in loader.load_order_components(components):
        setup_component(hass, domain, config)

    return hass
Example #5
0
def from_config_dict(config,
                     hass=None,
                     config_dir=None,
                     enable_log=True,
                     verbose=False,
                     daemon=False,
                     skip_pip=False,
                     log_rotate_days=None):
    """Try to configure Home Assistant from a config dict.

    Dynamically loads required components and its dependencies.
    """
    if hass is None:
        hass = core.HomeAssistant()
        if config_dir is not None:
            config_dir = os.path.abspath(config_dir)
            hass.config.config_dir = config_dir
            mount_local_lib_path(config_dir)

    process_ha_config_upgrade(hass)
    process_ha_core_config(hass, config.get(core.DOMAIN, {}))

    if enable_log:
        enable_logging(hass, verbose, daemon, log_rotate_days)

    hass.config.skip_pip = skip_pip
    if skip_pip:
        _LOGGER.warning('Skipping pip installation of required modules. '
                        'This may cause issues.')

    _ensure_loader_prepared(hass)

    # Make a copy because we are mutating it.
    # Convert it to defaultdict so components can always have config dict
    # Convert values to dictionaries if they are None
    config = defaultdict(dict,
                         {key: value or {}
                          for key, value in config.items()})

    # Filter out the repeating and common config section [homeassistant]
    components = set(
        key.split(' ')[0] for key in config.keys() if key != core.DOMAIN)

    if not core_components.setup(hass, config):
        _LOGGER.error('Home Assistant core failed to initialize. '
                      'Further initialization aborted.')

        return hass

    _LOGGER.info('Home Assistant core initialized')

    # Give event decorators access to HASS
    event_decorators.HASS = hass
    service.HASS = hass

    # Setup the components
    for domain in loader.load_order_components(components):
        _setup_component(hass, domain, config)

    return hass
Example #6
0
def from_config_dict(config, hass=None):
    """
    Tries to configure Home Assistant from a config dict.

    Dynamically loads required components and its dependencies.
    """
    if hass is None:
        hass = homeassistant.HomeAssistant()

    process_ha_core_config(hass, config.get(homeassistant.DOMAIN, {}))

    enable_logging(hass)

    _ensure_loader_prepared(hass)

    # Make a copy because we are mutating it.
    # Convert it to defaultdict so components can always have config dict
    # Convert values to dictionaries if they are None
    config = defaultdict(dict, {key: value or {} for key, value in config.items()})

    # Filter out the repeating and common config section [homeassistant]
    components = (key for key in config.keys() if " " not in key and key != homeassistant.DOMAIN)

    if not core_components.setup(hass, config):
        _LOGGER.error("Home Assistant core failed to initialize. " "Further initialization aborted.")

        return hass

    _LOGGER.info("Home Assistant core initialized")

    # Setup the components
    for domain in loader.load_order_components(components):
        _setup_component(hass, domain, config)

    return hass
Example #7
0
def from_config_dict(config, hass=None):
    """
    Tries to configure Home Assistant from a config dict.

    Dynamically loads required components and its dependencies.
    """
    if hass is None:
        hass = homeassistant.HomeAssistant()

    logger = logging.getLogger(__name__)

    loader.prepare(hass)

    # Make a copy because we are mutating it.
    # Convert it to defaultdict so components can always have config dict
    config = defaultdict(dict, config)

    # Filter out the repeating and common config section [homeassistant]
    components = (key for key in config.keys()
                  if ' ' not in key and key != homeassistant.DOMAIN)

    if not core_components.setup(hass, config):
        logger.error(("Home Assistant core failed to initialize. "
                      "Further initialization aborted."))

        return hass

    logger.info("Home Assistant core initialized")

    # Setup the components

    # We assume that all components that load before the group component loads
    # are components that poll devices. As their tasks are IO based, we will
    # add an extra worker for each of them.
    add_worker = True

    for domain in loader.load_order_components(components):
        component = loader.get_component(domain)

        try:
            if component.setup(hass, config):
                logger.info("component %s initialized", domain)

                add_worker = add_worker and domain != "group"

                if add_worker:
                    hass.pool.add_worker()

            else:
                logger.error("component %s failed to initialize", domain)

        except Exception:  # pylint: disable=broad-except
            logger.exception("Error during setup of component %s", domain)

    return hass
Example #8
0
def from_config_dict(
    config,
    hass=None,
    config_dir=None,
    enable_log=True,
    verbose=False,
    daemon=False,
    skip_pip=False,
    log_rotate_days=None,
):
    """
    Tries to configure Home Assistant from a config dict.

    Dynamically loads required components and its dependencies.
    """
    if hass is None:
        hass = core.HomeAssistant()
        if config_dir is not None:
            config_dir = os.path.abspath(config_dir)
            hass.config.config_dir = config_dir
            mount_local_lib_path(config_dir)

    process_ha_config_upgrade(hass)
    process_ha_core_config(hass, config.get(core.DOMAIN, {}))

    if enable_log:
        enable_logging(hass, verbose, daemon, log_rotate_days)

    hass.config.skip_pip = skip_pip
    if skip_pip:
        _LOGGER.warning("Skipping pip installation of required modules. " "This may cause issues.")

    _ensure_loader_prepared(hass)

    # Make a copy because we are mutating it.
    # Convert it to defaultdict so components can always have config dict
    # Convert values to dictionaries if they are None
    config = defaultdict(dict, {key: value or {} for key, value in config.items()})

    # Filter out the repeating and common config section [homeassistant]
    components = set(key.split(" ")[0] for key in config.keys() if key != core.DOMAIN)

    if not core_components.setup(hass, config):
        _LOGGER.error("Home Assistant core failed to initialize. " "Further initialization aborted.")

        return hass

    _LOGGER.info("Home Assistant core initialized")

    # Setup the components
    for domain in loader.load_order_components(components):
        _setup_component(hass, domain, config)

    return hass
Example #9
0
    def component_setup():
        """Set up a component."""
        if not core_components.setup(hass, config):
            _LOGGER.error("Home Assistant core failed to initialize. " "Further initialization aborted.")
            return hass

        persistent_notification.setup(hass, config)

        _LOGGER.info("Home Assistant core initialized")

        # Give event decorators access to HASS
        event_decorators.HASS = hass
        service.HASS = hass

        # Setup the components
        for domain in loader.load_order_components(components):
            _setup_component(hass, domain, config)
Example #10
0
    def component_setup():
        """Set up a component."""
        if not core_components.setup(hass, config):
            _LOGGER.error('Home Assistant core failed to initialize. '
                          'Further initialization aborted.')
            return hass

        persistent_notification.setup(hass, config)

        _LOGGER.info('Home Assistant core initialized')

        # Give event decorators access to HASS
        event_decorators.HASS = hass
        service.HASS = hass

        # Setup the components
        for domain in loader.load_order_components(components):
            _setup_component(hass, domain, config)
Example #11
0
def from_config_dict(config, hass=None, config_dir=None, enable_log=True,
                     verbose=False, daemon=False):
    """
    Tries to configure Home Assistant from a config dict.

    Dynamically loads required components and its dependencies.
    """
    if hass is None:
        hass = core.HomeAssistant()
        if config_dir is not None:
            config_dir = os.path.abspath(config_dir)
            hass.config.config_dir = config_dir
            mount_local_lib_path(config_dir)

    process_ha_core_config(hass, config.get(core.DOMAIN, {}))

    if enable_log:
        enable_logging(hass, verbose, daemon)

    _ensure_loader_prepared(hass)

    # Make a copy because we are mutating it.
    # Convert it to defaultdict so components can always have config dict
    # Convert values to dictionaries if they are None
    config = defaultdict(
        dict, {key: value or {} for key, value in config.items()})

    # Filter out the repeating and common config section [homeassistant]
    components = (key for key in config.keys()
                  if ' ' not in key and key != core.DOMAIN)

    if not core_components.setup(hass, config):
        _LOGGER.error('Home Assistant core failed to initialize. '
                      'Further initialization aborted.')

        return hass

    _LOGGER.info('Home Assistant core initialized')

    # Setup the components
    for domain in loader.load_order_components(components):
        _setup_component(hass, domain, config)

    return hass
Example #12
0
def from_config_dict(config, hass=None):
    """
    Tries to configure Home Assistant from a config dict.


    Dynamically loads required components and its dependencies.
    """

    # Make a copy because we are mutating it.
    # Convert it to defaultdict so components can always have config dict
    config = defaultdict(dict, config)

    if hass is None:
        hass = homeassistant.HomeAssistant(config)

    logger = logging.getLogger(__name__)

    loader.prepare(hass)


    # Filter out the repeating and common config section [homeassistant]
    components = (key for key in config.keys()
                  if ' ' not in key and key != homeassistant.DOMAIN)

    # Setup the components
    if core_components.setup(hass, config):
        logger.info("Home Assistant core initialized")

        for domain in loader.load_order_components(components):
            if domain is not "pushbullet":
                try:
                    if loader.get_component(domain).setup(hass, config):
                        logger.info("component %s initialized", domain)
                    else:
                        logger.error("component %s failed to initialize", domain)

                except Exception:  # pylint: disable=broad-except
                    logger.exception("Error during setup of component %s", domain)

    else:
        logger.error(("Home Assistant core failed to initialize. "
                      "Further initialization aborted."))

    return hass
Example #13
0
def from_config_dict(config, hass=None):
    """
    Tries to configure Home Assistant from a config dict.

    Dynamically loads required components and its dependencies.
    """
    if hass is None:
        hass = homeassistant.HomeAssistant()

    logger = logging.getLogger(__name__)

    loader.prepare(hass)

    # Make a copy because we are mutating it.
    # Convert it to defaultdict so components can always have config dict
    config = defaultdict(dict, config)

    # Filter out the repeating and common config section [homeassistant]
    components = (key for key in config.keys()
                  if ' ' not in key and key != homeassistant.DOMAIN)

    # Setup the components
    if core_components.setup(hass, config):
        logger.info("Home Assistant core initialized")

        for domain in loader.load_order_components(components):
            try:
                if loader.get_component(domain).setup(hass, config):
                    logger.info("component %s initialized", domain)
                else:
                    logger.error("component %s failed to initialize", domain)

            except Exception:  # pylint: disable=broad-except
                logger.exception("Error during setup of component %s", domain)

    else:
        logger.error(("Home Assistant core failed to initialize. "
                      "Further initialization aborted."))

    return hass
Example #14
0
def from_config_dict(config, hass=None):
    """
    Tries to configure Home Assistant from a config dict.

    Dynamically loads required components and its dependencies.
    """
    if hass is None:
        hass = core.HomeAssistant()

    process_ha_core_config(hass, config.get(core.DOMAIN, {}))

    enable_logging(hass)

    _ensure_loader_prepared(hass)

    # Make a copy because we are mutating it.
    # Convert it to defaultdict so components can always have config dict
    # Convert values to dictionaries if they are None
    config = defaultdict(dict,
                         {key: value or {}
                          for key, value in config.items()})

    # Filter out the repeating and common config section [homeassistant]
    components = (key for key in config.keys()
                  if ' ' not in key and key != core.DOMAIN)

    if not core_components.setup(hass, config):
        _LOGGER.error('Home Assistant core failed to initialize. '
                      'Further initialization aborted.')

        return hass

    _LOGGER.info('Home Assistant core initialized')

    # Setup the components
    for domain in loader.load_order_components(components):
        _setup_component(hass, domain, config)

    return hass
Example #15
0
def async_from_config_dict(config: Dict[str, Any],
                           hass: core.HomeAssistant,
                           config_dir: Optional[str]=None,
                           enable_log: bool=True,
                           verbose: bool=False,
                           skip_pip: bool=False,
                           log_rotate_days: Any=None) \
                           -> Optional[core.HomeAssistant]:
    """Try to configure Home Assistant from a config dict.

    Dynamically loads required components and its dependencies.
    This method is a coroutine.
    """
    hass.async_track_tasks()
    setup_lock = hass.data.get('setup_lock')
    if setup_lock is None:
        setup_lock = hass.data['setup_lock'] = asyncio.Lock(loop=hass.loop)

    yield from setup_lock.acquire()

    core_config = config.get(core.DOMAIN, {})

    try:
        yield from conf_util.async_process_ha_core_config(hass, core_config)
    except vol.Invalid as ex:
        async_log_exception(ex, 'homeassistant', core_config, hass)
        return None

    yield from hass.loop.run_in_executor(None,
                                         conf_util.process_ha_config_upgrade,
                                         hass)

    if enable_log:
        enable_logging(hass, verbose, log_rotate_days)

    hass.config.skip_pip = skip_pip
    if skip_pip:
        _LOGGER.warning('Skipping pip installation of required modules. '
                        'This may cause issues.')

    if not loader.PREPARED:
        yield from hass.loop.run_in_executor(None, loader.prepare, hass)

    # Merge packages
    conf_util.merge_packages_config(
        config, core_config.get(conf_util.CONF_PACKAGES, {}))

    # Make a copy because we are mutating it.
    # Use OrderedDict in case original one was one.
    # Convert values to dictionaries if they are None
    new_config = OrderedDict()
    for key, value in config.items():
        new_config[key] = value or {}
    config = new_config

    # Filter out the repeating and common config section [homeassistant]
    components = set(
        key.split(' ')[0] for key in config.keys() if key != core.DOMAIN)

    # setup components
    # pylint: disable=not-an-iterable
    res = yield from core_components.async_setup(hass, config)
    if not res:
        _LOGGER.error('Home Assistant core failed to initialize. '
                      'Further initialization aborted.')
        return hass

    yield from persistent_notification.async_setup(hass, config)

    _LOGGER.info('Home Assistant core initialized')

    # Give event decorators access to HASS
    event_decorators.HASS = hass
    service.HASS = hass

    # Setup the components
    for domain in loader.load_order_components(components):
        yield from _async_setup_component(hass, domain, config)

    setup_lock.release()

    yield from hass.async_stop_track_tasks()

    return hass
Example #16
0
def async_from_config_dict(config: Dict[str, Any],
                           hass: core.HomeAssistant,
                           config_dir: Optional[str]=None,
                           enable_log: bool=True,
                           verbose: bool=False,
                           skip_pip: bool=False,
                           log_rotate_days: Any=None) \
                           -> Optional[core.HomeAssistant]:
    """Try to configure Home Assistant from a config dict.

    Dynamically loads required components and its dependencies.
    This method is a coroutine.
    """
    core_config = config.get(core.DOMAIN, {})

    try:
        yield from conf_util.async_process_ha_core_config(hass, core_config)
    except vol.Invalid as ex:
        async_log_exception(ex, 'homeassistant', core_config, hass)
        return None

    yield from hass.loop.run_in_executor(None,
                                         conf_util.process_ha_config_upgrade,
                                         hass)

    if enable_log:
        enable_logging(hass, verbose, log_rotate_days)

    hass.config.skip_pip = skip_pip
    if skip_pip:
        _LOGGER.warning('Skipping pip installation of required modules. '
                        'This may cause issues.')

    if not loader.PREPARED:
        yield from hass.loop.run_in_executor(None, loader.prepare, hass)

    # Make a copy because we are mutating it.
    # Convert it to defaultdict so components can always have config dict
    # Convert values to dictionaries if they are None
    config = defaultdict(dict,
                         {key: value or {}
                          for key, value in config.items()})

    # Filter out the repeating and common config section [homeassistant]
    components = set(
        key.split(' ')[0] for key in config.keys() if key != core.DOMAIN)

    # setup components
    # pylint: disable=not-an-iterable
    res = yield from core_components.async_setup(hass, config)
    if not res:
        _LOGGER.error('Home Assistant core failed to initialize. '
                      'Further initialization aborted.')
        return hass

    yield from persistent_notification.async_setup(hass, config)

    _LOGGER.info('Home Assistant core initialized')

    # Give event decorators access to HASS
    event_decorators.HASS = hass
    service.HASS = hass

    # Setup the components
    for domain in loader.load_order_components(components):
        yield from _async_setup_component(hass, domain, config)

    return hass
Example #17
0
def async_from_config_dict(config: Dict[str, Any],
                           hass: core.HomeAssistant,
                           config_dir: Optional[str]=None,
                           enable_log: bool=True,
                           verbose: bool=False,
                           skip_pip: bool=False,
                           log_rotate_days: Any=None) \
                           -> Optional[core.HomeAssistant]:
    """Try to configure Home Assistant from a config dict.

    Dynamically loads required components and its dependencies.
    This method is a coroutine.
    """
    hass.async_track_tasks()
    setup_lock = hass.data.get('setup_lock')
    if setup_lock is None:
        setup_lock = hass.data['setup_lock'] = asyncio.Lock(loop=hass.loop)

    yield from setup_lock.acquire()

    core_config = config.get(core.DOMAIN, {})

    try:
        yield from conf_util.async_process_ha_core_config(hass, core_config)
    except vol.Invalid as ex:
        async_log_exception(ex, 'homeassistant', core_config, hass)
        return None

    yield from hass.loop.run_in_executor(
        None, conf_util.process_ha_config_upgrade, hass)

    if enable_log:
        async_enable_logging(hass, verbose, log_rotate_days)

    hass.config.skip_pip = skip_pip
    if skip_pip:
        _LOGGER.warning('Skipping pip installation of required modules. '
                        'This may cause issues.')

    if not loader.PREPARED:
        yield from hass.loop.run_in_executor(None, loader.prepare, hass)

    # Merge packages
    conf_util.merge_packages_config(
        config, core_config.get(conf_util.CONF_PACKAGES, {}))

    # Make a copy because we are mutating it.
    # Use OrderedDict in case original one was one.
    # Convert values to dictionaries if they are None
    new_config = OrderedDict()
    for key, value in config.items():
        new_config[key] = value or {}
    config = new_config

    # Filter out the repeating and common config section [homeassistant]
    components = set(key.split(' ')[0] for key in config.keys()
                     if key != core.DOMAIN)

    # setup components
    # pylint: disable=not-an-iterable
    res = yield from core_components.async_setup(hass, config)
    if not res:
        _LOGGER.error('Home Assistant core failed to initialize. '
                      'Further initialization aborted.')
        return hass

    yield from persistent_notification.async_setup(hass, config)

    _LOGGER.info('Home Assistant core initialized')

    # Give event decorators access to HASS
    event_decorators.HASS = hass
    service.HASS = hass

    # Setup the components
    dependency_blacklist = loader.DEPENDENCY_BLACKLIST - set(components)

    for domain in loader.load_order_components(components):
        if domain in dependency_blacklist:
            raise HomeAssistantError(
                '{} is not allowed to be a dependency'.format(domain))

        yield from _async_setup_component(hass, domain, config)

    setup_lock.release()

    yield from hass.async_stop_track_tasks()

    async_register_signal_handling(hass)
    return hass