Example #1
0
    def test_get_image_without_exists_camera(self):
        """Try to get image without exists camera."""
        self.hass.states.remove('camera.demo_camera')

        with pytest.raises(HomeAssistantError):
            run_coroutine_threadsafe(camera.async_get_image(
                self.hass, 'camera.demo_camera'), self.hass.loop).result()
Example #2
0
    def test_async_add_job_pending_tasks_callback(self):
        """Run a callback in pending tasks."""
        call_count = []

        @ha.callback
        def test_callback():
            """Test callback."""
            call_count.append('call')

        @asyncio.coroutine
        def wait_finish_callback():
            """Wait until all stuff is scheduled."""
            yield from asyncio.sleep(0, loop=self.hass.loop)
            yield from asyncio.sleep(0, loop=self.hass.loop)

        for i in range(2):
            self.hass.add_job(test_callback)

        run_coroutine_threadsafe(
            wait_finish_callback(), self.hass.loop).result()

        self.hass.block_till_done()

        assert len(self.hass._pending_tasks) == 0
        assert len(call_count) == 2
    def test_scan_devices_parse_error(self, aioclient_mock):
        """Setup a upc platform and scan device with parse error."""
        aioclient_mock.get(
            "http://{}/common_page/login.html".format(self.host),
            cookies={'sessionToken': '654321'}
        )
        aioclient_mock.post(
            "http://{}/xml/getter.xml".format(self.host),
            content=b'successful',
            cookies={'sessionToken': '654321'}
        )

        scanner = run_coroutine_threadsafe(platform.async_get_scanner(
            self.hass, {DOMAIN: {
                    CONF_PLATFORM: 'upc_connect',
                    CONF_HOST: self.host
                }}
            ), self.hass.loop).result()

        assert len(aioclient_mock.mock_calls) == 1

        aioclient_mock.clear_requests()
        aioclient_mock.post(
            "http://{}/xml/getter.xml".format(self.host),
            text="Blablebla blabalble",
            cookies={'sessionToken': '1235678'}
        )

        mac_list = run_coroutine_threadsafe(
            scanner.async_scan_devices(), self.hass.loop).result()

        assert len(aioclient_mock.mock_calls) == 1
        assert aioclient_mock.mock_calls[0][2] == 'token=654321&fun=123'
        assert scanner.token is None
        assert mac_list == []
    def test_scan_devices(self, aioclient_mock):
        """Setup a upc platform and scan device."""
        aioclient_mock.get(
            "http://{}/common_page/login.html".format(self.host),
            cookies={'sessionToken': '654321'}
        )
        aioclient_mock.post(
            "http://{}/xml/getter.xml".format(self.host),
            content=b'successful',
            cookies={'sessionToken': '654321'}
        )

        scanner = run_coroutine_threadsafe(platform.async_get_scanner(
            self.hass, {DOMAIN: {
                    CONF_PLATFORM: 'upc_connect',
                    CONF_HOST: self.host
                }}
            ), self.hass.loop).result()

        assert len(aioclient_mock.mock_calls) == 1

        aioclient_mock.clear_requests()
        aioclient_mock.post(
            "http://{}/xml/getter.xml".format(self.host),
            text=load_fixture('upc_connect.xml'),
            cookies={'sessionToken': '1235678'}
        )

        mac_list = run_coroutine_threadsafe(
            scanner.async_scan_devices(), self.hass.loop).result()

        assert len(aioclient_mock.mock_calls) == 1
        assert aioclient_mock.mock_calls[0][2] == 'token=654321&fun=123'
        assert mac_list == ['30:D3:2D:0:69:21', '5C:AA:FD:25:32:02',
                            '70:EE:50:27:A1:38']
Example #5
0
    def test_update_when_off(self, aioclient_mock):
        """Test update when switch is off."""
        aioclient_mock.get(self.resource, text=self.body_off.template)
        run_coroutine_threadsafe(
            self.switch.async_update(), self.hass.loop).result()

        assert not self.switch.is_on
