Ejemplo n.º 1
0
def setup(hass, config):
    """Track states and offer events for locks."""
    component = EntityComponent(
        _LOGGER, DOMAIN, hass, SCAN_INTERVAL, DISCOVERY_PLATFORMS,
        GROUP_NAME_ALL_LOCKS)
    component.setup(config)

    def handle_lock_service(service):
        """Handle calls to the lock services."""
        target_locks = component.extract_from_service(service)

        if ATTR_CODE not in service.data:
            code = None
        else:
            code = service.data[ATTR_CODE]

        for item in target_locks:
            if service.service == SERVICE_LOCK:
                item.lock(code=code)
            else:
                item.unlock(code=code)

            if item.should_poll:
                item.update_ha_state(True)

    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))
    hass.services.register(DOMAIN, SERVICE_UNLOCK, handle_lock_service,
                           descriptions.get(SERVICE_UNLOCK))
    hass.services.register(DOMAIN, SERVICE_LOCK, handle_lock_service,
                           descriptions.get(SERVICE_LOCK))

    return True
Ejemplo n.º 2
0
def setup(hass, config):
    """ Track states and offer events for sensors. """
    component = EntityComponent(logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL, DISCOVERY_PLATFORMS)

    component.setup(config)

    return True
Ejemplo n.º 3
0
def setup(hass, config):
    """Track states and offer events for covers."""
    component = EntityComponent(
        _LOGGER, DOMAIN, hass, SCAN_INTERVAL, GROUP_NAME_ALL_COVERS)
    component.setup(config)

    def handle_cover_service(service):
        """Handle calls to the cover services."""
        method = SERVICE_TO_METHOD.get(service.service)
        params = service.data.copy()
        params.pop(ATTR_ENTITY_ID, None)

        if method:
            for cover in component.extract_from_service(service):
                getattr(cover, method['method'])(**params)

                if cover.should_poll:
                    cover.update_ha_state(True)

    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))

    for service_name in SERVICE_TO_METHOD:
        schema = SERVICE_TO_METHOD[service_name].get(
            'schema', COVER_SERVICE_SCHEMA)
        hass.services.register(DOMAIN, service_name, handle_cover_service,
                               descriptions.get(service_name), schema=schema)
    return True
Ejemplo n.º 4
0
    def test_set_entity_namespace_via_config(self):
        """Test setting an entity namespace."""
        def platform_setup(hass, config, add_devices, discovery_info=None):
            """Test the platform setup."""
            add_devices([
                MockEntity(name='beer'),
                MockEntity(name=None),
            ])

        platform = MockPlatform(platform_setup)

        loader.set_component(self.hass, 'test_domain.platform', platform)

        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        component.setup({
            DOMAIN: {
                'platform': 'platform',
                'entity_namespace': 'yummy'
            }
        })

        self.hass.block_till_done()

        assert sorted(self.hass.states.entity_ids()) == \
            ['test_domain.yummy_beer', 'test_domain.yummy_unnamed_device']
Ejemplo n.º 5
0
def setup(hass, config):
    """Track states and offer events for switches."""
    component = EntityComponent(
        _LOGGER, DOMAIN, hass, SCAN_INTERVAL, GROUP_NAME_ALL_SWITCHES)
    component.setup(config)

    def handle_switch_service(service):
        """Handle calls to the switch services."""
        target_switches = component.extract_from_service(service)

        for switch in target_switches:
            if service.service == SERVICE_TURN_ON:
                switch.turn_on()
            elif service.service == SERVICE_TOGGLE:
                switch.toggle()
            else:
                switch.turn_off()

            if switch.should_poll:
                switch.update_ha_state(True)

    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))
    hass.services.register(DOMAIN, SERVICE_TURN_OFF, handle_switch_service,
                           descriptions.get(SERVICE_TURN_OFF),
                           schema=SWITCH_SERVICE_SCHEMA)
    hass.services.register(DOMAIN, SERVICE_TURN_ON, handle_switch_service,
                           descriptions.get(SERVICE_TURN_ON),
                           schema=SWITCH_SERVICE_SCHEMA)
    hass.services.register(DOMAIN, SERVICE_TOGGLE, handle_switch_service,
                           descriptions.get(SERVICE_TOGGLE),
                           schema=SWITCH_SERVICE_SCHEMA)

    return True
    def test_setup_recovers_when_setup_raises(self):
        """Test the setup if exceptions are happening."""
        platform1_setup = Mock(side_effect=Exception('Broken'))
        platform2_setup = Mock(return_value=None)

        loader.set_component('test_domain.mod1', MockPlatform(platform1_setup))
        loader.set_component('test_domain.mod2', MockPlatform(platform2_setup))

        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        assert not platform1_setup.called
        assert not platform2_setup.called

        component.setup(
            OrderedDict([
                (DOMAIN, {
                    'platform': 'mod1'
                }),
                ("{} 2".format(DOMAIN), {
                    'platform': 'non_exist'
                }),
                ("{} 3".format(DOMAIN), {
                    'platform': 'mod2'
                }),
            ]))

        self.hass.block_till_done()
        assert platform1_setup.called
        assert platform2_setup.called
Ejemplo n.º 7
0
def setup(hass, config):
    """Track states and offer events for covers."""
    component = EntityComponent(_LOGGER, DOMAIN, hass, SCAN_INTERVAL,
                                GROUP_NAME_ALL_COVERS)
    component.setup(config)

    def handle_cover_service(service):
        """Handle calls to the cover services."""
        method = SERVICE_TO_METHOD.get(service.service)
        params = service.data.copy()
        params.pop(ATTR_ENTITY_ID, None)

        if method:
            for cover in component.extract_from_service(service):
                getattr(cover, method['method'])(**params)

                if cover.should_poll:
                    cover.update_ha_state(True)

    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))

    for service_name in SERVICE_TO_METHOD:
        schema = SERVICE_TO_METHOD[service_name].get('schema',
                                                     COVER_SERVICE_SCHEMA)
        hass.services.register(DOMAIN,
                               service_name,
                               handle_cover_service,
                               descriptions.get(service_name),
                               schema=schema)
    return True
    def test_set_entity_namespace_via_config(self):
        """Test setting an entity namespace."""
        def platform_setup(hass, config, add_devices, discovery_info=None):
            """Test the platform setup."""
            add_devices([
                EntityTest(name='beer'),
                EntityTest(name=None),
            ])

        platform = MockPlatform(platform_setup)

        loader.set_component('test_domain.platform', platform)

        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        component.setup(
            {DOMAIN: {
                'platform': 'platform',
                'entity_namespace': 'yummy'
            }})

        self.hass.block_till_done()

        assert sorted(self.hass.states.entity_ids()) == \
            ['test_domain.yummy_beer', 'test_domain.yummy_unnamed_device']
