Example #1
0
def run(args):
    """Handle ensure configuration commandline script."""
    # Disable logging
    logging.getLogger('homeassistant.core').setLevel(logging.CRITICAL)

    parser = argparse.ArgumentParser(
        description=("Run a Home Assistant benchmark."))
    parser.add_argument('name', choices=BENCHMARKS)
    parser.add_argument('--script', choices=['benchmark'])

    args = parser.parse_args()

    bench = BENCHMARKS[args.name]

    print('Using event loop:', asyncio.get_event_loop_policy().__module__)

    with suppress(KeyboardInterrupt):
        while True:
            loop = asyncio.new_event_loop()
            hass = core.HomeAssistant(loop)
            hass.async_stop_track_tasks()
            runtime = loop.run_until_complete(bench(hass))
            print('Benchmark {} done in {}s'.format(bench.__name__, runtime))
            loop.run_until_complete(hass.async_stop())
            loop.close()

    return 0
Example #2
0
async def async_check_config(config_dir):
    """Check the HA config."""
    hass = core.HomeAssistant()
    hass.config.config_dir = config_dir
    components = await async_check_ha_config_file(hass)
    await hass.async_stop(force=True)
    return components
Example #3
0
def from_config_file(config_path,
                     hass=None,
                     verbose=False,
                     daemon=False,
                     skip_pip=True,
                     log_rotate_days=None):
    """
    Reads the configuration file and tries to start all the required
    functionality. Will add functionality to 'hass' parameter if given,
    instantiates a new Home Assistant object if 'hass' is not given.
    """
    if hass is None:
        hass = core.HomeAssistant()

    # Set config dir to directory holding config file
    config_dir = os.path.abspath(os.path.dirname(config_path))
    hass.config.config_dir = config_dir
    mount_local_lib_path(config_dir)

    enable_logging(hass, verbose, daemon, log_rotate_days)

    config_dict = config_util.load_config_file(config_path)

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

    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
            hass.loop.run_until_complete(
                async_mount_local_lib_path(config_dir, hass.loop))

    # run task
    hass = hass.loop.run_until_complete(
        async_from_config_dict(config, hass, config_dir, enable_log, verbose,
                               skip_pip, log_rotate_days, log_file,
                               log_no_color))

    return hass
Example #5
0
def from_config_file(config_path: str,
                     hass: Optional[core.HomeAssistant]=None,
                     verbose: bool=False,
                     skip_pip: bool=True,
                     log_rotate_days: Any=None):
    """Read the configuration file and try to start all the functionality.

    Will add functionality to 'hass' parameter if given,
    instantiates a new Home Assistant object if 'hass' is not given.
    """
    if hass is None:
        hass = core.HomeAssistant()

    @asyncio.coroutine
    def _async_init_from_config_file(future):
        try:
            re_hass = yield from async_from_config_file(
                config_path, hass, verbose, skip_pip, log_rotate_days)
            future.set_result(re_hass)
        # pylint: disable=broad-except
        except Exception as exc:
            future.set_exception(exc)

    # run task
    future = asyncio.Future(loop=hass.loop)
    hass.loop.create_task(_async_init_from_config_file(future))
    hass.loop.run_until_complete(future)

    return future.result()
def run(args):
    """Handle benchmark commandline script."""
    # Disable logging
    logging.getLogger("homeassistant.core").setLevel(logging.CRITICAL)

    parser = argparse.ArgumentParser(
        description=("Run a Home Assistant benchmark."))
    parser.add_argument("name", choices=BENCHMARKS)
    parser.add_argument("--script", choices=["benchmark"])

    args = parser.parse_args()

    bench = BENCHMARKS[args.name]

    print("Using event loop:", asyncio.get_event_loop_policy().__module__)

    with suppress(KeyboardInterrupt):
        while True:
            loop = asyncio.new_event_loop()
            hass = core.HomeAssistant(loop)
            hass.async_stop_track_tasks()
            runtime = loop.run_until_complete(bench(hass))
            print(f"Benchmark {bench.__name__} done in {runtime}s")
            loop.run_until_complete(hass.async_stop())
            loop.close()