Example #6
0
def start(hass, server_config):
    """Initialize MQTT Server."""
    from hbmqtt.broker import Broker, BrokerException

    try:
        passwd = tempfile.NamedTemporaryFile()

        if server_config is None:
            server_config, client_config = generate_config(hass, passwd)
        else:
            client_config = None

        broker = Broker(server_config, hass.loop)
        run_coroutine_threadsafe(broker.start(), hass.loop).result()
    except BrokerException:
        logging.getLogger(__name__).exception('Error initializing MQTT server')
        return False, None
    finally:
        passwd.close()

    @callback
    def shutdown_mqtt_server(event):
        """Shut down the MQTT server."""
        hass.async_add_job(broker.shutdown())

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, shutdown_mqtt_server)

    return True, client_config
Example #7
0
    def test_supported_features_children_and_cmds(self):
        """Test supported media commands with children and attrs."""
        config = self.config_children_and_attr
        universal.validate_config(config)
        config['commands']['turn_on'] = 'test'
        config['commands']['turn_off'] = 'test'
        config['commands']['volume_up'] = 'test'
        config['commands']['volume_down'] = 'test'
        config['commands']['volume_mute'] = 'test'
        config['commands']['volume_set'] = 'test'
        config['commands']['select_source'] = 'test'
        config['commands']['shuffle_set'] = 'test'

        ump = universal.UniversalMediaPlayer(self.hass, **config)
        ump.entity_id = media_player.ENTITY_ID_FORMAT.format(config['name'])
        run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result()

        self.mock_mp_1._state = STATE_PLAYING
        self.mock_mp_1.schedule_update_ha_state()
        self.hass.block_till_done()
        run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result()

        check_flags = universal.SUPPORT_TURN_ON | universal.SUPPORT_TURN_OFF \
            | universal.SUPPORT_VOLUME_STEP | universal.SUPPORT_VOLUME_MUTE \
            | universal.SUPPORT_SELECT_SOURCE | universal.SUPPORT_SHUFFLE_SET

        self.assertEqual(check_flags, ump.supported_features)
Example #8
0
    def test_turn_on_timeout(self, aioclient_mock):
        """Test turn_on when timeout occurs."""
        aioclient_mock.post(self.resource, status=500)
        run_coroutine_threadsafe(
            self.switch.async_turn_on(), self.hass.loop).result()

        assert self.switch.is_on is None
    def test_platform_setup(self):
        """Test platform setup."""
        config = {'name': 'test', 'platform': 'universal'}
        bad_config = {'platform': 'universal'}
        entities = []

        def add_devices(new_entities):
            """Add devices to list."""
            for dev in new_entities:
                entities.append(dev)

        setup_ok = True
        try:
            run_coroutine_threadsafe(
                universal.async_setup_platform(
                    self.hass, validate_config(bad_config), add_devices),
                self.hass.loop).result()
        except MultipleInvalid:
            setup_ok = False
        self.assertFalse(setup_ok)
        self.assertEqual(0, len(entities))

        run_coroutine_threadsafe(
            universal.async_setup_platform(
                self.hass, validate_config(config), add_devices),
            self.hass.loop).result()
        self.assertEqual(1, len(entities))
        self.assertEqual('test', entities[0].name)
Example #10
0
    def test_loading_configuration_from_packages(self):
        """Test loading packages config onto hass object config."""
        self.hass.config = mock.Mock()

        run_coroutine_threadsafe(
            config_util.async_process_ha_core_config(self.hass, {
                'latitude': 39,
                'longitude': -1,
                'elevation': 500,
                'name': 'Huis',
                CONF_TEMPERATURE_UNIT: 'C',
                'time_zone': 'Europe/Madrid',
                'packages': {
                    'package_1': {'wake_on_lan': None},
                    'package_2': {'light': {'platform': 'hue'},
                                  'media_extractor': None,
                                  'sun': None}},
            }), self.hass.loop).result()

        # Empty packages not allowed
        with pytest.raises(MultipleInvalid):
            run_coroutine_threadsafe(
                config_util.async_process_ha_core_config(self.hass, {
                    'latitude': 39,
                    'longitude': -1,
                    'elevation': 500,
                    'name': 'Huis',
                    CONF_TEMPERATURE_UNIT: 'C',
                    'time_zone': 'Europe/Madrid',
                    'packages': {'empty_package': None},
                }), self.hass.loop).result()