Ejemplo n.º 9
0
def setup(hass, config):
    """Track states and offer events for locks."""
    component = EntityComponent(
        _LOGGER, DOMAIN, hass, SCAN_INTERVAL, DISCOVERY_PLATFORMS,
        GROUP_NAME_ALL_LOCKS)
    component.setup(config)

    def handle_lock_service(service):
        """Handle calls to the lock services."""
        target_locks = component.extract_from_service(service)

        if ATTR_CODE not in service.data:
            code = None
        else:
            code = service.data[ATTR_CODE]

        for item in target_locks:
            if service.service == SERVICE_LOCK:
                item.lock(code=code)
            else:
                item.unlock(code=code)

            if item.should_poll:
                item.update_ha_state(True)

    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))
    hass.services.register(DOMAIN, SERVICE_UNLOCK, handle_lock_service,
                           descriptions.get(SERVICE_UNLOCK))
    hass.services.register(DOMAIN, SERVICE_LOCK, handle_lock_service,
                           descriptions.get(SERVICE_LOCK))

    return True
Ejemplo n.º 10
0
def setup(hass, config):
    """ Track states and offer events for remote. """
    component = EntityComponent(
        logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL,
        DISCOVERY_PLATFORMS)

    component.setup(config)

    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))

    def remote_service_handler(service):
        """ Maps services to methods on RemoteDevice. """
        target_remotes = component.extract_from_service(service)

        method = SERVICE_TO_METHOD[service.service]

        for remote in target_remotes:
            getattr(remote, method)()

            if remote.should_poll:
                remote.update_ha_state(True)

    for service in SERVICE_TO_METHOD:
        hass.services.register(DOMAIN, service, remote_service_handler,
                               descriptions.get(service))

    return True
Ejemplo n.º 11
0
def setup(hass, config):
    """ Track states and offer events for sensors. """
    component = EntityComponent(logging.getLogger(__name__), DOMAIN, hass,
                                SCAN_INTERVAL, DISCOVERY_PLATFORMS)

    component.setup(config)

    def alarm_service_handler(service):
        """ Maps services to methods on Alarm. """
        target_alarms = component.extract_from_service(service)

        if ATTR_CODE not in service.data:
            return

        code = service.data[ATTR_CODE]

        method = SERVICE_TO_METHOD[service.service]

        for alarm in target_alarms:
            getattr(alarm, method)(code)

    for service in SERVICE_TO_METHOD:
        hass.services.register(DOMAIN, service, alarm_service_handler)

    return True
Ejemplo n.º 12
0
def setup(hass, config):
    """Track states and offer events for sensors."""
    component = EntityComponent(
        logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL,
        DISCOVERY_PLATFORMS)

    component.setup(config)

    def alarm_service_handler(service):
        """Map services to methods on Alarm."""
        target_alarms = component.extract_from_service(service)

        if ATTR_CODE not in service.data:
            code = None
        else:
            code = service.data[ATTR_CODE]

        method = SERVICE_TO_METHOD[service.service]

        for alarm in target_alarms:
            getattr(alarm, method)(code)
            if alarm.should_poll:
                alarm.update_ha_state(True)

    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))

    for service in SERVICE_TO_METHOD:
        hass.services.register(DOMAIN, service, alarm_service_handler,
                               descriptions.get(service))

    return True
Ejemplo n.º 13
0
def setup(hass, config):
    """ Track states and offer events for rollershutters. """
    component = EntityComponent(_LOGGER, DOMAIN, hass, SCAN_INTERVAL,
                                DISCOVERY_PLATFORMS,
                                GROUP_NAME_ALL_ROLLERSHUTTERS)
    component.setup(config)

    def handle_rollershutter_service(service):
        """ Handles calls to the rollershutter services. """
        target_rollershutters = component.extract_from_service(service)

        for rollershutter in target_rollershutters:
            if service.service == SERVICE_MOVE_UP:
                rollershutter.move_up()
            elif service.service == SERVICE_MOVE_DOWN:
                rollershutter.move_down()
            elif service.service == SERVICE_STOP:
                rollershutter.stop()

            if rollershutter.should_poll:
                rollershutter.update_ha_state(True)

    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))

    hass.services.register(DOMAIN, SERVICE_MOVE_UP,
                           handle_rollershutter_service,
                           descriptions.get(SERVICE_MOVE_UP))
    hass.services.register(DOMAIN, SERVICE_MOVE_DOWN,
                           handle_rollershutter_service,
                           descriptions.get(SERVICE_MOVE_DOWN))
    hass.services.register(DOMAIN, SERVICE_STOP, handle_rollershutter_service,
                           descriptions.get(SERVICE_STOP))

    return True
Ejemplo n.º 14
0
def setup(hass, config):
    """ Track states and offer events for switches. """
    component = EntityComponent(
        _LOGGER, DOMAIN, hass, SCAN_INTERVAL, DISCOVERY_PLATFORMS,
        GROUP_NAME_ALL_SWITCHES)
    component.setup(config)

    def handle_switch_service(service):
        """ Handles calls to the switch services. """
        target_switches = component.extract_from_service(service)

        for switch in target_switches:
            if service.service == SERVICE_TURN_ON:
                switch.turn_on()
            else:
                switch.turn_off()

            if switch.should_poll:
                switch.update_ha_state(True)

    hass.services.register(DOMAIN, SERVICE_TURN_OFF, handle_switch_service)

    hass.services.register(DOMAIN, SERVICE_TURN_ON, handle_switch_service)

    return True
Ejemplo n.º 15
0
def setup(hass, config):
    """Track states and offer events for switches."""
    component = EntityComponent(_LOGGER, DOMAIN, hass, SCAN_INTERVAL,
                                DISCOVERY_PLATFORMS, GROUP_NAME_ALL_SWITCHES)
    component.setup(config)

    def handle_switch_service(service):
        """Handle calls to the switch services."""
        target_switches = component.extract_from_service(service)

        for switch in target_switches:
            if service.service == SERVICE_TURN_ON:
                switch.turn_on()
            elif service.service == SERVICE_TOGGLE:
                switch.toggle()
            else:
                switch.turn_off()

            if switch.should_poll:
                switch.update_ha_state(True)

    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))
    hass.services.register(DOMAIN, SERVICE_TURN_OFF, handle_switch_service,
                           descriptions.get(SERVICE_TURN_OFF))
    hass.services.register(DOMAIN, SERVICE_TURN_ON, handle_switch_service,
                           descriptions.get(SERVICE_TURN_ON))
    hass.services.register(DOMAIN, SERVICE_TOGGLE, handle_switch_service,
                           descriptions.get(SERVICE_TOGGLE))

    return True
Ejemplo n.º 16
0
def setup(hass, config):
    """Setup scenes."""
    logger = logging.getLogger(__name__)

    # You are not allowed to mutate the original config so make a copy
    config = dict(config)

    for config_key in extract_domain_configs(config, DOMAIN):
        platform_config = config[config_key]
        if not isinstance(platform_config, list):
            platform_config = [platform_config]

        if not any(CONF_PLATFORM in entry for entry in platform_config):
            platform_config = [{'platform': 'homeassistant', 'states': entry}
                               for entry in platform_config]

        config[config_key] = platform_config

    component = EntityComponent(logger, DOMAIN, hass)

    component.setup(config)

    def handle_scene_service(service):
        """Handle calls to the switch services."""
        target_scenes = component.extract_from_service(service)

        for scene in target_scenes:
            scene.activate()

    hass.services.register(DOMAIN, SERVICE_TURN_ON, handle_scene_service,
                           schema=SCENE_SERVICE_SCHEMA)

    return True
