Add config flow to template cover platform (#149433)

This commit is contained in:
Petro31 2025-07-30 08:48:24 -04:00 committed by GitHub
parent 749fc318ca
commit 6c2a662838
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
7 changed files with 303 additions and 17 deletions

View File

@ -11,6 +11,7 @@ import voluptuous as vol
from homeassistant.components import websocket_api
from homeassistant.components.binary_sensor import BinarySensorDeviceClass
from homeassistant.components.button import ButtonDeviceClass
from homeassistant.components.cover import CoverDeviceClass
from homeassistant.components.sensor import (
CONF_STATE_CLASS,
DEVICE_CLASS_STATE_CLASSES,
@ -62,6 +63,15 @@ from .const import (
CONF_TURN_ON,
DOMAIN,
)
from .cover import (
CLOSE_ACTION,
CONF_OPEN_AND_CLOSE,
CONF_POSITION,
OPEN_ACTION,
POSITION_ACTION,
STOP_ACTION,
async_create_preview_cover,
)
from .number import (
CONF_MAX,
CONF_MIN,
@ -143,6 +153,26 @@ def generate_schema(domain: str, flow_type: str) -> vol.Schema:
)
}
if domain == Platform.COVER:
schema |= _SCHEMA_STATE | {
vol.Inclusive(OPEN_ACTION, CONF_OPEN_AND_CLOSE): selector.ActionSelector(),
vol.Inclusive(CLOSE_ACTION, CONF_OPEN_AND_CLOSE): selector.ActionSelector(),
vol.Optional(STOP_ACTION): selector.ActionSelector(),
vol.Optional(CONF_POSITION): selector.TemplateSelector(),
vol.Optional(POSITION_ACTION): selector.ActionSelector(),
}
if flow_type == "config":
schema |= {
vol.Optional(CONF_DEVICE_CLASS): selector.SelectSelector(
selector.SelectSelectorConfig(
options=[cls.value for cls in CoverDeviceClass],
mode=selector.SelectSelectorMode.DROPDOWN,
translation_key="cover_device_class",
sort=True,
),
)
}
if domain == Platform.IMAGE:
schema |= {
vol.Required(CONF_URL): selector.TemplateSelector(),
@ -327,6 +357,7 @@ TEMPLATE_TYPES = [
Platform.ALARM_CONTROL_PANEL,
Platform.BINARY_SENSOR,
Platform.BUTTON,
Platform.COVER,
Platform.IMAGE,
Platform.NUMBER,
Platform.SELECT,
@ -350,6 +381,11 @@ CONFIG_FLOW = {
config_schema(Platform.BUTTON),
validate_user_input=validate_user_input(Platform.BUTTON),
),
Platform.COVER: SchemaFlowFormStep(
config_schema(Platform.COVER),
preview="template",
validate_user_input=validate_user_input(Platform.COVER),
),
Platform.IMAGE: SchemaFlowFormStep(
config_schema(Platform.IMAGE),
preview="template",
@ -394,6 +430,11 @@ OPTIONS_FLOW = {
options_schema(Platform.BUTTON),
validate_user_input=validate_user_input(Platform.BUTTON),
),
Platform.COVER: SchemaFlowFormStep(
options_schema(Platform.COVER),
preview="template",
validate_user_input=validate_user_input(Platform.COVER),
),
Platform.IMAGE: SchemaFlowFormStep(
options_schema(Platform.IMAGE),
preview="template",
@ -427,6 +468,7 @@ CREATE_PREVIEW_ENTITY: dict[
] = {
Platform.ALARM_CONTROL_PANEL: async_create_preview_alarm_control_panel,
Platform.BINARY_SENSOR: async_create_preview_binary_sensor,
Platform.COVER: async_create_preview_cover,
Platform.NUMBER: async_create_preview_number,
Platform.SELECT: async_create_preview_select,
Platform.SENSOR: async_create_preview_sensor,

View File

@ -18,6 +18,7 @@ from homeassistant.components.cover import (
CoverEntity,
CoverEntityFeature,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_COVERS,
CONF_DEVICE_CLASS,
@ -31,14 +32,22 @@ from homeassistant.const import (
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import TemplateError
from homeassistant.helpers import config_validation as cv, template
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.entity_platform import (
AddConfigEntryEntitiesCallback,
AddEntitiesCallback,
)
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from . import TriggerUpdateCoordinator
from .const import DOMAIN
from .entity import AbstractTemplateEntity
from .helpers import async_setup_template_platform
from .helpers import (
async_setup_template_entry,
async_setup_template_platform,
async_setup_template_preview,
)
from .template_entity import (
TEMPLATE_ENTITY_COMMON_CONFIG_ENTRY_SCHEMA,
TEMPLATE_ENTITY_COMMON_SCHEMA_LEGACY,
TEMPLATE_ENTITY_OPTIMISTIC_SCHEMA,
TemplateEntity,
@ -91,23 +100,29 @@ LEGACY_FIELDS = {
DEFAULT_NAME = "Template Cover"
COVER_COMMON_SCHEMA = vol.Schema(
{
vol.Inclusive(CLOSE_ACTION, CONF_OPEN_AND_CLOSE): cv.SCRIPT_SCHEMA,
vol.Inclusive(OPEN_ACTION, CONF_OPEN_AND_CLOSE): cv.SCRIPT_SCHEMA,
vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
vol.Optional(CONF_POSITION): cv.template,
vol.Optional(CONF_STATE): cv.template,
vol.Optional(CONF_TILT): cv.template,
vol.Optional(POSITION_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(STOP_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(TILT_ACTION): cv.SCRIPT_SCHEMA,
}
)
COVER_YAML_SCHEMA = vol.All(
vol.Schema(
{
vol.Inclusive(CLOSE_ACTION, CONF_OPEN_AND_CLOSE): cv.SCRIPT_SCHEMA,
vol.Inclusive(OPEN_ACTION, CONF_OPEN_AND_CLOSE): cv.SCRIPT_SCHEMA,
vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA,
vol.Optional(CONF_POSITION): cv.template,
vol.Optional(CONF_STATE): cv.template,
vol.Optional(CONF_TILT_OPTIMISTIC): cv.boolean,
vol.Optional(CONF_TILT): cv.template,
vol.Optional(POSITION_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(STOP_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(TILT_ACTION): cv.SCRIPT_SCHEMA,
}
)
.extend(make_template_entity_common_modern_schema(DEFAULT_NAME).schema)
.extend(TEMPLATE_ENTITY_OPTIMISTIC_SCHEMA),
.extend(COVER_COMMON_SCHEMA.schema)
.extend(TEMPLATE_ENTITY_OPTIMISTIC_SCHEMA)
.extend(make_template_entity_common_modern_schema(DEFAULT_NAME).schema),
cv.has_at_least_one_key(OPEN_ACTION, POSITION_ACTION),
)
@ -139,6 +154,11 @@ PLATFORM_SCHEMA = COVER_PLATFORM_SCHEMA.extend(
{vol.Required(CONF_COVERS): cv.schema_with_slug_keys(COVER_LEGACY_YAML_SCHEMA)}
)
COVER_CONFIG_ENTRY_SCHEMA = vol.All(
COVER_COMMON_SCHEMA.extend(TEMPLATE_ENTITY_COMMON_CONFIG_ENTRY_SCHEMA.schema),
cv.has_at_least_one_key(OPEN_ACTION, POSITION_ACTION),
)
async def async_setup_platform(
hass: HomeAssistant,
@ -160,6 +180,37 @@ async def async_setup_platform(
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Initialize config entry."""
await async_setup_template_entry(
hass,
config_entry,
async_add_entities,
StateCoverEntity,
COVER_CONFIG_ENTRY_SCHEMA,
True,
)
@callback
def async_create_preview_cover(
hass: HomeAssistant, name: str, config: dict[str, Any]
) -> StateCoverEntity:
"""Create a preview."""
return async_setup_template_preview(
hass,
name,
config,
StateCoverEntity,
COVER_CONFIG_ENTRY_SCHEMA,
True,
)
class AbstractTemplateCover(AbstractTemplateEntity, CoverEntity):
"""Representation of a template cover features."""

View File

@ -242,7 +242,7 @@ async def async_setup_template_entry(
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
state_entity_cls: type[TemplateEntity],
config_schema: vol.Schema,
config_schema: vol.Schema | vol.All,
replace_value_template: bool = False,
) -> None:
"""Setup the Template from a config entry."""
@ -267,7 +267,7 @@ def async_setup_template_preview[T: TemplateEntity](
name: str,
config: ConfigType,
state_entity_cls: type[T],
schema: vol.Schema,
schema: vol.Schema | vol.All,
replace_value_template: bool = False,
) -> T:
"""Setup the Template preview."""

View File

@ -80,6 +80,37 @@
},
"title": "Template button"
},
"cover": {
"data": {
"device_id": "[%key:common::config_flow::data::device%]",
"device_class": "[%key:component::template::common::device_class%]",
"name": "[%key:common::config_flow::data::name%]",
"state": "[%key:component::template::common::state%]",
"open_cover": "Actions on open",
"close_cover": "Actions on close",
"stop_cover": "Actions on stop",
"position": "Position",
"set_cover_position": "Actions on set position"
},
"data_description": {
"device_id": "[%key:component::template::common::device_id_description%]",
"state": "Defines a template to get the state of the cover. Valid output values from the template are `open`, `opening`, `closing` and `closed` which are directly mapped to the corresponding states. If both a state and a position are specified, only `opening` and `closing` are set from the state template.",
"open_cover": "Defines actions to run when the cover is opened.",
"close_cover": "Defines actions to run when the cover is closed.",
"stop_cover": "Defines actions to run when the cover is stopped.",
"position": "Defines a template to get the position of the cover. Value values are numbers between `0` (`closed`) and `100` (`open`).",
"set_cover_position": "Defines actions to run when the cover is given a `set_cover_position` command."
},
"sections": {
"advanced_options": {
"name": "[%key:component::template::common::advanced_options%]",
"data": {
"availability": "[%key:component::template::common::availability%]"
}
}
},
"title": "Template cover"
},
"image": {
"data": {
"device_id": "[%key:common::config_flow::data::device%]",
@ -173,6 +204,7 @@
"alarm_control_panel": "Template an alarm control panel",
"binary_sensor": "Template a binary sensor",
"button": "Template a button",
"cover": "Template a cover",
"image": "Template an image",
"number": "Template a number",
"select": "Template a select",
@ -270,6 +302,36 @@
},
"title": "[%key:component::template::config::step::button::title%]"
},
"cover": {
"data": {
"device_id": "[%key:common::config_flow::data::device%]",
"state": "[%key:component::template::common::state%]",
"open_cover": "[%key:component::template::config::step::cover::data::open_cover%]",
"close_cover": "[%key:component::template::config::step::cover::data::close_cover%]",
"stop_cover": "[%key:component::template::config::step::cover::data::stop_cover%]",
"position": "[%key:component::template::config::step::cover::data::position%]",
"set_cover_position": "[%key:component::template::config::step::cover::data::set_cover_position%]"
},
"data_description": {
"device_id": "[%key:component::template::common::device_id_description%]",
"state": "[%key:component::template::config::step::cover::data_description::state%]",
"open_cover": "[%key:component::template::config::step::cover::data_description::open_cover%]",
"close_cover": "[%key:component::template::config::step::cover::data_description::close_cover%]",
"stop_cover": "[%key:component::template::config::step::cover::data_description::stop_cover%]",
"position": "[%key:component::template::config::step::cover::data_description::position%]",
"set_cover_position": "[%key:component::template::config::step::cover::data_description::set_cover_position%]"
},
"sections": {
"advanced_options": {
"name": "[%key:component::template::common::advanced_options%]",
"data": {
"availability": "[%key:component::template::common::availability%]"
}
}
},
"title": "[%key:component::template::config::step::cover::title%]"
},
"image": {
"data": {
"device_id": "[%key:common::config_flow::data::device%]",
@ -425,6 +487,20 @@
"update": "[%key:component::button::entity_component::update::name%]"
}
},
"cover_device_class": {
"options": {
"awning": "[%key:component::cover::entity_component::awning::name%]",
"blind": "[%key:component::cover::entity_component::blind::name%]",
"curtain": "[%key:component::cover::entity_component::curtain::name%]",
"damper": "[%key:component::cover::entity_component::damper::name%]",
"door": "[%key:component::cover::entity_component::door::name%]",
"garage": "[%key:component::cover::entity_component::garage::name%]",
"gate": "[%key:component::cover::entity_component::gate::name%]",
"shade": "[%key:component::cover::entity_component::shade::name%]",
"shutter": "[%key:component::cover::entity_component::shutter::name%]",
"window": "[%key:component::cover::entity_component::window::name%]"
}
},
"sensor_device_class": {
"options": {
"apparent_power": "[%key:component::sensor::entity_component::apparent_power::name%]",

View File

@ -0,0 +1,16 @@
# serializer version: 1
# name: test_setup_config_entry
StateSnapshot({
'attributes': ReadOnlyDict({
'current_position': 100,
'friendly_name': 'My template',
'supported_features': <CoverEntityFeature: 7>,
}),
'context': <ANY>,
'entity_id': 'cover.my_template',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'open',
})
# ---

View File

@ -121,6 +121,34 @@ BINARY_SENSOR_OPTIONS = {
},
{},
),
(
"cover",
{"state": "{{ states('cover.one') }}"},
"open",
{"one": "open", "two": "closed"},
{},
{
"device_class": "garage",
"set_cover_position": [
{
"action": "input_number.set_value",
"target": {"entity_id": "input_number.test"},
"data": {"position": "{{ position }}"},
}
],
},
{
"device_class": "garage",
"set_cover_position": [
{
"action": "input_number.set_value",
"target": {"entity_id": "input_number.test"},
"data": {"position": "{{ position }}"},
}
],
},
{},
),
(
"image",
{"url": "{{ states('sensor.one') }}"},
@ -288,6 +316,12 @@ async def test_config_flow(
{},
{},
),
(
"cover",
{"state": "{{ 'open' }}"},
{"set_cover_position": []},
{"set_cover_position": []},
),
(
"image",
{
@ -474,6 +508,16 @@ async def test_config_flow_device(
},
"state",
),
(
"cover",
{"state": "{{ states('cover.one') }}"},
{"state": "{{ states('cover.two') }}"},
["open", "closed"],
{"one": "open", "two": "closed"},
{"set_cover_position": []},
{"set_cover_position": []},
"state",
),
(
"image",
{
@ -1315,6 +1359,12 @@ async def test_option_flow_sensor_preview_config_entry_removed(
{},
{},
),
(
"cover",
{"state": "{{ states('cover.one') }}"},
{"set_cover_position": []},
{"set_cover_position": []},
),
(
"image",
{

View File

@ -3,6 +3,7 @@
from typing import Any
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components import cover, template
from homeassistant.components.cover import (
@ -32,9 +33,10 @@ from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
from .conftest import ConfigurationStyle
from .conftest import ConfigurationStyle, async_get_flow_preview_state
from tests.common import assert_setup_component
from tests.common import MockConfigEntry, assert_setup_component
from tests.typing import WebSocketGenerator
TEST_OBJECT_ID = "test_template_cover"
TEST_ENTITY_ID = f"cover.{TEST_OBJECT_ID}"
@ -1604,3 +1606,52 @@ async def test_empty_action_config(
state.attributes["supported_features"]
== CoverEntityFeature.OPEN | CoverEntityFeature.CLOSE | supported_feature
)
async def test_setup_config_entry(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
) -> None:
"""Tests creating a cover from a config entry."""
hass.states.async_set(
"cover.test_state",
"open",
{},
)
template_config_entry = MockConfigEntry(
data={},
domain=template.DOMAIN,
options={
"name": "My template",
"state": "{{ states('cover.test_state') }}",
"set_cover_position": [],
"template_type": COVER_DOMAIN,
},
title="My template",
)
template_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(template_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("cover.my_template")
assert state is not None
assert state == snapshot
async def test_flow_preview(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test the config flow preview."""
state = await async_get_flow_preview_state(
hass,
hass_ws_client,
cover.DOMAIN,
{"name": "My template", "state": "{{ 'open' }}", "set_cover_position": []},
)
assert state["state"] == CoverState.OPEN