Example #1
0
async def async_setup(hass, config):
    """Set up an input text box."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)

    entities = []

    for object_id, cfg in config[DOMAIN].items():
        name = cfg.get(CONF_NAME)
        minimum = cfg.get(CONF_MIN)
        maximum = cfg.get(CONF_MAX)
        initial = cfg.get(CONF_INITIAL)
        icon = cfg.get(CONF_ICON)
        unit = cfg.get(ATTR_UNIT_OF_MEASUREMENT)
        pattern = cfg.get(ATTR_PATTERN)
        mode = cfg.get(CONF_MODE)

        entities.append(InputText(
            object_id, name, initial, minimum, maximum, icon, unit,
            pattern, mode))

    if not entities:
        return False

    component.async_register_entity_service(
        SERVICE_SET_VALUE, SERVICE_SET_VALUE_SCHEMA,
        'async_set_value'
    )

    await component.async_add_entities(entities)
    return True
Example #2
0
async def async_setup(hass, config):
    """Set up a timer."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)

    entities = []

    for object_id, cfg in config[DOMAIN].items():
        if not cfg:
            cfg = {}

        name = cfg.get(CONF_NAME)
        icon = cfg.get(CONF_ICON)
        duration = cfg.get(CONF_DURATION)

        entities.append(Timer(hass, object_id, name, icon, duration))

    if not entities:
        return False

    component.async_register_entity_service(
        SERVICE_START, SERVICE_SCHEMA_DURATION,
        'async_start')
    component.async_register_entity_service(
        SERVICE_PAUSE, SERVICE_SCHEMA,
        'async_pause')
    component.async_register_entity_service(
        SERVICE_CANCEL, SERVICE_SCHEMA,
        'async_cancel')
    component.async_register_entity_service(
        SERVICE_FINISH, SERVICE_SCHEMA,
        'async_finish')

    await component.async_add_entities(entities)
    return True
Example #3
0
async def async_setup(hass, config):
    """Track states and offer events for remotes."""
    component = EntityComponent(
        _LOGGER, DOMAIN, hass, SCAN_INTERVAL, GROUP_NAME_ALL_REMOTES)
    await component.async_setup(config)

    component.async_register_entity_service(
        SERVICE_TURN_OFF, REMOTE_SERVICE_ACTIVITY_SCHEMA,
        'async_turn_off'
    )

    component.async_register_entity_service(
        SERVICE_TURN_ON, REMOTE_SERVICE_ACTIVITY_SCHEMA,
        'async_turn_on'
    )

    component.async_register_entity_service(
        SERVICE_TOGGLE, REMOTE_SERVICE_ACTIVITY_SCHEMA,
        'async_toggle'
    )

    component.async_register_entity_service(
        SERVICE_SEND_COMMAND, REMOTE_SERVICE_SEND_COMMAND_SCHEMA,
        'async_send_command'
    )

    return True
Example #4
0
async def async_setup(hass, config):
    """Set up the counters."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)

    entities = []

    for object_id, cfg in config[DOMAIN].items():
        if not cfg:
            cfg = {}

        name = cfg.get(CONF_NAME)
        initial = cfg.get(CONF_INITIAL)
        step = cfg.get(CONF_STEP)
        icon = cfg.get(CONF_ICON)

        entities.append(Counter(object_id, name, initial, step, icon))

    if not entities:
        return False

    component.async_register_entity_service(
        SERVICE_INCREMENT, SERVICE_SCHEMA,
        'async_increment')
    component.async_register_entity_service(
        SERVICE_DECREMENT, SERVICE_SCHEMA,
        'async_decrement')
    component.async_register_entity_service(
        SERVICE_RESET, SERVICE_SCHEMA,
        'async_reset')

    await component.async_add_entities(entities)
    return True
Example #5
0
async def async_setup(hass, config):
    """Set up an input datetime."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)

    entities = []

    for object_id, cfg in config[DOMAIN].items():
        name = cfg.get(CONF_NAME)
        has_time = cfg.get(CONF_HAS_TIME)
        has_date = cfg.get(CONF_HAS_DATE)
        icon = cfg.get(CONF_ICON)
        initial = cfg.get(CONF_INITIAL)
        entities.append(InputDatetime(object_id, name,
                                      has_date, has_time, icon, initial))

    if not entities:
        return False

    async def async_set_datetime_service(entity, call):
        """Handle a call to the input datetime 'set datetime' service."""
        time = call.data.get(ATTR_TIME)
        date = call.data.get(ATTR_DATE)
        if (entity.has_date and not date) or (entity.has_time and not time):
            _LOGGER.error("Invalid service data for %s "
                          "input_datetime.set_datetime: %s",
                          entity.entity_id, str(call.data))
            return

        entity.async_set_datetime(date, time)

    component.async_register_entity_service(
        SERVICE_SET_DATETIME, SERVICE_SET_DATETIME_SCHEMA,
        async_set_datetime_service
    )

    await component.async_add_entities(entities)
    return True