Ejemplo n.º 17
0
    def test_setup_recovers_when_setup_raises(self):
        """Test the setup if exceptions are happening."""
        platform1_setup = Mock(side_effect=Exception("Broken"))
        platform2_setup = Mock(return_value=None)

        loader.set_component("test_domain.mod1", MockPlatform(platform1_setup))
        loader.set_component("test_domain.mod2", MockPlatform(platform2_setup))

        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        assert not platform1_setup.called
        assert not platform2_setup.called

        component.setup(
            OrderedDict(
                [
                    (DOMAIN, {"platform": "mod1"}),
                    ("{} 2".format(DOMAIN), {"platform": "non_exist"}),
                    ("{} 3".format(DOMAIN), {"platform": "mod2"}),
                ]
            )
        )

        assert platform1_setup.called
        assert platform2_setup.called
Ejemplo n.º 18
0
def setup(hass, config):
    """Setup scenes."""
    logger = logging.getLogger(__name__)

    # You are not allowed to mutate the original config so make a copy
    config = dict(config)

    for config_key in extract_domain_configs(config, DOMAIN):
        platform_config = config[config_key]
        if not isinstance(platform_config, list):
            platform_config = [platform_config]

        if not any(CONF_PLATFORM in entry for entry in platform_config):
            platform_config = [{'platform': 'homeassistant', 'states': entry}
                               for entry in platform_config]

        config[config_key] = platform_config

    component = EntityComponent(logger, DOMAIN, hass)

    component.setup(config)

    def handle_scene_service(service):
        """Handle calls to the switch services."""
        target_scenes = component.extract_from_service(service)

        for scene in target_scenes:
            scene.activate()

    hass.services.register(DOMAIN, SERVICE_TURN_ON, handle_scene_service)

    return True
Ejemplo n.º 19
0
def setup(hass, config):
    """ Track states and offer events for sensors. """
    component = EntityComponent(
        logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL,
        DISCOVERY_PLATFORMS)

    component.setup(config)

    def alarm_service_handler(service):
        """ Maps services to methods on Alarm. """
        target_alarms = component.extract_from_service(service)

        if ATTR_CODE not in service.data:
            return

        code = service.data[ATTR_CODE]

        method = SERVICE_TO_METHOD[service.service]

        for alarm in target_alarms:
            getattr(alarm, method)(code)

    for service in SERVICE_TO_METHOD:
        hass.services.register(DOMAIN, service, alarm_service_handler)

    return True
Ejemplo n.º 20
0
def setup(hass, config):
    """ Track states and offer events for remote. """
    component = EntityComponent(logging.getLogger(__name__), DOMAIN, hass,
                                SCAN_INTERVAL, DISCOVERY_PLATFORMS)

    component.setup(config)

    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))

    def remote_service_handler(service):
        """ Maps services to methods on RemoteDevice. """
        target_remotes = component.extract_from_service(service)

        method = SERVICE_TO_METHOD[service.service]

        for remote in target_remotes:
            getattr(remote, method)()

            if remote.should_poll:
                remote.update_ha_state(True)

    for service in SERVICE_TO_METHOD:
        hass.services.register(DOMAIN, service, remote_service_handler,
                               descriptions.get(service))

    return True
Ejemplo n.º 21
0
def setup(hass, config):
    """Track states and offer events for garage door."""
    component = EntityComponent(_LOGGER, DOMAIN, hass, SCAN_INTERVAL,
                                GROUP_NAME_ALL_GARAGE_DOORS)
    component.setup(config)

    def handle_garage_door_service(service):
        """Handle calls to the garage door services."""
        target_locks = component.extract_from_service(service)

        for item in target_locks:
            if service.service == SERVICE_CLOSE:
                item.close_door()
            else:
                item.open_door()

            if item.should_poll:
                item.update_ha_state(True)

    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))
    hass.services.register(DOMAIN,
                           SERVICE_OPEN,
                           handle_garage_door_service,
                           descriptions.get(SERVICE_OPEN),
                           schema=GARAGE_DOOR_SERVICE_SCHEMA)
    hass.services.register(DOMAIN,
                           SERVICE_CLOSE,
                           handle_garage_door_service,
                           descriptions.get(SERVICE_CLOSE),
                           schema=GARAGE_DOOR_SERVICE_SCHEMA)
    return True
Ejemplo n.º 22
0
def setup(hass, config):
    """ Track states and offer events for garage door. """
    component = EntityComponent(
        _LOGGER, DOMAIN, hass, SCAN_INTERVAL, DISCOVERY_PLATFORMS,
        GROUP_NAME_ALL_GARAGE_DOORS)
    component.setup(config)

    def handle_garage_door_service(service):
        """ Handles calls to the garage door services. """
        target_locks = component.extract_from_service(service)

        for item in target_locks:
            if service.service == SERVICE_CLOSE:
                item.close_door()
            else:
                item.open_door()

            if item.should_poll:
                item.update_ha_state(True)

    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))
    hass.services.register(DOMAIN, SERVICE_OPEN, handle_garage_door_service,
                           descriptions.get(SERVICE_OPEN))
    hass.services.register(DOMAIN, SERVICE_CLOSE, handle_garage_door_service,
                           descriptions.get(SERVICE_CLOSE))

    return True
Ejemplo n.º 23
0
async def test_setup_recovers_when_setup_raises(hass):
    """Test the setup if exceptions are happening."""
    platform1_setup = Mock(side_effect=Exception("Broken"))
    platform2_setup = Mock(return_value=None)

    mock_entity_platform(hass, "test_domain.mod1",
                         MockPlatform(platform1_setup))
    mock_entity_platform(hass, "test_domain.mod2",
                         MockPlatform(platform2_setup))

    component = EntityComponent(_LOGGER, DOMAIN, hass)

    assert not platform1_setup.called
    assert not platform2_setup.called

    component.setup(
        OrderedDict([
            (DOMAIN, {
                "platform": "mod1"
            }),
            (f"{DOMAIN} 2", {
                "platform": "non_exist"
            }),
            (f"{DOMAIN} 3", {
                "platform": "mod2"
            }),
        ]))

    await hass.async_block_till_done()
    assert platform1_setup.called
    assert platform2_setup.called
