Пример #1
0
 def schedule_add_entities(self, new_entities, update_before_add=False):
     """Add entities for a single platform."""
     run_callback_threadsafe(
         self.component.hass.loop,
         self.async_schedule_add_entities, list(new_entities),
         update_before_add
     ).result()
Пример #2
0
def listen(hass, service, callback):
    """Setup listener for discovery of specific service.

    Service can be a string or a list/tuple.
    """
    run_callback_threadsafe(
        hass.loop, async_listen, hass, service, callback).result()
Пример #3
0
 def _schedule_add_entities(self, new_entities, update_before_add=False):
     """Synchronously schedule adding entities for a single platform."""
     run_callback_threadsafe(
         self.hass.loop,
         self._async_schedule_add_entities, list(new_entities),
         update_before_add
     ).result()
Пример #4
0
def turn_on(hass, entity_id=None, transition=None, brightness=None,
            rgb_color=None, xy_color=None, color_temp=None, white_value=None,
            profile=None, flash=None, effect=None, color_name=None):
    """Turn all or specified light on."""
    run_callback_threadsafe(
        hass.loop, async_turn_on, hass, entity_id, transition, brightness,
        rgb_color, xy_color, color_temp, white_value,
        profile, flash, effect, color_name).result()
Пример #5
0
    def set(self, entity_id, new_state, attributes=None, force_update=False):
        """Set the state of an entity, add entity if it does not exist.

        Attributes is an optional dict to specify attributes of this state.

        If you just update the attributes and not the state, last changed will
        not be affected.
        """
        run_callback_threadsafe(self._loop, self.async_set, entity_id, new_state, attributes, force_update).result()
    def test_get_clientsession_with_ssl(self):
        """Test init clientsession with ssl."""
        run_callback_threadsafe(self.hass.loop, client.async_get_clientsession,
                                self.hass).result()

        assert isinstance(
            self.hass.data[client.DATA_CLIENTSESSION], aiohttp.ClientSession)
        assert isinstance(
            self.hass.data[client.DATA_CONNECTOR], aiohttp.TCPConnector)
Пример #7
0
    def register(self, domain, service, service_func, schema=None):
        """
        Register a service.

        Schema is called to coerce and validate the service data.
        """
        run_callback_threadsafe(
            self._hass.loop,
            self.async_register, domain, service, service_func, schema
        ).result()
Пример #8
0
 def __init__(self, bus, add_job, loop):
     """Initialize a service registry."""
     self._services = {}
     self._add_job = add_job
     self._bus = bus
     self._loop = loop
     self._cur_id = 0
     run_callback_threadsafe(
         loop,
         bus.async_listen, EVENT_CALL_SERVICE, self._event_to_service_call,
     )
Пример #9
0
    def register(self, domain, service, service_func, description=None, schema=None):
        """
        Register a service.

        Description is a dict containing key 'description' to describe
        the service and a key 'fields' to describe the fields.

        Schema is called to coerce and validate the service data.
        """
        run_callback_threadsafe(
            self._hass.loop, self.async_register, domain, service, service_func, description, schema
        ).result()
Пример #10
0
def setup_and_run_hass(config_dir: str,
                       args: argparse.Namespace) -> Optional[int]:
    """Set up HASS and run."""
    from homeassistant import bootstrap

    # Run a simple daemon runner process on Windows to handle restarts
    if os.name == 'nt' and '--runner' not in sys.argv:
        nt_args = cmdline() + ['--runner']
        while True:
            try:
                subprocess.check_call(nt_args)
                sys.exit(0)
            except subprocess.CalledProcessError as exc:
                if exc.returncode != RESTART_EXIT_CODE:
                    sys.exit(exc.returncode)

    if args.demo_mode:
        config = {
            'frontend': {},
            'demo': {}
        }
        hass = bootstrap.from_config_dict(
            config, config_dir=config_dir, verbose=args.verbose,
            skip_pip=args.skip_pip, log_rotate_days=args.log_rotate_days,
            log_file=args.log_file)
    else:
        config_file = ensure_config_file(config_dir)
        print('Config directory:', config_dir)
        hass = bootstrap.from_config_file(
            config_file, verbose=args.verbose, skip_pip=args.skip_pip,
            log_rotate_days=args.log_rotate_days, log_file=args.log_file)

    if hass is None:
        return None

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

        def open_browser(event):
            """Open the webinterface 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 hass.start()
Пример #11
0
 def test_update_template_error(self, mock_render):
     """"Test the template update error."""
     vs = run_callback_threadsafe(
         self.hass.loop, template.BinarySensorTemplate,
         self.hass, 'parent', 'Parent', 'motion',
         template_hlpr.Template('{{ 1 > 1 }}', self.hass), MATCH_ALL,
         None, None
     ).result()
     mock_render.side_effect = TemplateError('foo')
     run_callback_threadsafe(self.hass.loop, vs.async_check_state).result()
     mock_render.side_effect = TemplateError(
         "UndefinedError: 'None' has no attribute")
     run_callback_threadsafe(self.hass.loop, vs.async_check_state).result()