Example #7
0
def async_test_home_assistant(loop):
    """Return a Home Assistant object pointing at test config dir."""
    loop._thread_ident = threading.get_ident()

    hass = ha.HomeAssistant(loop)
    hass.async_track_tasks()

    hass.config.location_name = 'test home'
    hass.config.config_dir = get_test_config_dir()
    hass.config.latitude = 32.87336
    hass.config.longitude = -117.22743
    hass.config.elevation = 0
    hass.config.time_zone = date_util.get_time_zone('US/Pacific')
    hass.config.units = METRIC_SYSTEM
    hass.config.skip_pip = True

    if 'custom_components.test' not in loader.AVAILABLE_COMPONENTS:
        yield from loop.run_in_executor(None, loader.prepare, hass)

    hass.state = ha.CoreState.running

    # Mock async_start
    orig_start = hass.async_start

    @asyncio.coroutine
    def mock_async_start():
        """Start the mocking."""
        with patch.object(loop, 'add_signal_handler'), \
                patch('homeassistant.core._async_create_timer'):
            yield from orig_start()

    hass.async_start = mock_async_start

    return hass
Example #8
0
def setUpModule(mock_get_local_ip):  # pylint: disable=invalid-name
    """Initalize a Home Assistant server for testing this module."""
    global hass

    hass = ha.HomeAssistant()

    bootstrap.setup_component(
        hass, http.DOMAIN, {
            http.DOMAIN: {
                http.CONF_API_PASSWORD: API_PASSWORD,
                http.CONF_SERVER_PORT: SERVER_PORT
            }
        })

    hass.services.register('test', 'alexa', lambda call: calls.append(call))

    bootstrap.setup_component(
        hass, alexa.DOMAIN, {
            'alexa': {
                'intents': {
                    'WhereAreWeIntent': {
                        'speech': {
                            'type':
                            'plaintext',
                            'text':
                            """
                            {%- if is_state('device_tracker.paulus', 'home') and is_state('device_tracker.anne_therese', 'home') -%}
                                You are both home, you silly
                            {%- else -%}
                                Anne Therese is at {{ states("device_tracker.anne_therese") }} and Paulus is at {{ states("device_tracker.paulus") }}
                            {% endif %}
                        """,
                        }
                    },
                    'GetZodiacHoroscopeIntent': {
                        'speech': {
                            'type': 'plaintext',
                            'text':
                            'You told us your sign is {{ ZodiacSign }}.',
                        }
                    },
                    'CallServiceIntent': {
                        'speech': {
                            'type': 'plaintext',
                            'text': 'Service called',
                        },
                        'action': {
                            'service': 'test.alexa',
                            'data': {
                                'hello': 1
                            },
                            'entity_id': 'switch.test',
                        }
                    }
                }
            }
        })

    hass.start()
Example #9
0
 def setup_method(self, method):
     self.hass = ha.HomeAssistant()
     self.hass.states.set('zone.home', 'zoning', {
         'name': 'home',
         'latitude': 2.1,
         'longitude': 1.1,
         'radius': 10
     })
 def setup_method(self, method):
     """Setup things to be run when tests are started."""
     self.hass = ha.HomeAssistant()
     self.hass.config.latitude = 32.87336
     self.hass.config.longitude = 117.22743
     self.rs = cmd_rs.CommandRollershutter(self.hass, 'foo', 'cmd_up',
                                           'cmd_dn', 'cmd_stop',
                                           'cmd_state', None)  # FIXME
Example #11
0
    def setUp(self):  # pylint: disable=invalid-name
        self.hass = ha.HomeAssistant()

        self.test_entity = media_player.ENTITY_ID_FORMAT.format('living_room')
        self.hass.states.set(self.test_entity, STATE_OFF)

        self.test_entity2 = media_player.ENTITY_ID_FORMAT.format('bedroom')
        self.hass.states.set(self.test_entity2, "YouTube")