Ejemplo n.º 24
0
async def test_set_entity_namespace_via_config(hass):
    """Test setting an entity namespace."""
    def platform_setup(hass, config, add_entities, discovery_info=None):
        """Test the platform setup."""
        add_entities([
            MockEntity(name='beer'),
            MockEntity(name=None),
        ])

    platform = MockPlatform(platform_setup)

    mock_entity_platform(hass, 'test_domain.platform', platform)

    component = EntityComponent(_LOGGER, DOMAIN, hass)

    component.setup(
        {DOMAIN: {
            'platform': 'platform',
            'entity_namespace': 'yummy'
        }})

    await hass.async_block_till_done()

    assert sorted(hass.states.async_entity_ids()) == \
        ['test_domain.yummy_beer', 'test_domain.yummy_unnamed_device']
Ejemplo n.º 25
0
    def test_setup_loads_platforms(self):
        """Test the loading of the platforms."""
        component_setup = Mock(return_value=True)
        platform_setup = Mock(return_value=None)

        mock_integration(self.hass,
                         MockModule('test_component', setup=component_setup))
        # mock the dependencies
        mock_integration(self.hass,
                         MockModule('mod2', dependencies=['test_component']))
        mock_entity_platform(self.hass, 'test_domain.mod2',
                             MockPlatform(platform_setup))

        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        assert not component_setup.called
        assert not platform_setup.called

        component.setup({DOMAIN: {
            'platform': 'mod2',
        }})

        self.hass.block_till_done()
        assert component_setup.called
        assert platform_setup.called
Ejemplo n.º 26
0
def setup(hass, config):
    """Track states and offer events for sensors."""
    component = EntityComponent(logging.getLogger(__name__), DOMAIN, hass,
                                SCAN_INTERVAL, DISCOVERY_PLATFORMS)

    component.setup(config)

    def alarm_service_handler(service):
        """Map services to methods on Alarm."""
        target_alarms = component.extract_from_service(service)

        if ATTR_CODE not in service.data:
            code = None
        else:
            code = service.data[ATTR_CODE]

        method = SERVICE_TO_METHOD[service.service]

        for alarm in target_alarms:
            getattr(alarm, method)(code)
            if alarm.should_poll:
                alarm.update_ha_state(True)

    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))

    for service in SERVICE_TO_METHOD:
        hass.services.register(DOMAIN, service, alarm_service_handler,
                               descriptions.get(service))

    return True
Ejemplo n.º 27
0
def setup(hass, config):
    """Track states and offer events for calendars."""
    component = EntityComponent(logging.getLogger(__name__), DOMAIN, hass, 60,
                                DOMAIN)

    component.setup(config)

    return True
Ejemplo n.º 28
0
def setup(hass, config):
    """Track states and offer events for calendars."""
    component = EntityComponent(
        logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL, DOMAIN)

    component.setup(config)

    return True
Ejemplo n.º 29
0
def setup(hass, config):
    """Track states and offer events for sensors."""
    component = EntityComponent(logging.getLogger(__name__), DOMAIN, hass,
                                SCAN_INTERVAL)

    component.setup(config)

    return True
Ejemplo n.º 30
0
def setup(hass, config):
    """Setup the camera component."""
    component = EntityComponent(
        logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL,
        DISCOVERY_PLATFORMS)

    component.setup(config)

    def _proxy_camera_image(handler, path_match, data):
        """Serve the camera image via the HA server."""
        entity_id = path_match.group(ATTR_ENTITY_ID)
        camera = component.entities.get(entity_id)

        if camera is None:
            handler.send_response(HTTP_NOT_FOUND)
            handler.end_headers()
            return

        response = camera.camera_image()

        if response is None:
            handler.send_response(HTTP_NOT_FOUND)
            handler.end_headers()
            return

        handler.send_response(HTTP_OK)
        handler.write_content(response)

    hass.http.register_path(
        'GET',
        re.compile(r'/api/camera_proxy/(?P<entity_id>[a-zA-Z\._0-9]+)'),
        _proxy_camera_image)

    def _proxy_camera_mjpeg_stream(handler, path_match, data):
        """Proxy the camera image as an mjpeg stream via the HA server."""
        entity_id = path_match.group(ATTR_ENTITY_ID)
        camera = component.entities.get(entity_id)

        if camera is None:
            handler.send_response(HTTP_NOT_FOUND)
            handler.end_headers()
            return

        try:
            camera.is_streaming = True
            camera.update_ha_state()
            camera.mjpeg_stream(handler)

        except (requests.RequestException, IOError):
            camera.is_streaming = False
            camera.update_ha_state()

    hass.http.register_path(
        'GET',
        re.compile(r'/api/camera_proxy_stream/(?P<entity_id>[a-zA-Z\._0-9]+)'),
        _proxy_camera_mjpeg_stream)

    return True
Ejemplo n.º 31
0
def setup(hass, config: dict) -> None:
    """Expose fan control via statemachine and services."""
    component = EntityComponent(
        _LOGGER, DOMAIN, hass, SCAN_INTERVAL, GROUP_NAME_ALL_FANS)
    component.setup(config)

    def handle_fan_service(service: str) -> None:
        """Hande service call for fans."""
        # Get the validated data
        params = service.data.copy()

        # Convert the entity ids to valid fan ids
        target_fans = component.extract_from_service(service)
        params.pop(ATTR_ENTITY_ID, None)

        service_fun = None
        for service_def in [SERVICE_TURN_ON, SERVICE_TURN_OFF,
                            SERVICE_SET_SPEED, SERVICE_OSCILLATE,
                            SERVICE_SET_DIRECTION]:
            if service_def == service.service:
                service_fun = service_def
                break

        if service_fun:
            for fan in target_fans:
                getattr(fan, service_fun)(**params)

            for fan in target_fans:
                if fan.should_poll:
                    fan.update_ha_state(True)
            return

    # Listen for fan service calls.
    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))
    hass.services.register(DOMAIN, SERVICE_TURN_ON, handle_fan_service,
                           descriptions.get(SERVICE_TURN_ON),
                           schema=FAN_TURN_ON_SCHEMA)

    hass.services.register(DOMAIN, SERVICE_TURN_OFF, handle_fan_service,
                           descriptions.get(SERVICE_TURN_OFF),
                           schema=FAN_TURN_OFF_SCHEMA)

    hass.services.register(DOMAIN, SERVICE_SET_SPEED, handle_fan_service,
                           descriptions.get(SERVICE_SET_SPEED),
                           schema=FAN_SET_SPEED_SCHEMA)

    hass.services.register(DOMAIN, SERVICE_OSCILLATE, handle_fan_service,
                           descriptions.get(SERVICE_OSCILLATE),
                           schema=FAN_OSCILLATE_SCHEMA)

    hass.services.register(DOMAIN, SERVICE_SET_DIRECTION, handle_fan_service,
                           descriptions.get(SERVICE_SET_DIRECTION),
                           schema=FAN_SET_DIRECTION_SCHEMA)

    return True