Example #6
0
async def async_setup(hass, config):
    """Set up an Utility Meter."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)
    hass.data[DATA_UTILITY] = {}
    register_services = False

    for meter, conf in config.get(DOMAIN).items():
        _LOGGER.debug("Setup %s.%s", DOMAIN, meter)

        hass.data[DATA_UTILITY][meter] = conf

        if not conf[CONF_TARIFFS]:
            # only one entity is required
            hass.async_create_task(discovery.async_load_platform(
                hass, SENSOR_DOMAIN, DOMAIN,
                [{CONF_METER: meter, CONF_NAME: meter}], config))
        else:
            # create tariff selection
            await component.async_add_entities([
                TariffSelect(meter, list(conf[CONF_TARIFFS]))
            ])
            hass.data[DATA_UTILITY][meter][CONF_TARIFF_ENTITY] =\
                "{}.{}".format(DOMAIN, meter)

            # add one meter for each tariff
            tariff_confs = []
            for tariff in conf[CONF_TARIFFS]:
                tariff_confs.append({
                    CONF_METER: meter,
                    CONF_NAME: "{} {}".format(meter, tariff),
                    CONF_TARIFF: tariff,
                    })
            hass.async_create_task(discovery.async_load_platform(
                hass, SENSOR_DOMAIN, DOMAIN, tariff_confs, config))
            register_services = True

    if register_services:
        component.async_register_entity_service(
            SERVICE_RESET, SERVICE_METER_SCHEMA,
            'async_reset_meters'
        )

        component.async_register_entity_service(
            SERVICE_SELECT_TARIFF, SERVICE_SELECT_TARIFF_SCHEMA,
            'async_select_tariff'
        )

        component.async_register_entity_service(
            SERVICE_SELECT_NEXT_TARIFF, SERVICE_METER_SCHEMA,
            'async_next_tariff'
        )

    return True
Example #7
0
async def async_setup(hass, config):
    """Set up an input select."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)

    entities = []

    for object_id, cfg in config[DOMAIN].items():
        name = cfg.get(CONF_NAME)
        options = cfg.get(CONF_OPTIONS)
        initial = cfg.get(CONF_INITIAL)
        icon = cfg.get(CONF_ICON)
        entities.append(InputSelect(object_id, name, initial, options, icon))

    if not entities:
        return False

    component.async_register_entity_service(
        SERVICE_SELECT_OPTION, SERVICE_SELECT_OPTION_SCHEMA,
        'async_select_option'
    )

    component.async_register_entity_service(
        SERVICE_SELECT_NEXT, SERVICE_SELECT_NEXT_SCHEMA,
        lambda entity, call: entity.async_offset_index(1)
    )

    component.async_register_entity_service(
        SERVICE_SELECT_PREVIOUS, SERVICE_SELECT_PREVIOUS_SCHEMA,
        lambda entity, call: entity.async_offset_index(-1)
    )

    component.async_register_entity_service(
        SERVICE_SET_OPTIONS, SERVICE_SET_OPTIONS_SCHEMA,
        'async_set_options'
    )

    await component.async_add_entities(entities)
    return True
Example #8
0
async def async_setup(hass, config):
    """Track states and offer events for locks."""
    component = EntityComponent(
        _LOGGER, DOMAIN, hass, SCAN_INTERVAL, GROUP_NAME_ALL_LOCKS)

    await component.async_setup(config)

    component.async_register_entity_service(
        SERVICE_UNLOCK, LOCK_SERVICE_SCHEMA,
        'async_unlock'
    )
    component.async_register_entity_service(
        SERVICE_LOCK, LOCK_SERVICE_SCHEMA,
        'async_lock'
    )
    component.async_register_entity_service(
        SERVICE_OPEN, LOCK_SERVICE_SCHEMA,
        'async_open'
    )

    return True
Example #9
0
async def async_setup(hass, config):
    """Set up an input slider."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)

    entities = []

    for object_id, cfg in config[DOMAIN].items():
        name = cfg.get(CONF_NAME)
        minimum = cfg.get(CONF_MIN)
        maximum = cfg.get(CONF_MAX)
        initial = cfg.get(CONF_INITIAL)
        step = cfg.get(CONF_STEP)
        icon = cfg.get(CONF_ICON)
        unit = cfg.get(ATTR_UNIT_OF_MEASUREMENT)
        mode = cfg.get(CONF_MODE)

        entities.append(InputNumber(
            object_id, name, initial, minimum, maximum, step, icon, unit,
            mode))

    if not entities:
        return False

    component.async_register_entity_service(
        SERVICE_SET_VALUE, SERVICE_SET_VALUE_SCHEMA,
        'async_set_value'
    )

    component.async_register_entity_service(
        SERVICE_INCREMENT, SERVICE_DEFAULT_SCHEMA,
        'async_increment'
    )

    component.async_register_entity_service(
        SERVICE_DECREMENT, SERVICE_DEFAULT_SCHEMA,
        'async_decrement'
    )

    await component.async_add_entities(entities)
    return True
Example #10
0
async def async_setup(hass, config):
    """Set up an input boolean."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)

    entities = []

    for object_id, cfg in config[DOMAIN].items():
        if not cfg:
            cfg = {}

        name = cfg.get(CONF_NAME)
        initial = cfg.get(CONF_INITIAL)
        icon = cfg.get(CONF_ICON)

        entities.append(InputBoolean(object_id, name, initial, icon))

    if not entities:
        return False

    component.async_register_entity_service(
        SERVICE_TURN_ON, SERVICE_SCHEMA,
        'async_turn_on'
    )

    component.async_register_entity_service(
        SERVICE_TURN_OFF, SERVICE_SCHEMA,
        'async_turn_off'
    )

    component.async_register_entity_service(
        SERVICE_TOGGLE, SERVICE_SCHEMA,
        'async_toggle'
    )

    await component.async_add_entities(entities)
    return True