Example #12
0
    def setUp(self):  # pylint: disable=invalid-name
        self.hass = ha.HomeAssistant()
        self.calls = []

        def record_call(service):
            self.calls.append(service)

        self.hass.services.register('test', 'automation', record_call)
Example #13
0
    def setUp(self):  # pylint: disable=invalid-name
        """ Init needed objects. """
        self.hass = ha.HomeAssistant()
        loader.prepare(self.hass)
        self.assertTrue(comps.setup(self.hass, {}))

        self.hass.states.set('light.Bowl', STATE_ON)
        self.hass.states.set('light.Ceiling', STATE_OFF)
Example #14
0
 def setup_method(self, method):
     self.hass = ha.HomeAssistant()
     self.hass.config.latitude = 32.87336
     self.hass.config.longitude = 117.22743
     self.rs = cmd_rs.CommandRollershutter(self.hass, 'foo',
                                           'cmd_up', 'cmd_dn',
                                           'cmd_stop', 'cmd_state',
                                           None)  # FIXME
Example #15
0
async def async_setup_hass(
    *,
    config_dir: str,
    verbose: bool,
    log_rotate_days: int,
    log_file: str,
    log_no_color: bool,
    skip_pip: bool,
    safe_mode: bool,
) -> Optional[core.HomeAssistant]:
    """Set up Home Assistant."""
    hass = core.HomeAssistant()
    hass.config.config_dir = config_dir

    async_enable_logging(hass, verbose, log_rotate_days, log_file, log_no_color)

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

    if not await conf_util.async_ensure_config_exists(hass):
        _LOGGER.error("Error getting configuration path")
        return None

    _LOGGER.info("Config directory: %s", config_dir)

    config_dict = None

    if not safe_mode:
        await hass.async_add_executor_job(conf_util.process_ha_config_upgrade, hass)

        try:
            config_dict = await conf_util.async_hass_config_yaml(hass)
        except HomeAssistantError as err:
            _LOGGER.error(
                "Failed to parse configuration.yaml: %s. Falling back to safe mode",
                err,
            )
        else:
            if not is_virtual_env():
                await async_mount_local_lib_path(config_dir)

            await async_from_config_dict(config_dict, hass)
        finally:
            clear_secret_cache()

    if safe_mode or config_dict is None:
        _LOGGER.info("Starting in safe mode")

        http_conf = (await http.async_get_last_config(hass)) or {}

        await async_from_config_dict(
            {"safe_mode": {}, "http": http_conf}, hass,
        )

    return hass
Example #16
0
 def setUp(self):
     """Initialize values for this testcase class."""
     self.hass = ha.HomeAssistant()
     self.username = '******'
     self.password = '******'
     self.config = {
         'username': self.username,
         'password': self.password,
     }
Example #17
0
    def setup_method(self, method):
        self.hass = ha.HomeAssistant()

        self.calls = []

        def record_call(service):
            self.calls.append(service)

        self.hass.services.register('test', 'automation', record_call)