Example #11
0
    def test_update_when_unknown(self, aioclient_mock):
        """Test update when unknown status returned."""
        aioclient_mock.get(self.resource, text='unknown status')
        run_coroutine_threadsafe(
            self.switch.async_update(), self.hass.loop).result()

        assert self.switch.is_on is None
Example #12
0
    def test_update_timeout(self, aioclient_mock):
        """Test update when timeout occurs."""
        aioclient_mock.get(self.resource, exc=asyncio.TimeoutError())
        run_coroutine_threadsafe(
            self.switch.async_update(), self.hass.loop).result()

        assert self.switch.is_on is None
 def test_volume_down(self):
     """Test the volume_down helper function."""
     self.assertEqual(self.player.volume_level, 0)
     self.player.set_volume_level(0.5)
     self.assertEqual(self.player.volume_level, 0.5)
     run_coroutine_threadsafe(
         self.player.async_volume_down(), self.hass.loop).result()
     self.assertEqual(self.player.volume_level, 0.3)
Example #14
0
    def test_get_image_with_timeout(self, aioclient_mock):
        """Try to get image with timeout."""
        aioclient_mock.get(self.url, exc=asyncio.TimeoutError())

        with pytest.raises(HomeAssistantError):
            run_coroutine_threadsafe(camera.async_get_image(
                self.hass, 'camera.demo_camera'), self.hass.loop).result()

        assert len(aioclient_mock.mock_calls) == 1
Example #15
0
    def add_entities(self, new_entities, update_before_add=False):
        """Add entities for a single platform."""
        if update_before_add:
            for entity in new_entities:
                entity.update()

        run_coroutine_threadsafe(
            self.async_add_entities(list(new_entities), False),
            self.component.hass.loop).result()
Example #16
0
    def test_get_image_with_bad_http_state(self, aioclient_mock):
        """Try to get image with bad http status."""
        aioclient_mock.get(self.url, status=400)

        with pytest.raises(HomeAssistantError):
            run_coroutine_threadsafe(camera.async_get_image(
                self.hass, 'camera.demo_camera'), self.hass.loop).result()

        assert len(aioclient_mock.mock_calls) == 1
    def setup(self, config):
        """Set up a full entity component.

        Loads the platforms from the config and will listen for supported
        discovered platforms.
        """
        run_coroutine_threadsafe(
            self.async_setup(config), self.hass.loop
        ).result()
Example #18
0
    def test_turn_off_success(self, aioclient_mock):
        """Test turn_off."""
        aioclient_mock.post(self.resource, status=200)
        run_coroutine_threadsafe(
            self.switch.async_turn_off(), self.hass.loop).result()

        assert self.body_off.template == \
            aioclient_mock.mock_calls[-1][2].decode()
        assert not self.switch.is_on
Example #19
0
    def test_turn_off_status_not_ok(self, aioclient_mock):
        """Test turn_off when error status returned."""
        aioclient_mock.post(self.resource, status=500)
        run_coroutine_threadsafe(
            self.switch.async_turn_off(), self.hass.loop).result()

        assert self.body_off.template == \
            aioclient_mock.mock_calls[-1][2].decode()
        assert self.switch.is_on is None
Example #20
0
    def test_circular_import(self):
        """Test we don't break doing circular import.

        This test will have test_component discover the switch.test_circular
        component while setting up.

        The supplied config will load test_component and will load
        switch.test_circular.

        That means that after startup, we will have test_component and switch
        setup. The test_circular platform has been loaded twice.
        """
        component_calls = []
        platform_calls = []

        def component_setup(hass, config):
            """Setup mock component."""
            discovery.load_platform(hass, 'switch', 'test_circular', 'disc',
                                    config)
            component_calls.append(1)
            return True

        def setup_platform(hass, config, add_devices_callback,
                           discovery_info=None):
            """Setup mock platform."""
            platform_calls.append('disc' if discovery_info else 'component')

        loader.set_component(
            'test_component',
            MockModule('test_component', setup=component_setup))

        loader.set_component(
            'switch.test_circular',
            MockPlatform(setup_platform,
                         dependencies=['test_component']))

        bootstrap.setup_component(self.hass, 'test_component', {
            'test_component': None,
            'switch': [{
                'platform': 'test_circular',
            }],
        })

        # We wait for the setup_lock to finish
        run_coroutine_threadsafe(
            self.hass.data['setup_lock'].acquire(), self.hass.loop).result()

        self.hass.block_till_done()

        # test_component will only be setup once
        assert len(component_calls) == 1
        # The platform will be setup once via the config in `setup_component`
        # and once via the discovery inside test_component.
        assert len(platform_calls) == 2
        assert 'test_component' in self.hass.config.components
        assert 'switch' in self.hass.config.components
    def add_entities(self, new_entities, update_before_add=False):
        """Add entities for a single platform."""
        # That avoid deadlocks
        if update_before_add:
            self.component.logger.warning(
                "Call 'add_entities' with update_before_add=True "
                "only inside tests or you can run into a deadlock!")

        run_coroutine_threadsafe(
            self.async_add_entities(list(new_entities), update_before_add),
            self.component.hass.loop).result()