Example #11
0
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
    """Set up an input slider."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)

    # Process integration platforms right away since
    # we will create entities before firing EVENT_COMPONENT_LOADED
    await async_process_integration_platform_for_component(hass, DOMAIN)

    id_manager = collection.IDManager()

    yaml_collection = collection.YamlCollection(
        logging.getLogger(f"{__name__}.yaml_collection"), id_manager)
    collection.sync_entity_lifecycle(hass, DOMAIN, DOMAIN, component,
                                     yaml_collection, InputNumber.from_yaml)

    storage_collection = NumberStorageCollection(
        Store(hass, STORAGE_VERSION, STORAGE_KEY),
        logging.getLogger(f"{__name__}.storage_collection"),
        id_manager,
    )
    collection.sync_entity_lifecycle(hass, DOMAIN, DOMAIN, component,
                                     storage_collection, InputNumber)

    await yaml_collection.async_load([{
        CONF_ID: id_,
        **(conf or {})
    } for id_, conf in config.get(DOMAIN, {}).items()])
    await storage_collection.async_load()

    collection.StorageCollectionWebsocket(storage_collection, DOMAIN, DOMAIN,
                                          CREATE_FIELDS,
                                          UPDATE_FIELDS).async_setup(hass)

    async def reload_service_handler(service_call: ServiceCall) -> None:
        """Reload yaml entities."""
        conf = await component.async_prepare_reload(skip_reset=True)
        if conf is None:
            conf = {DOMAIN: {}}
        await yaml_collection.async_load([{
            CONF_ID: id_,
            **conf
        } for id_, conf in conf.get(DOMAIN, {}).items()])

    homeassistant.helpers.service.async_register_admin_service(
        hass,
        DOMAIN,
        SERVICE_RELOAD,
        reload_service_handler,
        schema=RELOAD_SERVICE_SCHEMA,
    )

    component.async_register_entity_service(
        SERVICE_SET_VALUE,
        {vol.Required(ATTR_VALUE): vol.Coerce(float)},
        "async_set_value",
    )

    component.async_register_entity_service(SERVICE_INCREMENT, {},
                                            "async_increment")

    component.async_register_entity_service(SERVICE_DECREMENT, {},
                                            "async_decrement")

    return True
Example #12
0
def async_setup(hass, config: dict):
    """Expose fan control via statemachine and services."""
    component = EntityComponent(_LOGGER, DOMAIN, hass, SCAN_INTERVAL,
                                GROUP_NAME_ALL_FANS)

    yield from component.async_setup(config)

    component.async_register_entity_service(SERVICE_TURN_ON,
                                            FAN_TURN_ON_SCHEMA,
                                            'async_turn_on')
    component.async_register_entity_service(SERVICE_TURN_OFF,
                                            FAN_TURN_OFF_SCHEMA,
                                            'async_turn_off')
    component.async_register_entity_service(SERVICE_TOGGLE, FAN_TOGGLE_SCHEMA,
                                            'async_toggle')
    component.async_register_entity_service(SERVICE_SET_SPEED,
                                            FAN_SET_SPEED_SCHEMA,
                                            'async_set_speed')
    component.async_register_entity_service(SERVICE_OSCILLATE,
                                            FAN_OSCILLATE_SCHEMA,
                                            'async_oscillate')
    component.async_register_entity_service(SERVICE_SET_DIRECTION,
                                            FAN_SET_DIRECTION_SCHEMA,
                                            'async_set_direction')

    return True
Example #13
0
def async_setup(hass, config: dict):
    """Expose fan control via statemachine and services."""
    component = EntityComponent(
        _LOGGER, DOMAIN, hass, SCAN_INTERVAL, GROUP_NAME_ALL_FANS)

    yield from component.async_setup(config)

    component.async_register_entity_service(
        SERVICE_TURN_ON, FAN_TURN_ON_SCHEMA,
        'async_turn_on'
    )
    component.async_register_entity_service(
        SERVICE_TURN_OFF, FAN_TURN_OFF_SCHEMA,
        'async_turn_off'
    )
    component.async_register_entity_service(
        SERVICE_TOGGLE, FAN_TOGGLE_SCHEMA,
        'async_toggle'
    )
    component.async_register_entity_service(
        SERVICE_SET_SPEED, FAN_SET_SPEED_SCHEMA,
        'async_set_speed'
    )
    component.async_register_entity_service(
        SERVICE_OSCILLATE, FAN_OSCILLATE_SCHEMA,
        'async_oscillate'
    )
    component.async_register_entity_service(
        SERVICE_SET_DIRECTION, FAN_SET_DIRECTION_SCHEMA,
        'async_set_direction'
    )

    return True
Example #14
0
async def async_setup(hass, config):
    """Set up the vacuum component."""
    component = EntityComponent(
        _LOGGER, DOMAIN, hass, SCAN_INTERVAL, GROUP_NAME_ALL_VACUUMS)

    await component.async_setup(config)

    component.async_register_entity_service(
        SERVICE_TURN_ON, VACUUM_SERVICE_SCHEMA,
        'async_turn_on'
    )
    component.async_register_entity_service(
        SERVICE_TURN_OFF, VACUUM_SERVICE_SCHEMA,
        'async_turn_off'
    )
    component.async_register_entity_service(
        SERVICE_TOGGLE, VACUUM_SERVICE_SCHEMA,
        'async_toggle'
    )
    component.async_register_entity_service(
        SERVICE_START_PAUSE, VACUUM_SERVICE_SCHEMA,
        'async_start_pause'
    )
    component.async_register_entity_service(
        SERVICE_START, VACUUM_SERVICE_SCHEMA,
        'async_start'
    )
    component.async_register_entity_service(
        SERVICE_PAUSE, VACUUM_SERVICE_SCHEMA,
        'async_pause'
    )
    component.async_register_entity_service(
        SERVICE_RETURN_TO_BASE, VACUUM_SERVICE_SCHEMA,
        'async_return_to_base'
    )
    component.async_register_entity_service(
        SERVICE_CLEAN_SPOT, VACUUM_SERVICE_SCHEMA,
        'async_clean_spot'
    )
    component.async_register_entity_service(
        SERVICE_LOCATE, VACUUM_SERVICE_SCHEMA,
        'async_locate'
    )
    component.async_register_entity_service(
        SERVICE_STOP, VACUUM_SERVICE_SCHEMA,
        'async_stop'
    )
    component.async_register_entity_service(
        SERVICE_SET_FAN_SPEED, VACUUM_SET_FAN_SPEED_SERVICE_SCHEMA,
        'async_set_fan_speed'
    )
    component.async_register_entity_service(
        SERVICE_SEND_COMMAND, VACUUM_SEND_COMMAND_SERVICE_SCHEMA,
        'async_send_command'
    )

    return True
Example #15
0
async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
    """Set up an input boolean."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)
    id_manager = collection.IDManager()

    yaml_collection = collection.YamlCollection(
        logging.getLogger(f"{__name__}.yaml_collection"), id_manager)
    collection.attach_entity_component_collection(
        component, yaml_collection,
        lambda conf: InputBoolean(conf, from_yaml=True))

    storage_collection = InputBooleanStorageCollection(
        Store(hass, STORAGE_VERSION, STORAGE_KEY),
        logging.getLogger(f"{__name__}.storage_collection"),
        id_manager,
    )
    collection.attach_entity_component_collection(component,
                                                  storage_collection,
                                                  InputBoolean)

    await yaml_collection.async_load([{
        CONF_ID: id_,
        **(conf or {})
    } for id_, conf in config.get(DOMAIN, {}).items()])
    await storage_collection.async_load()

    collection.StorageCollectionWebsocket(storage_collection, DOMAIN, DOMAIN,
                                          CREATE_FIELDS,
                                          UPDATE_FIELDS).async_setup(hass)

    collection.attach_entity_registry_cleaner(hass, DOMAIN, DOMAIN,
                                              yaml_collection)
    collection.attach_entity_registry_cleaner(hass, DOMAIN, DOMAIN,
                                              storage_collection)

    async def reload_service_handler(service_call: ServiceCallType) -> None:
        """Remove all input booleans and load new ones from config."""
        conf = await component.async_prepare_reload(skip_reset=True)
        if conf is None:
            return
        await yaml_collection.async_load([{
            CONF_ID: id_,
            **(conf or {})
        } for id_, conf in conf.get(DOMAIN, {}).items()])

    homeassistant.helpers.service.async_register_admin_service(
        hass,
        DOMAIN,
        SERVICE_RELOAD,
        reload_service_handler,
        schema=RELOAD_SERVICE_SCHEMA,
    )

    component.async_register_entity_service(SERVICE_TURN_ON, {},
                                            "async_turn_on")

    component.async_register_entity_service(SERVICE_TURN_OFF, {},
                                            "async_turn_off")

    component.async_register_entity_service(SERVICE_TOGGLE, {}, "async_toggle")

    return True