Ejemplo n.º 32
0
def setup(hass, config):
    """Setup the camera component."""
    component = EntityComponent(logging.getLogger(__name__), DOMAIN, hass,
                                SCAN_INTERVAL, DISCOVERY_PLATFORMS)

    component.setup(config)

    def _proxy_camera_image(handler, path_match, data):
        """Serve the camera image via the HA server."""
        entity_id = path_match.group(ATTR_ENTITY_ID)
        camera = component.entities.get(entity_id)

        if camera is None:
            handler.send_response(HTTP_NOT_FOUND)
            handler.end_headers()
            return

        response = camera.camera_image()

        if response is None:
            handler.send_response(HTTP_NOT_FOUND)
            handler.end_headers()
            return

        handler.send_response(HTTP_OK)
        handler.write_content(response)

    hass.http.register_path(
        'GET', re.compile(r'/api/camera_proxy/(?P<entity_id>[a-zA-Z\._0-9]+)'),
        _proxy_camera_image)

    def _proxy_camera_mjpeg_stream(handler, path_match, data):
        """Proxy the camera image as an mjpeg stream via the HA server."""
        entity_id = path_match.group(ATTR_ENTITY_ID)
        camera = component.entities.get(entity_id)

        if camera is None:
            handler.send_response(HTTP_NOT_FOUND)
            handler.end_headers()
            return

        try:
            camera.is_streaming = True
            camera.update_ha_state()
            camera.mjpeg_stream(handler)

        except (requests.RequestException, IOError):
            camera.is_streaming = False
            camera.update_ha_state()

    hass.http.register_path(
        'GET',
        re.compile(r'/api/camera_proxy_stream/(?P<entity_id>[a-zA-Z\._0-9]+)'),
        _proxy_camera_mjpeg_stream)

    return True
Ejemplo n.º 33
0
def setup(hass, config):
    """Setup the camera component."""
    component = EntityComponent(logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL)

    hass.wsgi.register_view(CameraImageView(hass, component.entities))
    hass.wsgi.register_view(CameraMjpegStream(hass, component.entities))

    component.setup(config)

    return True
Ejemplo n.º 34
0
def setup(hass, config):
    """ Setup thermostats. """
    component = EntityComponent(_LOGGER, DOMAIN, hass,
                                SCAN_INTERVAL, DISCOVERY_PLATFORMS)
    component.setup(config)

    def thermostat_service(service):
        """ Handles calls to the services. """

        # Convert the entity ids to valid light ids
        target_thermostats = component.extract_from_service(service)

        if service.service == SERVICE_SET_AWAY_MODE:
            away_mode = service.data.get(ATTR_AWAY_MODE)

            if away_mode is None:
                _LOGGER.error(
                    "Received call to %s without attribute %s",
                    SERVICE_SET_AWAY_MODE, ATTR_AWAY_MODE)

            elif away_mode:
                for thermostat in target_thermostats:
                    thermostat.turn_away_mode_on()
            else:
                for thermostat in target_thermostats:
                    thermostat.turn_away_mode_off()

        elif service.service == SERVICE_SET_TEMPERATURE:
            temperature = util.convert(
                service.data.get(ATTR_TEMPERATURE), float)

            if temperature is None:
                return

            for thermostat in target_thermostats:
                thermostat.set_temperature(convert(
                    temperature, hass.config.temperature_unit,
                    thermostat.unit_of_measurement))

        for thermostat in target_thermostats:
            thermostat.update_ha_state(True)

    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))

    hass.services.register(
        DOMAIN, SERVICE_SET_AWAY_MODE, thermostat_service,
        descriptions.get(SERVICE_SET_AWAY_MODE))

    hass.services.register(
        DOMAIN, SERVICE_SET_TEMPERATURE, thermostat_service,
        descriptions.get(SERVICE_SET_TEMPERATURE))

    return True
Ejemplo n.º 35
0
def setup(hass, config):
    """ Setup thermostats. """
    component = EntityComponent(_LOGGER, DOMAIN, hass,
                                SCAN_INTERVAL, DISCOVERY_PLATFORMS)
    component.setup(config)

    def thermostat_service(service):
        """ Handles calls to the services. """

        # Convert the entity ids to valid light ids
        target_thermostats = component.extract_from_service(service)

        if service.service == SERVICE_SET_AWAY_MODE:
            away_mode = service.data.get(ATTR_AWAY_MODE)

            if away_mode is None:
                _LOGGER.error(
                    "Received call to %s without attribute %s",
                    SERVICE_SET_AWAY_MODE, ATTR_AWAY_MODE)

            elif away_mode:
                for thermostat in target_thermostats:
                    thermostat.turn_away_mode_on()
            else:
                for thermostat in target_thermostats:
                    thermostat.turn_away_mode_off()

        elif service.service == SERVICE_SET_TEMPERATURE:
            temperature = util.convert(
                service.data.get(ATTR_TEMPERATURE), float)

            if temperature is None:
                return

            for thermostat in target_thermostats:
                thermostat.set_temperature(convert(
                    temperature, hass.config.temperature_unit,
                    thermostat.unit_of_measurement))

        for thermostat in target_thermostats:
            thermostat.update_ha_state(True)

    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))

    hass.services.register(
        DOMAIN, SERVICE_SET_AWAY_MODE, thermostat_service,
        descriptions.get(SERVICE_SET_AWAY_MODE))

    hass.services.register(
        DOMAIN, SERVICE_SET_TEMPERATURE, thermostat_service,
        descriptions.get(SERVICE_SET_TEMPERATURE))

    return True
Ejemplo n.º 36
0
def setup(hass, config):
    """Setup the camera component."""
    component = EntityComponent(logging.getLogger(__name__), DOMAIN, hass,
                                SCAN_INTERVAL)

    hass.wsgi.register_view(CameraImageView(hass, component.entities))
    hass.wsgi.register_view(CameraMjpegStream(hass, component.entities))

    component.setup(config)

    return True
Ejemplo n.º 37
0
    def test_setup_does_discovery(self, mock_setup_component, mock_setup):
        """Test setup for discovery."""
        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        component.setup({})

        discovery.load_platform(self.hass, DOMAIN, "platform_test", {"msg": "discovery_info"})

        self.hass.pool.block_till_done()

        assert mock_setup.called
        assert ("platform_test", {}, {"msg": "discovery_info"}) == mock_setup.call_args[0]