Пример #12
0
    def test_get_clientsession_cleanup(self):
        """Test init clientsession with ssl."""
        run_callback_threadsafe(self.hass.loop, client.async_get_clientsession,
                                self.hass).result()

        assert isinstance(
            self.hass.data[client.DATA_CLIENTSESSION], aiohttp.ClientSession)
        assert isinstance(
            self.hass.data[client.DATA_CONNECTOR], aiohttp.TCPConnector)

        self.hass.bus.fire(EVENT_HOMEASSISTANT_CLOSE)
        self.hass.block_till_done()

        assert self.hass.data[client.DATA_CLIENTSESSION].closed
        assert self.hass.data[client.DATA_CONNECTOR].closed
Пример #13
0
    def test_setup_component_test_servcie_start_with_entity(self):
        """Setup ffmpeg component test service start."""
        with assert_setup_component(2):
            setup_component(self.hass, ffmpeg.DOMAIN, {ffmpeg.DOMAIN: {}})

        ffmpeg_dev = MockFFmpegDev(False)
        manager = self.hass.data[ffmpeg.DATA_FFMPEG]

        run_callback_threadsafe(
            self.hass.loop, manager.async_register_device, ffmpeg_dev).result()

        ffmpeg.start(self.hass, 'test.ffmpeg_device')
        self.hass.block_till_done()

        assert ffmpeg_dev.called_start
Пример #14
0
    def render(self, variables=None, **kwargs):
        """Render given template."""
        if variables is not None:
            kwargs.update(variables)

        return run_callback_threadsafe(
            self.hass.loop, self.async_render, kwargs).result()
Пример #15
0
def numeric_state(hass: HomeAssistant, entity, below=None, above=None,
                  value_template=None, variables=None):
    """Test a numeric state condition."""
    return run_callback_threadsafe(
        hass.loop, async_numeric_state, hass, entity, below, above,
        value_template, variables,
    ).result()
    def test_get_clientsession_cleanup(self):
        """Test init clientsession with ssl."""
        run_callback_threadsafe(self.hass.loop, client.async_get_clientsession,
                                self.hass).result()

        assert isinstance(
            self.hass.data[client.DATA_CLIENTSESSION], aiohttp.ClientSession)
        assert isinstance(
            self.hass.data[client.DATA_CONNECTOR], aiohttp.TCPConnector)

        run_coroutine_threadsafe(
            client.async_cleanup_websession(self.hass), self.hass.loop
        ).result()

        assert self.hass.data[client.DATA_CLIENTSESSION].closed
        assert self.hass.data[client.DATA_CONNECTOR].closed
Пример #17
0
    def remove(self, entity_id):
        """Remove the state of an entity.

        Returns boolean to indicate if an entity was removed.
        """
        return run_callback_threadsafe(
            self._loop, self.async_remove, entity_id).result()
Пример #18
0
 def _remove_listener(self, event_type, listener):
     """Remove a listener of a specific event_type."""
     future = run_callback_threadsafe(
         self._loop,
         self.async_remove_listener, event_type, listener
     )
     future.result()
Пример #19
0
    def test_setup_component_start(self, mock_start):
        """Setup ffmpeg component."""
        with assert_setup_component(1, 'binary_sensor'):
            setup_component(self.hass, 'binary_sensor', self.config)

        assert self.hass.data['ffmpeg'].binary == 'ffmpeg'
        assert len(self.hass.data['ffmpeg'].entities) == 1

        entity = self.hass.data['ffmpeg'].entities[0]
        self.hass.start()
        assert mock_start.called

        assert entity.state == 'off'
        run_callback_threadsafe(
            self.hass.loop, entity._async_callback, True).result()
        assert entity.state == 'on'
Пример #20
0
def request_config(hass, *args, **kwargs):
    """Create a new request for configuration.

    Will return an ID to be used for sequent calls.
    """
    return run_callback_threadsafe(
        hass.loop, ft.partial(async_request_config, hass, *args, **kwargs)
    ).result()