Example #16
0
async def async_setup(hass, config):
    """Track states and offer events for covers."""
    component = EntityComponent(
        _LOGGER, DOMAIN, hass, SCAN_INTERVAL, GROUP_NAME_ALL_COVERS)

    await component.async_setup(config)

    component.async_register_entity_service(
        SERVICE_OPEN_COVER, COVER_SERVICE_SCHEMA,
        'async_open_cover'
    )

    component.async_register_entity_service(
        SERVICE_CLOSE_COVER, COVER_SERVICE_SCHEMA,
        'async_close_cover'
    )

    component.async_register_entity_service(
        SERVICE_SET_COVER_POSITION, COVER_SET_COVER_POSITION_SCHEMA,
        'async_set_cover_position'
    )

    component.async_register_entity_service(
        SERVICE_STOP_COVER, COVER_SERVICE_SCHEMA,
        'async_stop_cover'
    )

    component.async_register_entity_service(
        SERVICE_OPEN_COVER_TILT, COVER_SERVICE_SCHEMA,
        'async_open_cover_tilt'
    )

    component.async_register_entity_service(
        SERVICE_CLOSE_COVER_TILT, COVER_SERVICE_SCHEMA,
        'async_close_cover_tilt'
    )

    component.async_register_entity_service(
        SERVICE_STOP_COVER_TILT, COVER_SERVICE_SCHEMA,
        'async_stop_cover_tilt'
    )

    component.async_register_entity_service(
        SERVICE_SET_COVER_TILT_POSITION, COVER_SET_COVER_TILT_POSITION_SCHEMA,
        'async_set_cover_tilt_position'
    )

    hass.helpers.intent.async_register(intent.ServiceIntentHandler(
        INTENT_OPEN_COVER, DOMAIN, SERVICE_OPEN_COVER,
        "Opened {}"))
    hass.helpers.intent.async_register(intent.ServiceIntentHandler(
        INTENT_CLOSE_COVER, DOMAIN, SERVICE_CLOSE_COVER,
        "Closed {}"))

    return True
