Migrate template switch to new style (#140324)

* Migrate template switch to new style

* update tests

* Update tests

* Add config flow migration

* comment fixes

* revert entity config migration
This commit is contained in:
Petro31 2025-03-20 10:12:43 -04:00 committed by GitHub
parent 5f84fc3ee5
commit 212d39ba19
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 798 additions and 470 deletions

View File

@ -17,6 +17,7 @@ from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN
from homeassistant.components.number import DOMAIN as NUMBER_DOMAIN
from homeassistant.components.select import DOMAIN as SELECT_DOMAIN
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.components.weather import DOMAIN as WEATHER_DOMAIN
from homeassistant.config import async_log_schema_error, config_without_domain
from homeassistant.const import (
@ -41,6 +42,7 @@ from . import (
number as number_platform,
select as select_platform,
sensor as sensor_platform,
switch as switch_platform,
weather as weather_platform,
)
from .const import (
@ -112,8 +114,13 @@ CONFIG_SECTION_SCHEMA = vol.Schema(
vol.Optional(WEATHER_DOMAIN): vol.All(
cv.ensure_list, [weather_platform.WEATHER_SCHEMA]
),
vol.Optional(SWITCH_DOMAIN): vol.All(
cv.ensure_list, [switch_platform.SWITCH_SCHEMA]
),
},
ensure_domains_do_not_have_trigger_or_action(BUTTON_DOMAIN, LIGHT_DOMAIN),
ensure_domains_do_not_have_trigger_or_action(
BUTTON_DOMAIN, LIGHT_DOMAIN, SWITCH_DOMAIN
),
)
)

View File

@ -17,6 +17,7 @@ from homeassistant.const import (
ATTR_FRIENDLY_NAME,
CONF_DEVICE_ID,
CONF_NAME,
CONF_STATE,
CONF_SWITCHES,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
@ -25,7 +26,7 @@ from homeassistant.const import (
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import TemplateError
from homeassistant.helpers import config_validation as cv, selector
from homeassistant.helpers import config_validation as cv, selector, template
from homeassistant.helpers.device import async_device_info_to_link_from_device_id
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.entity_platform import (
@ -35,16 +36,41 @@ from homeassistant.helpers.entity_platform import (
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from .const import CONF_TURN_OFF, CONF_TURN_ON, DOMAIN
from .const import CONF_OBJECT_ID, CONF_PICTURE, CONF_TURN_OFF, CONF_TURN_ON, DOMAIN
from .template_entity import (
LEGACY_FIELDS as TEMPLATE_ENTITY_LEGACY_FIELDS,
TEMPLATE_ENTITY_AVAILABILITY_SCHEMA,
TEMPLATE_ENTITY_COMMON_SCHEMA_LEGACY,
TEMPLATE_ENTITY_ICON_SCHEMA,
TemplateEntity,
rewrite_common_legacy_to_modern_conf,
)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
SWITCH_SCHEMA = vol.All(
LEGACY_FIELDS = TEMPLATE_ENTITY_LEGACY_FIELDS | {
CONF_VALUE_TEMPLATE: CONF_STATE,
}
DEFAULT_NAME = "Template Switch"
SWITCH_SCHEMA = (
vol.Schema(
{
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.template,
vol.Optional(CONF_STATE): cv.template,
vol.Required(CONF_TURN_ON): cv.SCRIPT_SCHEMA,
vol.Required(CONF_TURN_OFF): cv.SCRIPT_SCHEMA,
vol.Optional(CONF_UNIQUE_ID): cv.string,
vol.Optional(CONF_PICTURE): cv.template,
}
)
.extend(TEMPLATE_ENTITY_AVAILABILITY_SCHEMA.schema)
.extend(TEMPLATE_ENTITY_ICON_SCHEMA.schema)
)
LEGACY_SWITCH_SCHEMA = vol.All(
cv.deprecated(ATTR_ENTITY_ID),
vol.Schema(
{
@ -59,13 +85,13 @@ SWITCH_SCHEMA = vol.All(
)
PLATFORM_SCHEMA = SWITCH_PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(LEGACY_SWITCH_SCHEMA)}
)
SWITCH_CONFIG_SCHEMA = vol.Schema(
{
vol.Required(CONF_NAME): cv.template,
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_STATE): cv.template,
vol.Optional(CONF_TURN_ON): cv.SCRIPT_SCHEMA,
vol.Optional(CONF_TURN_OFF): cv.SCRIPT_SCHEMA,
vol.Optional(CONF_DEVICE_ID): selector.DeviceSelector(),
@ -73,24 +99,62 @@ SWITCH_CONFIG_SCHEMA = vol.Schema(
)
async def _async_create_entities(hass: HomeAssistant, config: ConfigType):
"""Create the Template switches."""
def rewrite_legacy_to_modern_conf(
hass: HomeAssistant, config: dict[str, dict]
) -> list[dict]:
"""Rewrite legacy switch configuration definitions to modern ones."""
switches = []
for object_id, entity_config in config[CONF_SWITCHES].items():
entity_config = rewrite_common_legacy_to_modern_conf(hass, entity_config)
unique_id = entity_config.get(CONF_UNIQUE_ID)
for object_id, entity_conf in config.items():
entity_conf = {**entity_conf, CONF_OBJECT_ID: object_id}
entity_conf = rewrite_common_legacy_to_modern_conf(
hass, entity_conf, LEGACY_FIELDS
)
if CONF_NAME not in entity_conf:
entity_conf[CONF_NAME] = template.Template(object_id, hass)
switches.append(entity_conf)
return switches
def rewrite_options_to_moder_conf(option_config: dict[str, dict]) -> dict[str, dict]:
"""Rewrite option configuration to modern configuration."""
option_config = {**option_config}
if CONF_VALUE_TEMPLATE in option_config:
option_config[CONF_STATE] = option_config.pop(CONF_VALUE_TEMPLATE)
return option_config
@callback
def _async_create_template_tracking_entities(
async_add_entities: AddEntitiesCallback,
hass: HomeAssistant,
definitions: list[dict],
unique_id_prefix: str | None,
) -> None:
"""Create the template switches."""
switches = []
for entity_conf in definitions:
unique_id = entity_conf.get(CONF_UNIQUE_ID)
if unique_id and unique_id_prefix:
unique_id = f"{unique_id_prefix}-{unique_id}"
switches.append(
SwitchTemplate(
hass,
object_id,
entity_config,
entity_conf,
unique_id,
)
)
return switches
async_add_entities(switches)
async def async_setup_platform(
@ -100,7 +164,21 @@ async def async_setup_platform(
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the template switches."""
async_add_entities(await _async_create_entities(hass, config))
if discovery_info is None:
_async_create_template_tracking_entities(
async_add_entities,
hass,
rewrite_legacy_to_modern_conf(hass, config[CONF_SWITCHES]),
None,
)
return
_async_create_template_tracking_entities(
async_add_entities,
hass,
discovery_info["entities"],
discovery_info["unique_id"],
)
async def async_setup_entry(
@ -111,10 +189,9 @@ async def async_setup_entry(
"""Initialize config entry."""
_options = dict(config_entry.options)
_options.pop("template_type")
_options = rewrite_options_to_moder_conf(_options)
validated_config = SWITCH_CONFIG_SCHEMA(_options)
async_add_entities(
[SwitchTemplate(hass, None, validated_config, config_entry.entry_id)]
)
async_add_entities([SwitchTemplate(hass, validated_config, config_entry.entry_id)])
@callback
@ -123,7 +200,7 @@ def async_create_preview_switch(
) -> SwitchTemplate:
"""Create a preview switch."""
validated_config = SWITCH_CONFIG_SCHEMA(config | {CONF_NAME: name})
return SwitchTemplate(hass, None, validated_config, None)
return SwitchTemplate(hass, validated_config, None)
class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
@ -134,22 +211,19 @@ class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
def __init__(
self,
hass: HomeAssistant,
object_id,
config: ConfigType,
unique_id,
unique_id: str | None,
) -> None:
"""Initialize the Template switch."""
super().__init__(
hass, config=config, fallback_name=object_id, unique_id=unique_id
)
if object_id is not None:
super().__init__(hass, config=config, fallback_name=None, unique_id=unique_id)
if (object_id := config.get(CONF_OBJECT_ID)) is not None:
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, object_id, hass=hass
)
name = self._attr_name
if TYPE_CHECKING:
assert name is not None
self._template = config.get(CONF_VALUE_TEMPLATE)
self._template = config.get(CONF_STATE)
if on_action := config.get(CONF_TURN_ON):
self.add_script(CONF_TURN_ON, on_action, name, DOMAIN)

View File

@ -1,5 +1,18 @@
# serializer version: 1
# name: test_setup_config_entry
# name: test_setup_config_entry[state]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'My template',
}),
'context': <ANY>,
'entity_id': 'switch.my_template',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
})
# ---
# name: test_setup_config_entry[value_template]
StateSnapshot({
'attributes': ReadOnlyDict({
'friendly_name': 'My template',

View File

@ -16,6 +16,36 @@ from homeassistant.helpers import device_registry as dr
from tests.common import MockConfigEntry
from tests.typing import WebSocketGenerator
SWITCH_BEFORE_OPTIONS = {
"name": "test_template_switch",
"template_type": "switch",
"turn_off": [{"event": "test_template_switch", "event_data": {"event": "off"}}],
"turn_on": [{"event": "test_template_switch", "event_data": {"event": "on"}}],
"value_template": "{{ now().minute % 2 == 0 }}",
}
SWITCH_AFTER_OPTIONS = {
"name": "test_template_switch",
"template_type": "switch",
"turn_off": [{"event": "test_template_switch", "event_data": {"event": "off"}}],
"turn_on": [{"event": "test_template_switch", "event_data": {"event": "on"}}],
"state": "{{ now().minute % 2 == 0 }}",
"value_template": "{{ now().minute % 2 == 0 }}",
}
SENSOR_OPTIONS = {
"name": "test_template_sensor",
"template_type": "sensor",
"state": "{{ 'a' if now().minute % 2 == 0 else 'b' }}",
}
BINARY_SENSOR_OPTIONS = {
"name": "test_template_sensor",
"template_type": "binary_sensor",
"state": "{{ now().minute % 2 == 0 else }}",
}
@pytest.mark.parametrize(
(

File diff suppressed because it is too large Load Diff