Example #22
0
    def update_ha_state(self, force_refresh=False):
        """Update Home Assistant with current state of entity.

        If force_refresh == True will update entity before setting state.
        """
        # We're already in a thread, do the force refresh here.
        if force_refresh and not hasattr(self, "async_update"):
            self.update()
            force_refresh = False

        run_coroutine_threadsafe(self.async_update_ha_state(force_refresh), self.hass.loop).result()
Example #23
0
    def update(self):
        """Retrieve latest state.

        When not implemented, will forward call to async version if available.
        """
        async_update = getattr(self, 'async_update', None)

        if async_update is None:
            return

        run_coroutine_threadsafe(async_update(), self.hass.loop).result()
Example #24
0
    def _compute_state(self, config):
        run_coroutine_threadsafe(
            config_util.async_process_ha_core_config(self.hass, config),
            self.hass.loop).result()

        entity = Entity()
        entity.entity_id = 'test.test'
        entity.hass = self.hass
        entity.schedule_update_ha_state()

        self.hass.block_till_done()

        return self.hass.states.get('test.test')
Example #25
0
    def test_active_child_state(self):
        """Test active child state property."""
        config = self.config_children_only
        universal.validate_config(config)

        ump = universal.UniversalMediaPlayer(self.hass, **config)
        ump.entity_id = media_player.ENTITY_ID_FORMAT.format(config['name'])
        run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result()

        self.assertEqual(None, ump._child_state)

        self.mock_mp_1._state = STATE_PLAYING
        self.mock_mp_1.schedule_update_ha_state()
        self.hass.block_till_done()
        run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result()
        self.assertEqual(self.mock_mp_1.entity_id,
                         ump._child_state.entity_id)

        self.mock_mp_2._state = STATE_PLAYING
        self.mock_mp_2.schedule_update_ha_state()
        self.hass.block_till_done()
        run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result()
        self.assertEqual(self.mock_mp_1.entity_id,
                         ump._child_state.entity_id)

        self.mock_mp_1._state = STATE_OFF
        self.mock_mp_1.schedule_update_ha_state()
        self.hass.block_till_done()
        run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result()
        self.assertEqual(self.mock_mp_2.entity_id,
                         ump._child_state.entity_id)
    def test_check_ha_config_file_wrong(self, mock_create):
        """Check that restart with a bad config doesn't propagate to stop."""
        process_mock = mock.MagicMock()
        attrs = {
            'communicate.return_value':
                mock_generator((r'\033[hellom'.encode('utf-8'), 'error')),
            'wait.return_value': mock_generator(1)}
        process_mock.configure_mock(**attrs)
        mock_create.return_value = mock_generator(process_mock)

        with self.assertRaises(HomeAssistantError):
            run_coroutine_threadsafe(
                config_util.async_check_ha_config_file(self.hass),
                self.hass.loop
            ).result()