Example #17
0
async def async_setup(hass, config):
    """Set up the vacuum component."""
    component = EntityComponent(_LOGGER, DOMAIN, hass, SCAN_INTERVAL,
                                GROUP_NAME_ALL_VACUUMS)

    await component.async_setup(config)

    component.async_register_entity_service(SERVICE_TURN_ON,
                                            VACUUM_SERVICE_SCHEMA,
                                            'async_turn_on')
    component.async_register_entity_service(SERVICE_TURN_OFF,
                                            VACUUM_SERVICE_SCHEMA,
                                            'async_turn_off')
    component.async_register_entity_service(SERVICE_TOGGLE,
                                            VACUUM_SERVICE_SCHEMA,
                                            'async_toggle')
    component.async_register_entity_service(SERVICE_START_PAUSE,
                                            VACUUM_SERVICE_SCHEMA,
                                            'async_start_pause')
    component.async_register_entity_service(SERVICE_START,
                                            VACUUM_SERVICE_SCHEMA,
                                            'async_start')
    component.async_register_entity_service(SERVICE_PAUSE,
                                            VACUUM_SERVICE_SCHEMA,
                                            'async_pause')
    component.async_register_entity_service(SERVICE_RETURN_TO_BASE,
                                            VACUUM_SERVICE_SCHEMA,
                                            'async_return_to_base')
    component.async_register_entity_service(SERVICE_CLEAN_SPOT,
                                            VACUUM_SERVICE_SCHEMA,
                                            'async_clean_spot')
    component.async_register_entity_service(SERVICE_LOCATE,
                                            VACUUM_SERVICE_SCHEMA,
                                            'async_locate')
    component.async_register_entity_service(SERVICE_STOP,
                                            VACUUM_SERVICE_SCHEMA,
                                            'async_stop')
    component.async_register_entity_service(
        SERVICE_SET_FAN_SPEED, VACUUM_SET_FAN_SPEED_SERVICE_SCHEMA,
        'async_set_fan_speed')
    component.async_register_entity_service(
        SERVICE_SEND_COMMAND, VACUUM_SEND_COMMAND_SERVICE_SCHEMA,
        'async_send_command')

    return True