Пример #21
0
    def test_setup_component_test_register_no_startup(self):
        """Setup ffmpeg component test register without startup."""
        with assert_setup_component(2):
            setup_component(self.hass, ffmpeg.DOMAIN, {ffmpeg.DOMAIN: {}})

        self.hass.bus.async_listen_once = MagicMock()
        ffmpeg_dev = MockFFmpegDev(False)

        manager = self.hass.data[ffmpeg.DATA_FFMPEG]

        run_callback_threadsafe(
            self.hass.loop, manager.async_register_device, ffmpeg_dev).result()

        assert self.hass.bus.async_listen_once.called
        assert self.hass.bus.async_listen_once.call_count == 1
        assert len(manager.entities) == 1
        assert manager.entities[0] == ffmpeg_dev
Пример #22
0
    def render_with_possible_json_value(self, value, error_value=_SENTINEL):
        """Render template with value exposed.

        If valid JSON will expose value_json too.
        """
        return run_callback_threadsafe(
            self.hass.loop, self.async_render_with_possible_json_value, value,
            error_value).result()
Пример #23
0
    def extract_from_service(self, service):
        """Extract all known entities from a service call.

        Will return all entities if no entities specified in call.
        Will return an empty list if entities specified but unknown.
        """
        return run_callback_threadsafe(
            self.hass.loop, self.async_extract_from_service, service
        ).result()
Пример #24
0
    def test_create_clientsession_without_ssl_and_cookies(self):
        """Test create clientsession without ssl."""

        def _async_helper():
            return client.async_create_clientsession(self.hass, False, cookies={"bla": True})

        session = run_callback_threadsafe(self.hass.loop, _async_helper).result()

        assert isinstance(session, aiohttp.ClientSession)
        assert isinstance(self.hass.data[client.DATA_CONNECTOR_NOTVERIFY], aiohttp.TCPConnector)
Пример #25
0
def dispatcher_connect(hass, signal, target):
    """Connect a callable function to a signal."""
    async_unsub = run_callback_threadsafe(
        hass.loop, async_dispatcher_connect, hass, signal, target).result()

    def remove_dispatcher():
        """Remove signal listener."""
        run_callback_threadsafe(hass.loop, async_unsub).result()

    return remove_dispatcher
Пример #26
0
    def test_attributes(self):
        """"Test the attributes."""
        vs = run_callback_threadsafe(
            self.hass.loop, template.BinarySensorTemplate,
            self.hass, 'parent', 'Parent', 'motion',
            template_hlpr.Template('{{ 1 > 1 }}', self.hass), MATCH_ALL,
            None, None
        ).result()
        self.assertFalse(vs.should_poll)
        self.assertEqual('motion', vs.device_class)
        self.assertEqual('Parent', vs.name)

        run_callback_threadsafe(self.hass.loop, vs.async_check_state).result()
        self.assertFalse(vs.is_on)

        # pylint: disable=protected-access
        vs._template = template_hlpr.Template("{{ 2 > 1 }}", self.hass)

        run_callback_threadsafe(self.hass.loop, vs.async_check_state).result()
        self.assertTrue(vs.is_on)
Пример #27
0
    def test_event(self):
        """"Test the event."""
        vs = run_callback_threadsafe(
            self.hass.loop, template.BinarySensorTemplate,
            self.hass, 'parent', 'Parent', 'motion',
            template_hlpr.Template('{{ 1 > 1 }}', self.hass), MATCH_ALL
        ).result()
        vs.update_ha_state()
        self.hass.block_till_done()

        with mock.patch.object(vs, 'async_update') as mock_update:
            self.hass.bus.fire(EVENT_STATE_CHANGED)
            self.hass.block_till_done()
            assert mock_update.call_count == 1
Пример #28
0
    def listen(self, event_type, listener):
        """Listen for all events or events of a specific type.

        To listen to all events specify the constant ``MATCH_ALL``
        as event_type.
        """
        async_remove_listener = run_callback_threadsafe(
            self._hass.loop, self.async_listen, event_type, listener).result()

        def remove_listener():
            """Remove the listener."""
            run_callback_threadsafe(self._hass.loop,
                                    async_remove_listener).result()

        return remove_listener