Example #18
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 #19
0
def async_test_home_assistant(loop):
    """Return a Home Assistant object pointing at test config dir."""
    global INST_COUNT
    INST_COUNT += 1
    loop._thread_ident = threading.get_ident()

    hass = ha.HomeAssistant(loop)

    orig_async_add_job = hass.async_add_job

    def async_add_job(target, *args):
        """Add a magic mock."""
        if isinstance(target, MagicMock):
            return
        return orig_async_add_job(target, *args)

    hass.async_add_job = async_add_job

    hass.config.location_name = 'test home'
    hass.config.config_dir = get_test_config_dir()
    hass.config.latitude = 32.87336
    hass.config.longitude = -117.22743
    hass.config.elevation = 0
    hass.config.time_zone = date_util.get_time_zone('US/Pacific')
    hass.config.units = METRIC_SYSTEM
    hass.config.skip_pip = True

    if 'custom_components.test' not in loader.AVAILABLE_COMPONENTS:
        yield from loop.run_in_executor(None, loader.prepare, hass)

    hass.state = ha.CoreState.running

    # Mock async_start
    orig_start = hass.async_start

    @asyncio.coroutine
    def mock_async_start():
        """Start the mocking."""
        # 1. We only mock time during tests
        # 2. We want block_till_done that is called inside stop_track_tasks
        with patch('homeassistant.core._async_create_timer'), \
                patch.object(hass, 'async_stop_track_tasks',
                             hass.async_block_till_done):
            yield from orig_start()

    hass.async_start = mock_async_start

    @ha.callback
    def clear_instance(event):
        """Clear global instance."""
        global INST_COUNT
        INST_COUNT -= 1

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_CLOSE, clear_instance)

    return hass
Example #20
0
    def setUp(self):  # pylint: disable=invalid-name
        """ Init needed objects. """
        self.hass = ha.HomeAssistant()

        self.hass.states.set('light.Bowl', STATE_ON)
        self.hass.states.set('light.Ceiling', STATE_OFF)
        test_group = group.Group(
            self.hass, 'init_group', ['light.Bowl', 'light.Ceiling'], False)

        self.group_entity_id = test_group.entity_id
 def setUp(self):
     """Initialize values for this testcase class."""
     self.DEVICES = []
     self.hass = ha.HomeAssistant()
     self.key = 'foo'
     self.config = VALID_CONFIG_PWS
     self.lat = 37.8267
     self.lon = -122.423
     self.hass.config.latitude = self.lat
     self.hass.config.longitude = self.lon
Example #22
0
async def async_check_config(config_dir):
    """Check the HA config."""
    hass = core.HomeAssistant()
    hass.config.config_dir = config_dir
    await area_registry.async_load(hass)
    await device_registry.async_load(hass)
    await entity_registry.async_load(hass)
    components = await async_check_ha_config_file(hass)
    await hass.async_stop(force=True)
    return components
Example #23
0
async def hass(loop, hass_storage, sent_messages):
    """Home Assistant instance."""
    hass = core.HomeAssistant()

    hass.config.config_dir = str(Path(__file__).parent.parent)
    hass.config.skip_pip = True

    hass.config_entries = config_entries.ConfigEntries(hass, {})
    await hass.config_entries.async_initialize()
    return hass
Example #24
0
def async_test_home_assistant(loop):
    """Return a Home Assistant object pointing at test config dir."""
    hass = ha.HomeAssistant(loop)
    hass.config.async_load = Mock()
    store = auth.AuthStore(hass)
    hass.auth = auth.AuthManager(hass, store, {})
    ensure_auth_manager_loaded(hass.auth)
    INSTANCES.append(hass)

    orig_async_add_job = hass.async_add_job

    def async_add_job(target, *args):
        """Add a magic mock."""
        if isinstance(target, Mock):
            return mock_coro(target(*args))
        return orig_async_add_job(target, *args)

    hass.async_add_job = async_add_job

    hass.config.location_name = 'test home'
    hass.config.config_dir = get_test_config_dir()
    hass.config.latitude = 32.87336
    hass.config.longitude = -117.22743
    hass.config.elevation = 0
    hass.config.time_zone = date_util.get_time_zone('US/Pacific')
    hass.config.units = METRIC_SYSTEM
    hass.config.skip_pip = True

    hass.config_entries = config_entries.ConfigEntries(hass, {})
    hass.config_entries._entries = []
    hass.config_entries._store._async_ensure_stop_listener = lambda: None

    hass.state = ha.CoreState.running

    # Mock async_start
    orig_start = hass.async_start

    @asyncio.coroutine
    def mock_async_start():
        """Start the mocking."""
        # We only mock time during tests and we want to track tasks
        with patch('homeassistant.core._async_create_timer'), \
                patch.object(hass, 'async_stop_track_tasks'):
            yield from orig_start()

    hass.async_start = mock_async_start

    @ha.callback
    def clear_instance(event):
        """Clear global instance."""
        INSTANCES.remove(hass)

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_CLOSE, clear_instance)

    return hass