Example #18
0
async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
    """Set up an input datetime."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)
    id_manager = collection.IDManager()

    yaml_collection = collection.YamlCollection(
        logging.getLogger(f"{__name__}.yaml_collection"), id_manager)
    collection.sync_entity_lifecycle(hass, DOMAIN, DOMAIN, component,
                                     yaml_collection, InputDatetime.from_yaml)

    storage_collection = DateTimeStorageCollection(
        Store(hass, STORAGE_VERSION, STORAGE_KEY),
        logging.getLogger(f"{__name__}.storage_collection"),
        id_manager,
    )
    collection.sync_entity_lifecycle(hass, DOMAIN, DOMAIN, component,
                                     storage_collection, InputDatetime)

    await yaml_collection.async_load([{
        CONF_ID: id_,
        **cfg
    } for id_, cfg in config.get(DOMAIN, {}).items()])
    await storage_collection.async_load()

    collection.StorageCollectionWebsocket(storage_collection, DOMAIN, DOMAIN,
                                          CREATE_FIELDS,
                                          UPDATE_FIELDS).async_setup(hass)

    async def reload_service_handler(service_call: ServiceCallType) -> None:
        """Reload yaml entities."""
        conf = await component.async_prepare_reload(skip_reset=True)
        if conf is None:
            conf = {DOMAIN: {}}
        await yaml_collection.async_load([{
            CONF_ID: id_,
            **cfg
        } for id_, cfg in conf.get(DOMAIN, {}).items()])

    homeassistant.helpers.service.async_register_admin_service(
        hass,
        DOMAIN,
        SERVICE_RELOAD,
        reload_service_handler,
        schema=RELOAD_SERVICE_SCHEMA,
    )

    component.async_register_entity_service(
        "set_datetime",
        vol.All(
            vol.Schema(
                {
                    vol.Optional(ATTR_DATE): cv.date,
                    vol.Optional(ATTR_TIME): cv.time,
                    vol.Optional(ATTR_DATETIME): cv.datetime,
                    vol.Optional(ATTR_TIMESTAMP): vol.Coerce(float),
                },
                extra=vol.ALLOW_EXTRA,
            ),
            cv.has_at_least_one_key(ATTR_DATE, ATTR_TIME, ATTR_DATETIME,
                                    ATTR_TIMESTAMP),
            validate_set_datetime_attrs,
        ),
        "async_set_datetime",
    )

    return True
Example #19
0
async def async_setup(hass, config):
    """Set up an Utility Meter."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)
    hass.data[DATA_UTILITY] = {}
    register_services = False

    for meter, conf in config.get(DOMAIN).items():
        _LOGGER.debug("Setup %s.%s", DOMAIN, meter)

        hass.data[DATA_UTILITY][meter] = conf

        if not conf[CONF_TARIFFS]:
            # only one entity is required
            hass.async_create_task(
                discovery.async_load_platform(
                    hass,
                    SENSOR_DOMAIN,
                    DOMAIN,
                    [{CONF_METER: meter, CONF_NAME: meter}],
                    config,
                )
            )
        else:
            # create tariff selection
            await component.async_add_entities(
                [TariffSelect(meter, list(conf[CONF_TARIFFS]))]
            )
            hass.data[DATA_UTILITY][meter][CONF_TARIFF_ENTITY] = "{}.{}".format(
                DOMAIN, meter
            )

            # add one meter for each tariff
            tariff_confs = []
            for tariff in conf[CONF_TARIFFS]:
                tariff_confs.append(
                    {
                        CONF_METER: meter,
                        CONF_NAME: "{} {}".format(meter, tariff),
                        CONF_TARIFF: tariff,
                    }
                )
            hass.async_create_task(
                discovery.async_load_platform(
                    hass, SENSOR_DOMAIN, DOMAIN, tariff_confs, config
                )
            )
            register_services = True

    if register_services:
        component.async_register_entity_service(
            SERVICE_RESET, ENTITY_SERVICE_SCHEMA, "async_reset_meters"
        )

        component.async_register_entity_service(
            SERVICE_SELECT_TARIFF, SERVICE_SELECT_TARIFF_SCHEMA, "async_select_tariff"
        )

        component.async_register_entity_service(
            SERVICE_SELECT_NEXT_TARIFF, ENTITY_SERVICE_SCHEMA, "async_next_tariff"
        )

    return True
async def test_register_entity_service(hass):
    """Test not expanding a group."""
    entity = MockEntity(entity_id=f"{DOMAIN}.entity")
    calls = []

    @ha.callback
    def appender(**kwargs):
        calls.append(kwargs)

    entity.async_called_by_service = appender

    component = EntityComponent(_LOGGER, DOMAIN, hass)
    await component.async_add_entities([entity])

    component.async_register_entity_service("hello", {"some": str},
                                            "async_called_by_service")

    with pytest.raises(vol.Invalid):
        await hass.services.async_call(
            DOMAIN,
            "hello",
            {
                "entity_id": entity.entity_id,
                "invalid": "data"
            },
            blocking=True,
        )
        assert len(calls) == 0

    await hass.services.async_call(DOMAIN,
                                   "hello", {
                                       "entity_id": entity.entity_id,
                                       "some": "data"
                                   },
                                   blocking=True)
    assert len(calls) == 1
    assert calls[0] == {"some": "data"}

    await hass.services.async_call(DOMAIN,
                                   "hello", {
                                       "entity_id": ENTITY_MATCH_ALL,
                                       "some": "data"
                                   },
                                   blocking=True)
    assert len(calls) == 2
    assert calls[1] == {"some": "data"}

    await hass.services.async_call(DOMAIN,
                                   "hello", {
                                       "entity_id": ENTITY_MATCH_NONE,
                                       "some": "data"
                                   },
                                   blocking=True)
    assert len(calls) == 2

    await hass.services.async_call(DOMAIN,
                                   "hello", {
                                       "area_id": ENTITY_MATCH_NONE,
                                       "some": "data"
                                   },
                                   blocking=True)
    assert len(calls) == 2