Example #27
0
    def test_mac_vendor_lookup_unknown(self):
        """Prevent another mac vendor lookup if was not found first time."""
        mac = 'B8:27:EB:00:00:00'

        device = device_tracker.Device(
            self.hass, timedelta(seconds=180), True, 'test', mac, 'Test name')

        with mock_aiohttp_client() as aioclient_mock:
            aioclient_mock.get('http://api.macvendors.com/b8:27:eb',
                               status=404)

            run_coroutine_threadsafe(device.set_vendor_for_mac(),
                                     self.hass.loop).result()

            self.assertEqual(device.vendor, 'unknown')
    def test_state_children_only(self):
        """Test media player state with only children."""
        config = validate_config(self.config_children_only)

        ump = universal.UniversalMediaPlayer(self.hass, **config)
        ump.entity_id = media_player.ENTITY_ID_FORMAT.format(config['name'])
        run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result()

        self.assertTrue(ump.state, STATE_OFF)

        self.mock_mp_1._state = STATE_PLAYING
        self.mock_mp_1.schedule_update_ha_state()
        self.hass.block_till_done()
        run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result()
        self.assertEqual(STATE_PLAYING, ump.state)
Example #29
0
    def test_mac_vendor_lookup_exception(self):
        """Prevent another lookup if exception during API call."""
        mac = 'B8:27:EB:00:00:00'

        device = device_tracker.Device(
            self.hass, timedelta(seconds=180), True, 'test', mac, 'Test name')

        with mock_aiohttp_client() as aioclient_mock:
            aioclient_mock.get('http://api.macvendors.com/b8:27:eb',
                               exc=asyncio.TimeoutError())

            run_coroutine_threadsafe(device.set_vendor_for_mac(),
                                     self.hass.loop).result()

            self.assertEqual(device.vendor, 'unknown')
Example #30
0
 def create_group(hass, name, entity_ids=None, user_defined=True,
                  icon=None, view=False, control=None, object_id=None):
     """Initialize a group."""
     return run_coroutine_threadsafe(
         Group.async_create_group(hass, name, entity_ids, user_defined,
                                  icon, view, control, object_id),
         hass.loop).result()
Example #31
0
 def run(self, variables=None):
     """Run script."""
     run_coroutine_threadsafe(self.async_run(variables),
                              self.hass.loop).result()
Example #32
0
 def turn_off(self, **kwargs) -> None:
     """Turn the entity off."""
     run_coroutine_threadsafe(self.async_turn_off(**kwargs),
                              self.hass.loop).result()
    def setUpClass(cls):
        """Setup the class."""
        cls.hass = hass = get_test_home_assistant()

        # We need to do this to get access to homeassistant/turn_(on,off)
        run_coroutine_threadsafe(
            core_components.async_setup(hass, {core.DOMAIN: {}}),
            hass.loop).result()

        bootstrap.setup_component(
            hass, http.DOMAIN,
            {http.DOMAIN: {
                http.CONF_SERVER_PORT: HTTP_SERVER_PORT
            }})

        with patch('homeassistant.components'
                   '.emulated_hue.UPNPResponderThread'):
            bootstrap.setup_component(
                hass, emulated_hue.DOMAIN, {
                    emulated_hue.DOMAIN: {
                        emulated_hue.CONF_LISTEN_PORT: BRIDGE_SERVER_PORT,
                        emulated_hue.CONF_EXPOSE_BY_DEFAULT: True
                    }
                })

        bootstrap.setup_component(cls.hass, light.DOMAIN,
                                  {'light': [{
                                      'platform': 'demo',
                                  }]})

        bootstrap.setup_component(
            cls.hass, script.DOMAIN, {
                'script': {
                    'set_kitchen_light': {
                        'sequence': [{
                            'service_template':
                            "light.turn_{{ requested_state }}",
                            'data_template': {
                                'entity_id': 'light.kitchen_lights',
                                'brightness': "{{ requested_level }}"
                            }
                        }]
                    }
                }
            })

        bootstrap.setup_component(cls.hass, media_player.DOMAIN,
                                  {'media_player': [{
                                      'platform': 'demo',
                                  }]})

        cls.hass.start()

        # Kitchen light is explicitly excluded from being exposed
        kitchen_light_entity = cls.hass.states.get('light.kitchen_lights')
        attrs = dict(kitchen_light_entity.attributes)
        attrs[emulated_hue.ATTR_EMULATED_HUE] = False
        cls.hass.states.set(kitchen_light_entity.entity_id,
                            kitchen_light_entity.state,
                            attributes=attrs)

        # Expose the script
        script_entity = cls.hass.states.get('script.set_kitchen_light')
        attrs = dict(script_entity.attributes)
        attrs[emulated_hue.ATTR_EMULATED_HUE] = True
        cls.hass.states.set(script_entity.entity_id,
                            script_entity.state,
                            attributes=attrs)