Ejemplo n.º 38
0
def setup(hass, config):
    """Track states and offer events for roller shutters."""
    component = EntityComponent(_LOGGER, DOMAIN, hass, SCAN_INTERVAL,
                                DISCOVERY_PLATFORMS,
                                GROUP_NAME_ALL_ROLLERSHUTTERS)
    component.setup(config)

    def handle_rollershutter_service(service):
        """Handle calls to the roller shutter services."""
        target_rollershutters = component.extract_from_service(service)
        dat = service.data
        params = {}

        for rollershutter in target_rollershutters:
            if service.service == SERVICE_MOVE_UP:
                rollershutter.move_up()
            elif service.service == SERVICE_MOVE_DOWN:
                rollershutter.move_down()
            elif service.service == SERVICE_STOP:
                rollershutter.stop()
            elif service.service == SERVICE_POSITION:
                if ATTR_POSITION in dat:
                    params[ATTR_POSITION] = util.convert(
                        dat.get(ATTR_POSITION), int, params.get(ATTR_POSITION))
                    rollershutter.position(**params)
            if rollershutter.should_poll:
                rollershutter.update_ha_state(True)

    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))

    hass.services.register(DOMAIN,
                           SERVICE_MOVE_UP,
                           handle_rollershutter_service,
                           descriptions.get(SERVICE_MOVE_UP),
                           schema=ROLLERSHUTTER_SERVICE_SCHEMA)
    hass.services.register(DOMAIN,
                           SERVICE_MOVE_DOWN,
                           handle_rollershutter_service,
                           descriptions.get(SERVICE_MOVE_DOWN),
                           schema=ROLLERSHUTTER_SERVICE_SCHEMA)
    hass.services.register(DOMAIN,
                           SERVICE_STOP,
                           handle_rollershutter_service,
                           descriptions.get(SERVICE_STOP),
                           schema=ROLLERSHUTTER_SERVICE_SCHEMA)
    hass.services.register(DOMAIN,
                           SERVICE_POSITION,
                           handle_rollershutter_service,
                           descriptions.get(SERVICE_POSITION),
                           schema=ROLLERSHUTTER_SERVICE_SCHEMA)
    return True
Ejemplo n.º 39
0
def setup(hass, config):
    """Track states and offer events for roller shutters."""
    _LOGGER.warning('This component has been deprecated in favour of the '
                    '"cover" component and will be removed in the future.'
                    ' Please upgrade.')
    component = EntityComponent(_LOGGER, DOMAIN, hass, SCAN_INTERVAL,
                                GROUP_NAME_ALL_ROLLERSHUTTERS)
    component.setup(config)

    def handle_rollershutter_service(service):
        """Handle calls to the roller shutter services."""
        target_rollershutters = component.extract_from_service(service)

        for rollershutter in target_rollershutters:
            if service.service == SERVICE_MOVE_UP:
                rollershutter.move_up()
            elif service.service == SERVICE_MOVE_DOWN:
                rollershutter.move_down()
            elif service.service == SERVICE_MOVE_POSITION:
                rollershutter.move_position(service.data[ATTR_POSITION])
            elif service.service == SERVICE_STOP:
                rollershutter.stop()

            if rollershutter.should_poll:
                rollershutter.update_ha_state(True)

    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))

    hass.services.register(DOMAIN,
                           SERVICE_MOVE_UP,
                           handle_rollershutter_service,
                           descriptions.get(SERVICE_MOVE_UP),
                           schema=ROLLERSHUTTER_SERVICE_SCHEMA)
    hass.services.register(DOMAIN,
                           SERVICE_MOVE_DOWN,
                           handle_rollershutter_service,
                           descriptions.get(SERVICE_MOVE_DOWN),
                           schema=ROLLERSHUTTER_SERVICE_SCHEMA)
    hass.services.register(DOMAIN,
                           SERVICE_MOVE_POSITION,
                           handle_rollershutter_service,
                           descriptions.get(SERVICE_MOVE_POSITION),
                           schema=ROLLERSHUTTER_MOVE_POSITION_SCHEMA)
    hass.services.register(DOMAIN,
                           SERVICE_STOP,
                           handle_rollershutter_service,
                           descriptions.get(SERVICE_STOP),
                           schema=ROLLERSHUTTER_SERVICE_SCHEMA)
    return True
    def test_setup_does_discovery(self, mock_setup_component, mock_setup):
        """Test setup for discovery."""
        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        component.setup({})

        discovery.load_platform(self.hass, DOMAIN, 'platform_test',
                                {'msg': 'discovery_info'})

        self.hass.block_till_done()

        assert mock_setup.called
        assert ('platform_test', {}, {'msg': 'discovery_info'}) == \
            mock_setup.call_args[0]