Example #21
0
async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
    """Set up an input slider."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)
    id_manager = collection.IDManager()

    yaml_collection = collection.YamlCollection(
        logging.getLogger(f"{__name__}.yaml_collection"), id_manager)
    collection.attach_entity_component_collection(
        component, yaml_collection,
        lambda cfg: TemplateNumber.from_yaml(cfg, hass))

    storage_collection = NumberStorageCollection(
        Store(hass, STORAGE_VERSION, STORAGE_KEY),
        logging.getLogger(f"{__name__}.storage_collection"),
        id_manager,
    )
    collection.attach_entity_component_collection(component,
                                                  storage_collection,
                                                  TemplateNumber)

    await yaml_collection.async_load([{
        CONF_ID: id_,
        **(conf or {})
    } for id_, conf in config.get(DOMAIN, {}).items()])
    await storage_collection.async_load()

    collection.StorageCollectionWebsocket(storage_collection, DOMAIN, DOMAIN,
                                          CREATE_FIELDS,
                                          UPDATE_FIELDS).async_setup(hass)

    collection.attach_entity_registry_cleaner(hass, DOMAIN, DOMAIN,
                                              yaml_collection)
    collection.attach_entity_registry_cleaner(hass, DOMAIN, DOMAIN,
                                              storage_collection)

    async def reload_service_handler(service_call: ServiceCallType) -> None:
        """Reload yaml entities."""
        conf = await component.async_prepare_reload(skip_reset=True)
        if conf is None:
            conf = {DOMAIN: {}}
        await yaml_collection.async_load([{
            CONF_ID: id_,
            **conf
        } for id_, conf in conf.get(DOMAIN, {}).items()])

    homeassistant.helpers.service.async_register_admin_service(
        hass,
        DOMAIN,
        SERVICE_RELOAD,
        reload_service_handler,
        schema=RELOAD_SERVICE_SCHEMA,
    )

    component.async_register_entity_service(
        SERVICE_SET_VALUE,
        {vol.Required(ATTR_VALUE): vol.Coerce(float)},
        "async_set_value",
    )

    component.async_register_entity_service(SERVICE_INCREMENT, {},
                                            "async_increment")

    component.async_register_entity_service(SERVICE_DECREMENT, {},
                                            "async_decrement")

    # (Start) Template Number
    component.async_register_entity_service(
        SERVICE_SET_VALUE_NO_SCRIPT,
        {vol.Required(ATTR_VALUE): vol.Coerce(float)},
        "async_set_value_no_script",
    )
    # (End) Template Number

    return True
Example #22
0
async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
    """Set up an input select."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)
    id_manager = collection.IDManager()

    yaml_collection = collection.YamlCollection(
        logging.getLogger(f"{__name__}.yaml_collection"), id_manager)
    collection.attach_entity_component_collection(component, yaml_collection,
                                                  Timer.from_yaml)

    storage_collection = TimerStorageCollection(
        Store(hass, STORAGE_VERSION, STORAGE_KEY),
        logging.getLogger(f"{__name__}.storage_collection"),
        id_manager,
    )
    collection.attach_entity_component_collection(component,
                                                  storage_collection, Timer)

    await yaml_collection.async_load([{
        CONF_ID: id_,
        **cfg
    } for id_, cfg in config.get(DOMAIN, {}).items()])
    await storage_collection.async_load()

    collection.StorageCollectionWebsocket(storage_collection, DOMAIN, DOMAIN,
                                          CREATE_FIELDS,
                                          UPDATE_FIELDS).async_setup(hass)

    collection.attach_entity_registry_cleaner(hass, DOMAIN, DOMAIN,
                                              yaml_collection)
    collection.attach_entity_registry_cleaner(hass, DOMAIN, DOMAIN,
                                              storage_collection)

    async def reload_service_handler(service_call: ServiceCallType) -> None:
        """Reload yaml entities."""
        conf = await component.async_prepare_reload(skip_reset=True)
        if conf is None:
            conf = {DOMAIN: {}}
        await yaml_collection.async_load([{
            CONF_ID: id_,
            **cfg
        } for id_, cfg in conf.get(DOMAIN, {}).items()])

    homeassistant.helpers.service.async_register_admin_service(
        hass,
        DOMAIN,
        SERVICE_RELOAD,
        reload_service_handler,
        schema=RELOAD_SERVICE_SCHEMA,
    )
    component.async_register_entity_service(
        SERVICE_START,
        {
            vol.Optional(ATTR_DURATION, default=DEFAULT_DURATION):
            cv.time_period
        },
        "async_start",
    )
    component.async_register_entity_service(SERVICE_PAUSE, {}, "async_pause")
    component.async_register_entity_service(SERVICE_CANCEL, {}, "async_cancel")
    component.async_register_entity_service(SERVICE_FINISH, {}, "async_finish")

    return True