Пример #29
0
    def test_create_clientsession_without_ssl_and_cookies(self):
        """Test create clientsession without ssl."""
        def _async_helper():
            return client.async_create_clientsession(self.hass,
                                                     False,
                                                     cookies={'bla': True})

        session = run_callback_threadsafe(
            self.hass.loop,
            _async_helper,
        ).result()

        assert isinstance(session, aiohttp.ClientSession)
        assert isinstance(self.hass.data[client.DATA_CONNECTOR_NOTVERIFY],
                          aiohttp.TCPConnector)
Пример #30
0
    def listen(self, event_type, listener):
        """Listen for all events or events of a specific type.

        To listen to all events specify the constant ``MATCH_ALL``
        as event_type.
        """
        async_remove_listener = run_callback_threadsafe(
            self._hass.loop, self.async_listen, event_type, listener).result()

        def remove_listener():
            """Remove the listener."""
            run_callback_threadsafe(
                self._hass.loop, async_remove_listener).result()

        return remove_listener
Пример #31
0
    def test_pending_sheduler(self):
        """Add a coro to pending tasks."""
        call_count = []

        @asyncio.coroutine
        def test_coro():
            """Test Coro."""
            call_count.append('call')

        for i in range(50):
            self.hass.add_job(test_coro())

        run_coroutine_threadsafe(
            asyncio.wait(self.hass._pending_tasks, loop=self.hass.loop),
            loop=self.hass.loop
        ).result()

        with patch.object(self.hass.loop, 'call_later') as mock_later:
            run_callback_threadsafe(
                self.hass.loop, self.hass._async_tasks_cleanup).result()
            assert mock_later.called

        assert len(self.hass._pending_tasks) == 0
        assert len(call_count) == 50
Пример #32
0
def generate_entity_id(entity_id_format: str,
                       name: Optional[str],
                       current_ids: Optional[List[str]] = None,
                       hass: Optional[HomeAssistant] = None) -> str:
    """Generate a unique entity ID based on given entity IDs or used IDs."""
    if current_ids is None:
        if hass is None:
            raise ValueError("Missing required parameter currentids or hass")
        else:
            return run_callback_threadsafe(hass.loop, async_generate_entity_id,
                                           entity_id_format, name, current_ids,
                                           hass).result()

    name = (slugify(name) or slugify(DEVICE_DEFAULT_NAME)).lower()

    return ensure_unique_string(entity_id_format.format(name), current_ids)
Пример #33
0
def generate_entity_id(entity_id_format: str, name: Optional[str],
                       current_ids: Optional[List[str]]=None,
                       hass: Optional[HomeAssistant]=None) -> str:
    """Generate a unique entity ID based on given entity IDs or used IDs."""
    if current_ids is None:
        if hass is None:
            raise ValueError("Missing required parameter currentids or hass")
        else:
            return run_callback_threadsafe(
                hass.loop, async_generate_entity_id, entity_id_format, name,
                current_ids, hass
            ).result()

    name = (name or DEVICE_DEFAULT_NAME).lower()

    return ensure_unique_string(
        entity_id_format.format(slugify(name)), current_ids)
Пример #34
0
def numeric_state(hass: HomeAssistant,
                  entity,
                  below=None,
                  above=None,
                  value_template=None,
                  variables=None):
    """Test a numeric state condition."""
    return run_callback_threadsafe(
        hass.loop,
        async_numeric_state,
        hass,
        entity,
        below,
        above,
        value_template,
        variables,
    ).result()
Пример #35
0
    def listen_once(self, event_type, listener):
        """Listen once for event of a specific type.

        To listen to all events specify the constant ``MATCH_ALL``
        as event_type.

        Returns function to unsubscribe the listener.
        """
        async_remove_listener = run_callback_threadsafe(
            self._hass.loop, self.async_listen_once, event_type, listener,
        ).result()

        def remove_listener():
            """Remove the listener."""
            run_callback_threadsafe(
                self._hass.loop, async_remove_listener).result()

        return remove_listener
Пример #36
0
    def test_attributes(self):
        """"Test the attributes."""
        vs = run_callback_threadsafe(
            self.hass.loop, template.BinarySensorTemplate, self.hass,
            'parent', 'Parent', 'motion',
            template_hlpr.Template('{{ 1 > 1 }}',
                                   self.hass), MATCH_ALL).result()
        self.assertFalse(vs.should_poll)
        self.assertEqual('motion', vs.sensor_class)
        self.assertEqual('Parent', vs.name)

        vs.update()
        self.assertFalse(vs.is_on)

        # pylint: disable=protected-access
        vs._template = template_hlpr.Template("{{ 2 > 1 }}", self.hass)

        vs.update()
        self.assertTrue(vs.is_on)