async def test_setup_does_discovery(mock_setup_component, mock_setup, hass):
    """Test setup for discovery."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)

    component.setup({})

    discovery.load_platform(
        hass, DOMAIN, "platform_test", {"msg": "discovery_info"}, {DOMAIN: {}}
    )

    await hass.async_block_till_done()

    assert mock_setup.called
    assert ("platform_test", {}, {"msg": "discovery_info"}) == mock_setup.call_args[0]
Ejemplo n.º 42
0
    def test_setup_does_discovery(self, mock_setup_component, mock_setup):
        """Test setup for discovery."""
        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        component.setup({})

        discovery.load_platform(self.hass, DOMAIN, 'platform_test',
                                {'msg': 'discovery_info'})

        self.hass.block_till_done()

        assert mock_setup.called
        assert ('platform_test', {}, {'msg': 'discovery_info'}) == \
            mock_setup.call_args[0]
    def test_setup_does_discovery(self, mock_setup):
        """Test setup for discovery."""
        component = EntityComponent(_LOGGER, DOMAIN, self.hass, discovery_platforms={"discovery.test": "platform_test"})

        component.setup({})

        self.hass.bus.fire(
            discovery.EVENT_PLATFORM_DISCOVERED,
            {discovery.ATTR_SERVICE: "discovery.test", discovery.ATTR_DISCOVERED: "discovery_info"},
        )

        self.hass.pool.block_till_done()

        assert mock_setup.called
        assert ("platform_test", {}, "discovery_info") == mock_setup.call_args[0]
Ejemplo n.º 44
0
    def test_set_scan_interval_via_config(self, mock_track):
        """Test the setting of the scan interval via configuration."""

        def platform_setup(hass, config, add_devices, discovery_info=None):
            """Test the platform setup."""
            add_devices([EntityTest(should_poll=True)])

        loader.set_component("test_domain.platform", MockPlatform(platform_setup))

        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        component.setup({DOMAIN: {"platform": "platform", "scan_interval": 30}})

        assert mock_track.called
        assert [0, 30] == list(mock_track.call_args[1]["second"])
Ejemplo n.º 45
0
    def test_setup_loads_platforms(self):
        """Test the loading of the platforms."""
        component_setup = Mock(return_value=True)
        platform_setup = Mock(return_value=None)
        loader.set_component("test_component", MockModule("test_component", setup=component_setup))
        loader.set_component("test_domain.mod2", MockPlatform(platform_setup, ["test_component"]))

        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        assert not component_setup.called
        assert not platform_setup.called

        component.setup({DOMAIN: {"platform": "mod2"}})

        assert component_setup.called
        assert platform_setup.called
Ejemplo n.º 46
0
    def test_set_entity_namespace_via_config(self):
        """Test setting an entity namespace."""

        def platform_setup(hass, config, add_devices, discovery_info=None):
            """Test the platform setup."""
            add_devices([EntityTest(name="beer"), EntityTest(name=None)])

        platform = MockPlatform(platform_setup)

        loader.set_component("test_domain.platform", platform)

        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        component.setup({DOMAIN: {"platform": "platform", "entity_namespace": "yummy"}})

        assert sorted(self.hass.states.entity_ids()) == ["test_domain.yummy_beer", "test_domain.yummy_unnamed_device"]
Ejemplo n.º 47
0
def setup(hass, config):
    """Track states and offer events for roller shutters."""
    component = EntityComponent(
        _LOGGER, DOMAIN, hass, SCAN_INTERVAL, DISCOVERY_PLATFORMS,
        GROUP_NAME_ALL_ROLLERSHUTTERS)
    component.setup(config)

    def handle_rollershutter_service(service):
        """Handle calls to the roller shutter services."""
        target_rollershutters = component.extract_from_service(service)
        dat = service.data
        params = {}

        for rollershutter in target_rollershutters:
            if service.service == SERVICE_MOVE_UP:
                rollershutter.move_up()
            elif service.service == SERVICE_MOVE_DOWN:
                rollershutter.move_down()
            elif service.service == SERVICE_STOP:
                rollershutter.stop()
            elif service.service == SERVICE_POSITION:
                if ATTR_POSITION in dat:
                    params[ATTR_POSITION] = util.convert(dat.get(ATTR_POSITION), int, params.get(ATTR_POSITION))
                    rollershutter.position(**params)
            if rollershutter.should_poll:
                rollershutter.update_ha_state(True)

    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))

    hass.services.register(DOMAIN, SERVICE_MOVE_UP,
                           handle_rollershutter_service,
                           descriptions.get(SERVICE_MOVE_UP),
                           schema=ROLLERSHUTTER_SERVICE_SCHEMA)
    hass.services.register(DOMAIN, SERVICE_MOVE_DOWN,
                           handle_rollershutter_service,
                           descriptions.get(SERVICE_MOVE_DOWN),
                           schema=ROLLERSHUTTER_SERVICE_SCHEMA)
    hass.services.register(DOMAIN, SERVICE_STOP,
                           handle_rollershutter_service,
                           descriptions.get(SERVICE_STOP),
                           schema=ROLLERSHUTTER_SERVICE_SCHEMA)
    hass.services.register(DOMAIN, SERVICE_POSITION,
                           handle_rollershutter_service,
                           descriptions.get(SERVICE_POSITION),
                           schema=ROLLERSHUTTER_SERVICE_SCHEMA)
    return True
Ejemplo n.º 48
0
    def test_set_scan_interval_via_platform(self, mock_track):
        def platform_setup(hass, config, add_devices, discovery_info=None):
            add_devices([EntityTest(should_poll=True)])

        platform = MockPlatform(platform_setup)
        platform.SCAN_INTERVAL = 30

        loader.set_component('test_domain.platform', platform)

        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        component.setup({DOMAIN: {
            'platform': 'platform',
        }})

        assert mock_track.called
        assert [0, 30] == list(mock_track.call_args[1]['second'])
Ejemplo n.º 49
0
def setup(hass, config):
    """Track states and offer events for roller shutters."""
    _LOGGER.warning('This component has been deprecated in favour of the '
                    '"cover" component and will be removed in the future.'
                    ' Please upgrade.')
    component = EntityComponent(
        _LOGGER, DOMAIN, hass, SCAN_INTERVAL, GROUP_NAME_ALL_ROLLERSHUTTERS)
    component.setup(config)

    def handle_rollershutter_service(service):
        """Handle calls to the roller shutter services."""
        target_rollershutters = component.extract_from_service(service)

        for rollershutter in target_rollershutters:
            if service.service == SERVICE_MOVE_UP:
                rollershutter.move_up()
            elif service.service == SERVICE_MOVE_DOWN:
                rollershutter.move_down()
            elif service.service == SERVICE_MOVE_POSITION:
                rollershutter.move_position(service.data[ATTR_POSITION])
            elif service.service == SERVICE_STOP:
                rollershutter.stop()

            if rollershutter.should_poll:
                rollershutter.update_ha_state(True)

    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))

    hass.services.register(DOMAIN, SERVICE_MOVE_UP,
                           handle_rollershutter_service,
                           descriptions.get(SERVICE_MOVE_UP),
                           schema=ROLLERSHUTTER_SERVICE_SCHEMA)
    hass.services.register(DOMAIN, SERVICE_MOVE_DOWN,
                           handle_rollershutter_service,
                           descriptions.get(SERVICE_MOVE_DOWN),
                           schema=ROLLERSHUTTER_SERVICE_SCHEMA)
    hass.services.register(DOMAIN, SERVICE_MOVE_POSITION,
                           handle_rollershutter_service,
                           descriptions.get(SERVICE_MOVE_POSITION),
                           schema=ROLLERSHUTTER_MOVE_POSITION_SCHEMA)
    hass.services.register(DOMAIN, SERVICE_STOP,
                           handle_rollershutter_service,
                           descriptions.get(SERVICE_STOP),
                           schema=ROLLERSHUTTER_SERVICE_SCHEMA)
    return True
Ejemplo n.º 50
0
def setup(hass, config):
    """Track states and offer events for remotes."""
    component = EntityComponent(_LOGGER, DOMAIN, hass, SCAN_INTERVAL,
                                GROUP_NAME_ALL_REMOTES)
    component.setup(config)

    def handle_remote_service(service):
        """Handle calls to the remote services."""
        target_remotes = component.extract_from_service(service)

        activity_id = service.data.get(ATTR_ACTIVITY)
        device = service.data.get(ATTR_DEVICE)
        command = service.data.get(ATTR_COMMAND)

        for remote in target_remotes:
            if service.service == SERVICE_TURN_ON:
                remote.turn_on(activity=activity_id)
            elif service.service == SERVICE_SEND_COMMAND:
                remote.send_command(device=device, command=command)
            elif service.service == SERVICE_SYNC:
                remote.sync()
            else:
                remote.turn_off()

            if remote.should_poll:
                remote.update_ha_state(True)

    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))
    hass.services.register(DOMAIN,
                           SERVICE_TURN_OFF,
                           handle_remote_service,
                           descriptions.get(SERVICE_TURN_OFF),
                           schema=REMOTE_SERVICE_SCHEMA)
    hass.services.register(DOMAIN,
                           SERVICE_TURN_ON,
                           handle_remote_service,
                           descriptions.get(SERVICE_TURN_ON),
                           schema=REMOTE_SERVICE_TURN_ON_SCHEMA)
    hass.services.register(DOMAIN,
                           SERVICE_SEND_COMMAND,
                           handle_remote_service,
                           descriptions.get(SERVICE_SEND_COMMAND),
                           schema=REMOTE_SERVICE_SEND_COMMAND_SCHEMA)

    return True
Ejemplo n.º 51
0
def setup(hass, config):
    """ Setup thermostats. """
    component = EntityComponent(_LOGGER, DOMAIN, hass, SCAN_INTERVAL)
    component.setup(config)

    def thermostat_service(service):
        """ Handles calls to the services. """

        # Convert the entity ids to valid light ids
        target_thermostats = component.extract_from_service(service)

        if service.service == SERVICE_SET_AWAY_MODE:
            away_mode = service.data.get(ATTR_AWAY_MODE)

            if away_mode is None:
                _LOGGER.error(
                    "Received call to %s without attribute %s",
                    SERVICE_SET_AWAY_MODE, ATTR_AWAY_MODE)

            elif away_mode:
                for thermostat in target_thermostats:
                    thermostat.turn_away_mode_on()
            else:
                for thermostat in target_thermostats:
                    thermostat.turn_away_mode_off()

        elif service.service == SERVICE_SET_TEMPERATURE:
            temperature = util.convert(
                service.data.get(ATTR_TEMPERATURE), float)

            if temperature is None:
                return

            for thermostat in target_thermostats:
                thermostat.set_temperature(temperature)

        for thermostat in target_thermostats:
            thermostat.update_ha_state(True)

    hass.services.register(
        DOMAIN, SERVICE_SET_AWAY_MODE, thermostat_service)

    hass.services.register(
        DOMAIN, SERVICE_SET_TEMPERATURE, thermostat_service)

    return True
Ejemplo n.º 52
0
def setup(hass, config):
    """ Track states and offer events for media_players. """
    component = EntityComponent(
        logging.getLogger(__name__), DOMAIN, hass, SCAN_INTERVAL,
        DISCOVERY_PLATFORMS)

    component.setup(config)

    def media_player_service_handler(service):
        """ Maps services to methods on MediaPlayerDevice. """
        target_players = component.extract_from_service(service)

        method = SERVICE_TO_METHOD[service.service]

        for player in target_players:
            getattr(player, method)()

            if player.should_poll:
                player.update_ha_state(True)

    for service in SERVICE_TO_METHOD:
        hass.services.register(DOMAIN, service, media_player_service_handler)

    def play_youtube_video_service(service, media_id):
        """ Plays specified media_id on the media player. """
        target_players = component.extract_from_service(service)

        if media_id:
            for player in target_players:
                player.play_youtube(media_id)

    hass.services.register(DOMAIN, "start_fireplace",
                           lambda service:
                           play_youtube_video_service(service, "eyU3bRy2x44"))

    hass.services.register(DOMAIN, "start_epic_sax",
                           lambda service:
                           play_youtube_video_service(service, "kxopViU98Xo"))

    hass.services.register(DOMAIN, SERVICE_YOUTUBE_VIDEO,
                           lambda service:
                           play_youtube_video_service(
                               service, service.data.get('video')))

    return True
Ejemplo n.º 53
0
async def test_set_scan_interval_via_platform(mock_track, hass):
    """Test the setting of the scan interval via platform."""
    def platform_setup(hass, config, add_entities, discovery_info=None):
        """Test the platform setup."""
        add_entities([MockEntity(should_poll=True)])

    platform = MockPlatform(platform_setup)
    platform.SCAN_INTERVAL = timedelta(seconds=30)

    mock_entity_platform(hass, "test_domain.platform", platform)

    component = EntityComponent(_LOGGER, DOMAIN, hass)

    component.setup({DOMAIN: {"platform": "platform"}})

    await hass.async_block_till_done()
    assert mock_track.called
    assert timedelta(seconds=30) == mock_track.call_args[0][2]
Ejemplo n.º 54
0
    def test_setup_does_discovery(self, mock_setup):
        component = EntityComponent(
            _LOGGER, DOMAIN, self.hass, discovery_platforms={
                'discovery.test': 'platform_test',
            })

        component.setup({})

        self.hass.bus.fire(discovery.EVENT_PLATFORM_DISCOVERED, {
            discovery.ATTR_SERVICE: 'discovery.test',
            discovery.ATTR_DISCOVERED: 'discovery_info',
        })

        self.hass.pool.block_till_done()

        assert mock_setup.called
        assert ('platform_test', {}, 'discovery_info') == \
            mock_setup.call_args[0]
    def test_set_scan_interval_via_config(self, mock_track):
        def platform_setup(hass, config, add_devices, discovery_info=None):
            add_devices([EntityTest(should_poll=True)])

        loader.set_component('test_domain.platform',
                             MockPlatform(platform_setup))

        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        component.setup({
            DOMAIN: {
                'platform': 'platform',
                'scan_interval': 30,
            }
        })

        assert mock_track.called
        assert [0, 30] == list(mock_track.call_args[1]['second'])
Ejemplo n.º 56
0
def setup(hass, config):
    """ Track states and offer events for media_players. """
    component = EntityComponent(logging.getLogger(__name__), DOMAIN, hass,
                                SCAN_INTERVAL, DISCOVERY_PLATFORMS)

    component.setup(config)

    def media_player_service_handler(service):
        """ Maps services to methods on MediaPlayerDevice. """
        target_players = component.extract_from_service(service)

        method = SERVICE_TO_METHOD[service.service]

        for player in target_players:
            getattr(player, method)()

            if player.should_poll:
                player.update_ha_state(True)

    for service in SERVICE_TO_METHOD:
        hass.services.register(DOMAIN, service, media_player_service_handler)

    def play_youtube_video_service(service, media_id):
        """ Plays specified media_id on the media player. """
        target_players = component.extract_from_service(service)

        if media_id:
            for player in target_players:
                player.play_youtube(media_id)

    hass.services.register(
        DOMAIN, "start_fireplace",
        lambda service: play_youtube_video_service(service, "eyU3bRy2x44"))

    hass.services.register(
        DOMAIN, "start_epic_sax",
        lambda service: play_youtube_video_service(service, "kxopViU98Xo"))

    hass.services.register(
        DOMAIN, SERVICE_YOUTUBE_VIDEO,
        lambda service: play_youtube_video_service(service,
                                                   service.data.get('video')))

    return True
Ejemplo n.º 57
0
    def test_set_scan_interval_via_config(self, mock_track):
        """Test the setting of the scan interval via configuration."""
        def platform_setup(hass, config, add_devices, discovery_info=None):
            """Test the platform setup."""
            add_devices([EntityTest(should_poll=True)])

        loader.set_component('test_domain.platform',
                             MockPlatform(platform_setup))

        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        component.setup(
            {DOMAIN: {
                'platform': 'platform',
                'scan_interval': 30,
            }})

        assert mock_track.called
        assert [0, 30] == list(mock_track.call_args[1]['second'])
    def test_setup_recovers_when_setup_raises(self):
        platform1_setup = Mock(side_effect=Exception('Broken'))
        platform2_setup = Mock(return_value=None)

        loader.set_component('test_domain.mod1', MockPlatform(platform1_setup))
        loader.set_component('test_domain.mod2', MockPlatform(platform2_setup))

        component = EntityComponent(_LOGGER, DOMAIN, self.hass)

        assert not platform1_setup.called
        assert not platform2_setup.called

        component.setup(OrderedDict([
            (DOMAIN, {'platform': 'mod1'}),
            ("{} 2".format(DOMAIN), {'platform': 'non_exist'}),
            ("{} 3".format(DOMAIN), {'platform': 'mod2'}),
        ]))

        assert platform1_setup.called
        assert platform2_setup.called