Example #23
0
async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
    """Set up an input select."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)
    id_manager = collection.IDManager()

    yaml_collection = collection.YamlCollection(
        logging.getLogger(f"{__name__}.yaml_collection"), id_manager)
    collection.sync_entity_lifecycle(hass, DOMAIN, DOMAIN, component,
                                     yaml_collection, InputSelect.from_yaml)

    storage_collection = InputSelectStorageCollection(
        Store(hass, STORAGE_VERSION, STORAGE_KEY),
        logging.getLogger(f"{__name__}.storage_collection"),
        id_manager,
    )
    collection.sync_entity_lifecycle(hass, DOMAIN, DOMAIN, component,
                                     storage_collection, InputSelect)

    await yaml_collection.async_load([{
        CONF_ID: id_,
        **cfg
    } for id_, cfg in config.get(DOMAIN, {}).items()])
    await storage_collection.async_load()

    collection.StorageCollectionWebsocket(storage_collection, DOMAIN, DOMAIN,
                                          CREATE_FIELDS,
                                          UPDATE_FIELDS).async_setup(hass)

    async def reload_service_handler(service_call: ServiceCallType) -> None:
        """Reload yaml entities."""
        conf = await component.async_prepare_reload(skip_reset=True)
        if conf is None:
            conf = {DOMAIN: {}}
        await yaml_collection.async_load([{
            CONF_ID: id_,
            **cfg
        } for id_, cfg in conf.get(DOMAIN, {}).items()])

    homeassistant.helpers.service.async_register_admin_service(
        hass,
        DOMAIN,
        SERVICE_RELOAD,
        reload_service_handler,
        schema=RELOAD_SERVICE_SCHEMA,
    )

    component.async_register_entity_service(
        SERVICE_SELECT_OPTION,
        {vol.Required(ATTR_OPTION): cv.string},
        "async_select_option",
    )

    component.async_register_entity_service(
        SERVICE_SELECT_NEXT,
        {vol.Optional(ATTR_CYCLE, default=True): bool},
        "async_next",
    )

    component.async_register_entity_service(
        SERVICE_SELECT_PREVIOUS,
        {vol.Optional(ATTR_CYCLE, default=True): bool},
        "async_previous",
    )

    component.async_register_entity_service(
        SERVICE_SELECT_FIRST,
        {},
        callback(lambda entity, call: entity.async_select_index(0)),
    )

    component.async_register_entity_service(
        SERVICE_SELECT_LAST,
        {},
        callback(lambda entity, call: entity.async_select_index(-1)),
    )

    component.async_register_entity_service(
        SERVICE_SET_OPTIONS,
        {
            vol.Required(ATTR_OPTIONS):
            vol.All(cv.ensure_list, vol.Length(min=1), [cv.string])
        },
        "async_set_options",
    )

    return True
Example #24
0
async def async_setup(hass, config):
    """Set up variables from config."""
    component = EntityComponent(_LOGGER, DOMAIN, hass)

    entities = []

    for object_id, cfg in config[DOMAIN].items():
        if not cfg:
            cfg = {}

        initial_value = cfg.get(CONF_INITIAL_VALUE)
        unit = cfg.get(ATTR_UNIT_OF_MEASUREMENT)
        restore = cfg.get(CONF_RESTORE, True)
        force_update = cfg.get(CONF_FORCE_UPDATE, False)
        friendly_name = cfg.get(ATTR_FRIENDLY_NAME, object_id)
        icon = cfg.get(CONF_ICON)
        entity_picture = cfg.get(ATTR_ENTITY_PICTURE)

        value_template = cfg.get(CONF_VALUE_TEMPLATE)
        friendly_name_template = cfg.get(CONF_FRIENDLY_NAME_TEMPLATE)
        icon_template = cfg.get(CONF_ICON_TEMPLATE)
        entity_picture_template = cfg.get(CONF_ENTITY_PICTURE_TEMPLATE)
        for template in (
                value_template,
                icon_template,
                entity_picture_template,
                friendly_name_template,
        ):
            if template is not None:
                template.hass = hass

        manual_entity_ids = cfg.get(CONF_TRACKED_ENTITY_ID)

        tracked_entity_ids = list()
        if manual_entity_ids is not None:
            tracked_entity_ids = list(set(manual_entity_ids))

        tracked_event_types = cfg.get(CONF_TRACKED_EVENT_TYPE)
        if tracked_event_types is not None:
            tracked_event_types = list(set(tracked_event_types))

        query = cfg.get(CONF_QUERY)
        column = cfg.get(CONF_COLUMN)

        session = hass.data[recorder.DATA_INSTANCE].get_session()

        entities.append(
            Variable(hass, object_id, initial_value, value_template, session,
                     query, column, unit, restore, force_update, friendly_name,
                     friendly_name_template, icon, icon_template,
                     entity_picture, entity_picture_template,
                     tracked_entity_ids, tracked_event_types))

    if not entities:
        return False

    component.async_register_entity_service(SERVICE_SET, SERVICE_SET_SCHEMA,
                                            'async_set')

    component.async_register_entity_service(SERVICE_UPDATE,
                                            SERVICE_UPDATE_SCHEMA,
                                            'async_force_update')

    await component.async_add_entities(entities)
    return True