Example #25
0
    def setUp(self):  # pylint: disable=invalid-name
        self.hass = ha.HomeAssistant()
        self.assertTrue(
            notify.setup(self.hass, {'notify': {
                'platform': 'demo'
            }}))
        self.events = []

        def record_event(event):
            self.events.append(event)

        self.hass.bus.listen(demo.EVENT_NOTIFY, record_event)
Example #26
0
 def setUp(self):  # pylint: disable=invalid-name
     self.hass = ha.HomeAssistant()
     self.hass.config.temperature_unit = TEMP_CELCIUS
     thermostat.setup(
         self.hass, {
             'thermostat': {
                 'platform': 'heat_control',
                 'name': 'test',
                 'heater': ent_switch,
                 'target_sensor': ent_sensor
             }
         })
Example #27
0
 def setUp(self):
     """Initialize values for this testcase class."""
     self.hass = ha.HomeAssistant()
     self.key = 'foo'
     self.config = {
         'api_key': 'foo',
         'monitored_conditions': ['summary', 'icon']
     }
     self.lat = 37.8267
     self.lon = -122.423
     self.hass.config.latitude = self.lat
     self.hass.config.longitude = self.lon
Example #28
0
def test_track_task_functions(loop):
    """Test function to start/stop track task and initial state."""
    hass = ha.HomeAssistant(loop=loop)
    try:
        assert hass._track_task

        hass.async_stop_track_tasks()
        assert not hass._track_task

        hass.async_track_tasks()
        assert hass._track_task
    finally:
        yield from hass.async_stop()
Example #29
0
async def setup_and_run_hass(config_dir: str, args: argparse.Namespace) -> int:
    """Set up HASS and run."""
    # pylint: disable=redefined-outer-name
    from homeassistant import bootstrap, core

    hass = core.HomeAssistant()

    if args.demo_mode:
        config = {"frontend": {}, "demo": {}}  # type: Dict[str, Any]
        bootstrap.async_from_config_dict(
            config,
            hass,
            config_dir=config_dir,
            verbose=args.verbose,
            skip_pip=args.skip_pip,
            log_rotate_days=args.log_rotate_days,
            log_file=args.log_file,
            log_no_color=args.log_no_color,
        )
    else:
        config_file = await ensure_config_file(hass, config_dir)
        print("Config directory:", config_dir)
        await bootstrap.async_from_config_file(
            config_file,
            hass,
            verbose=args.verbose,
            skip_pip=args.skip_pip,
            log_rotate_days=args.log_rotate_days,
            log_file=args.log_file,
            log_no_color=args.log_no_color,
        )

    if args.open_ui:
        # Imported here to avoid importing asyncio before monkey patch
        from homeassistant.util.async_ import run_callback_threadsafe

        def open_browser(_: Any) -> None:
            """Open the web interface in a browser."""
            if hass.config.api is not None:
                import webbrowser

                webbrowser.open(hass.config.api.base_url)

        run_callback_threadsafe(
            hass.loop,
            hass.bus.async_listen_once,
            EVENT_HOMEASSISTANT_START,
            open_browser,
        )

    return await hass.async_run()
Example #30
0
def from_config_file(config_path, hass=None):
    """
    Reads the configuration file and tries to start all the required
    functionality. Will add functionality to 'hass' parameter if given,
    instantiates a new Home Assistant object if 'hass' is not given.
    """
    if hass is None:
        hass = core.HomeAssistant()

    # Set config dir to directory holding config file
    hass.config.config_dir = os.path.abspath(os.path.dirname(config_path))

    config_dict = config_util.load_config_file(config_path)

    return from_config_dict(config_dict, hass)