Пример #37
0
 def services(self):
     """Return dictionary with per domain a list of available services."""
     return run_callback_threadsafe(
         self._hass.loop, self.async_services,
     ).result()
Пример #38
0
 def all(self):
     """Create a list of all states."""
     return run_callback_threadsafe(self._loop, self.async_all).result()
Пример #39
0
 def entity_ids(self, domain_filter=None):
     """List of entity ids that are being tracked."""
     future = run_callback_threadsafe(
         self._loop, self.async_entity_ids, domain_filter
     )
     return future.result()
Пример #40
0
 def remove_listener():
     """Remove the listener."""
     run_callback_threadsafe(
         self._hass.loop, async_remove_listener).result()
Пример #41
0
def log_entry(hass, name, message, domain=None, entity_id=None):
    """Add an entry to the logbook."""
    run_callback_threadsafe(hass.loop, async_log_entry, hass, name, message,
                            domain, entity_id).result()
Пример #42
0
def fire_mqtt_message(hass, topic, payload, qos=0):
    """Fire the MQTT message."""
    run_callback_threadsafe(
        hass.loop, async_fire_mqtt_message, hass, topic, payload, qos).result()
Пример #43
0
def turn_off(hass, entity_id=None, transition=None):
    """Turn all or specified light off."""
    run_callback_threadsafe(hass.loop, async_turn_off, hass, entity_id,
                            transition).result()
 def process_faces(self, faces, total):
     """Send event with detected faces and store data."""
     run_callback_threadsafe(self.hass.loop, self.async_process_faces,
                             faces, total).result()
Пример #45
0
 def start(self):
     """Start tracking members."""
     run_callback_threadsafe(self.hass.loop, self.async_start).result()
Пример #46
0
def create(hass, message, title=None, notification_id=None):
    """Generate a notification."""
    run_callback_threadsafe(hass.loop, async_create, hass, message, title,
                            notification_id).result()
Пример #47
0
def log_exception(ex, domain, config, hass):
    """Generate log exception for config validation."""
    run_callback_threadsafe(hass.loop, async_log_exception, ex, domain, config,
                            hass).result()
Пример #48
0
 def services(self):
     """Dict with per domain a list of available services."""
     return run_callback_threadsafe(
         self._loop,
         self.async_services,
     ).result()
Пример #49
0
 def threadsafe(*args, **kwargs):
     """Call func threadsafe."""
     hass = args[0]
     return run_callback_threadsafe(hass.loop,
                                    ft.partial(func, *args,
                                               **kwargs)).result()
Пример #50
0
 def remove(self, domain, service):
     """Remove a registered service from service handler."""
     run_callback_threadsafe(
         self._hass.loop, self.async_remove, domain, service).result()
Пример #51
0
 def update_group(self):
     """Set up and/or update component group."""
     run_callback_threadsafe(self.hass.loop,
                             self.async_update_group).result()
Пример #52
0
 def stop(self) -> None:
     """Stop running script."""
     run_callback_threadsafe(self.hass.loop, self.async_stop).result()
Пример #53
0
 def listeners(self):
     """Return dictionary with events and the number of listeners."""
     return run_callback_threadsafe(
         self._hass.loop, self.async_listeners
     ).result()
Пример #54
0
def request_done(hass, request_id):
    """Mark a configuration request as done."""
    return run_callback_threadsafe(hass.loop, async_request_done, hass,
                                   request_id).result()
Пример #55
0
 def get_info_callback(items):
     """Set the addressed of connected buttons as result of the future."""
     addresses = items["bd_addr_of_verified_buttons"]
     run_callback_threadsafe(loop, future.set_result, addresses)
Пример #56
0
 def remove():
     """Remove listener convert."""
     run_callback_threadsafe(hass.loop, async_remove).result()
Пример #57
0
def active_zone(hass, latitude, longitude, radius=0):
    """Find the active zone for given latitude, longitude."""
    return run_callback_threadsafe(
        hass.loop, async_active_zone, hass, latitude, longitude, radius
    ).result()
Пример #58
0
def notify_errors(hass, request_id, error):
    """Add errors to a config request."""
    return run_callback_threadsafe(hass.loop, async_notify_errors, hass,
                                   request_id, error).result()
Пример #59
0
def listen_platform(hass, component, callback):
    """Register a platform loader listener."""
    run_callback_threadsafe(hass.loop, async_listen_platform, hass, component,
                            callback).result()