Example #34
0
    def test_service_call_to_child(self):
        """Test service calls that should be routed to a child."""
        config = validate_config(self.config_children_only)

        ump = universal.UniversalMediaPlayer(self.hass, **config)
        ump.entity_id = media_player.ENTITY_ID_FORMAT.format(config['name'])
        run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result()

        self.mock_mp_2._state = STATE_PLAYING
        self.mock_mp_2.schedule_update_ha_state()
        self.hass.block_till_done()
        run_coroutine_threadsafe(ump.async_update(), self.hass.loop).result()

        run_coroutine_threadsafe(ump.async_turn_off(), self.hass.loop).result()
        self.assertEqual(1, len(self.mock_mp_2.service_calls['turn_off']))

        run_coroutine_threadsafe(ump.async_turn_on(), self.hass.loop).result()
        self.assertEqual(1, len(self.mock_mp_2.service_calls['turn_on']))

        run_coroutine_threadsafe(ump.async_mute_volume(True),
                                 self.hass.loop).result()
        self.assertEqual(1, len(self.mock_mp_2.service_calls['mute_volume']))

        run_coroutine_threadsafe(ump.async_set_volume_level(0.5),
                                 self.hass.loop).result()
        self.assertEqual(1,
                         len(self.mock_mp_2.service_calls['set_volume_level']))

        run_coroutine_threadsafe(ump.async_media_play(),
                                 self.hass.loop).result()
        self.assertEqual(1, len(self.mock_mp_2.service_calls['media_play']))

        run_coroutine_threadsafe(ump.async_media_pause(),
                                 self.hass.loop).result()
        self.assertEqual(1, len(self.mock_mp_2.service_calls['media_pause']))

        run_coroutine_threadsafe(ump.async_media_previous_track(),
                                 self.hass.loop).result()
        self.assertEqual(
            1, len(self.mock_mp_2.service_calls['media_previous_track']))

        run_coroutine_threadsafe(ump.async_media_next_track(),
                                 self.hass.loop).result()
        self.assertEqual(1,
                         len(self.mock_mp_2.service_calls['media_next_track']))

        run_coroutine_threadsafe(ump.async_media_seek(100),
                                 self.hass.loop).result()
        self.assertEqual(1, len(self.mock_mp_2.service_calls['media_seek']))

        run_coroutine_threadsafe(ump.async_play_media('movie', 'batman'),
                                 self.hass.loop).result()
        self.assertEqual(1, len(self.mock_mp_2.service_calls['play_media']))

        run_coroutine_threadsafe(ump.async_volume_up(),
                                 self.hass.loop).result()
        self.assertEqual(1, len(self.mock_mp_2.service_calls['volume_up']))

        run_coroutine_threadsafe(ump.async_volume_down(),
                                 self.hass.loop).result()
        self.assertEqual(1, len(self.mock_mp_2.service_calls['volume_down']))

        run_coroutine_threadsafe(ump.async_media_play_pause(),
                                 self.hass.loop).result()
        self.assertEqual(1,
                         len(self.mock_mp_2.service_calls['media_play_pause']))

        run_coroutine_threadsafe(ump.async_select_source('dvd'),
                                 self.hass.loop).result()
        self.assertEqual(1, len(self.mock_mp_2.service_calls['select_source']))

        run_coroutine_threadsafe(ump.async_clear_playlist(),
                                 self.hass.loop).result()
        self.assertEqual(1,
                         len(self.mock_mp_2.service_calls['clear_playlist']))

        run_coroutine_threadsafe(ump.async_set_shuffle(True),
                                 self.hass.loop).result()
        self.assertEqual(1, len(self.mock_mp_2.service_calls['shuffle_set']))
 def add_entity(self, entity, platform=None, update_before_add=False):
     """Add entity to component."""
     return run_coroutine_threadsafe(
         self.async_add_entity(entity, platform, update_before_add),
         self.hass.loop
     ).result()
Example #36
0
 def stop(self) -> None:
     """Stop Home Assistant and shuts down all threads."""
     run_coroutine_threadsafe(self.async_stop(), self.loop)
Example #37
0
 def update_tracked_entity_ids(self, entity_ids):
     """Update the member entity IDs."""
     run_coroutine_threadsafe(
         self.async_update_tracked_entity_ids(entity_ids),
         self.hass.loop).result()
Example #38
0
 def stop(self):
     """Unregister the group from Home Assistant."""
     run_coroutine_threadsafe(self.async_stop(), self.hass.loop).result()
Example #39
0
 def camera_image(self):
     """Return bytes of camera image."""
     return run_coroutine_threadsafe(self.async_camera_image(),
                                     self.hass.loop).result()
Example #40
0
 def preload_media_image_url(self, url):
     """Preload and cache a media image for future use."""
     run_coroutine_threadsafe(_async_fetch_image(self.hass, url),
                              self.hass.loop).result()
Example #41
0
def load_config(path: str, hass: HomeAssistantType, consider_home: timedelta):
    """Load devices from YAML configuration file."""
    return run_coroutine_threadsafe(
        async_load_config(path, hass, consider_home), hass.loop).result()
Example #42
0
def call_from_config(hass, config, blocking=False, variables=None,
                     validate_config=True):
    """Call a service based on a config hash."""
    run_coroutine_threadsafe(
        async_call_from_config(hass, config, blocking, variables,
                               validate_config), hass.loop).result()
 def reset(self):
     """Remove entities and reset the entity component to initial values."""
     run_coroutine_threadsafe(self.async_reset(), self.hass.loop).result()
Example #44
0
 def test_setup_missing_config(self):
     """Test setup with configuration missing required entries."""
     assert not run_coroutine_threadsafe(
         rest.async_setup_platform(self.hass, {'platform': 'rest'}, None),
         self.hass.loop).result()
Example #45
0
 def threadsafe(*args, **kwargs):
     """Call func threadsafe."""
     hass = args[0]
     return run_coroutine_threadsafe(func(*args, **kwargs),
                                     hass.loop).result()
Example #46
0
 def start_hass(*mocks):
     """Helper to start hass."""
     run_coroutine_threadsafe(hass.async_start(), loop=hass.loop).result()
Example #47
0
def reproduce_state(hass, states, blocking=False):
    """Reproduce given state."""
    return run_coroutine_threadsafe(
        async_reproduce_state(hass, states, blocking), hass.loop).result()
Example #48
0
def setup_component(hass: core.HomeAssistant, domain: str,
                    config: Optional[Dict]=None) -> bool:
    """Set up a component and all its dependencies."""
    return run_coroutine_threadsafe(
        async_setup_component(hass, domain, config), loop=hass.loop).result()
Example #49
0
def prepare_setup_component(hass: core.HomeAssistant, config: dict,
                            domain: str):
    """Prepare setup of a component and return processed config."""
    return run_coroutine_threadsafe(
        async_prepare_setup_component(hass, config, domain), loop=hass.loop
    ).result()
Example #50
0
 def block_till_done(self) -> None:
     """Block till all pending work is done."""
     run_coroutine_threadsafe(self.async_block_till_done(),
                              loop=self.loop).result()
Example #51
0
def prepare_setup_platform(hass: core.HomeAssistant, config, domain: str,
                           platform_name: str) -> Optional[ModuleType]:
    """Load a platform and makes sure dependencies are setup."""
    return run_coroutine_threadsafe(async_prepare_setup_platform(
        hass, config, domain, platform_name),
                                    loop=hass.loop).result()
 def prepare_reload(self):
     """Prepare reloading this entity component."""
     return run_coroutine_threadsafe(
         self.async_prepare_reload(), loop=self.hass.loop).result()
Example #53
0
 def remove(self) -> None:
     """Remove entity from HASS."""
     run_coroutine_threadsafe(self.async_remove(), self.hass.loop).result()
Example #54
0
 def setUp(self):     # pylint: disable=invalid-name
     """Run when tests are started."""
     self.hass = get_test_home_assistant()
     run_coroutine_threadsafe(core_components.async_setup(
         self.hass, {}), self.hass.loop).result()