mirror of
https://github.com/home-assistant/core.git
synced 2026-12-06 13:45:55 -04:00
Move select entity classes to entity module (#186811)
This commit is contained in:
@@ -2,16 +2,11 @@
|
||||
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
from typing import Any, final, override
|
||||
|
||||
from propcache.api import cached_property
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import ATTR_OPTION, SERVICE_SELECT_OPTION
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.exceptions import ServiceValidationError
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import config_validation as cv
|
||||
from homeassistant.helpers.entity import Entity, EntityDescription
|
||||
from homeassistant.helpers.entity_component import EntityComponent
|
||||
from homeassistant.helpers.typing import ConfigType
|
||||
|
||||
@@ -26,6 +21,7 @@ from .const import (
|
||||
SERVICE_SELECT_PREVIOUS,
|
||||
SelectEntityCapabilityAttribute,
|
||||
)
|
||||
from .entity import SelectEntity, SelectEntityDescription
|
||||
from .services import async_setup_services
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
@@ -77,164 +73,3 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
"""Unload a config entry."""
|
||||
return await hass.data[DATA_COMPONENT].async_unload_entry(entry)
|
||||
|
||||
|
||||
class SelectEntityDescription(EntityDescription, frozen_or_thawed=True):
|
||||
"""A class that describes select entities."""
|
||||
|
||||
options: list[str] | None = None
|
||||
|
||||
|
||||
CACHED_PROPERTIES_WITH_ATTR_ = {
|
||||
"current_option",
|
||||
"options",
|
||||
}
|
||||
|
||||
|
||||
class SelectEntity(Entity, cached_properties=CACHED_PROPERTIES_WITH_ATTR_):
|
||||
"""Representation of a Select entity."""
|
||||
|
||||
_entity_component_unrecorded_attributes = frozenset(
|
||||
{SelectEntityCapabilityAttribute.OPTIONS}
|
||||
)
|
||||
|
||||
entity_description: SelectEntityDescription
|
||||
_attr_current_option: str | None = None
|
||||
_attr_options: list[str]
|
||||
_attr_state: None = None
|
||||
|
||||
@property
|
||||
@override
|
||||
def capability_attributes(self) -> dict[str, Any]:
|
||||
"""Return capability attributes."""
|
||||
return {
|
||||
SelectEntityCapabilityAttribute.OPTIONS: self.options,
|
||||
}
|
||||
|
||||
@property
|
||||
@final
|
||||
@override
|
||||
def state(self) -> str | None:
|
||||
"""Return the entity state."""
|
||||
current_option = self.current_option
|
||||
if current_option is None or current_option not in self.options:
|
||||
return None
|
||||
return current_option
|
||||
|
||||
@cached_property
|
||||
def options(self) -> list[str]:
|
||||
"""Return a set of selectable options."""
|
||||
if hasattr(self, "_attr_options"):
|
||||
return self._attr_options
|
||||
if (
|
||||
hasattr(self, "entity_description")
|
||||
and self.entity_description.options is not None
|
||||
):
|
||||
return self.entity_description.options
|
||||
raise AttributeError
|
||||
|
||||
@cached_property
|
||||
def current_option(self) -> str | None:
|
||||
"""Return the selected entity option to represent the entity state."""
|
||||
return self._attr_current_option
|
||||
|
||||
@final
|
||||
@callback
|
||||
def _options_or_raise(self) -> list[str]:
|
||||
"""Return the options, raise ServiceValidationError if there are none."""
|
||||
if not (options := self.options):
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="no_options",
|
||||
translation_placeholders={"entity_id": self.entity_id},
|
||||
)
|
||||
return options
|
||||
|
||||
@final
|
||||
@callback
|
||||
def _valid_option_or_raise(self, option: str) -> None:
|
||||
"""Raise ServiceValidationError on invalid option."""
|
||||
options = self.options
|
||||
if not options or option not in options:
|
||||
friendly_options: str = ", ".join(options or [])
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="not_valid_option",
|
||||
translation_placeholders={
|
||||
"entity_id": self.entity_id,
|
||||
"option": option,
|
||||
"options": friendly_options,
|
||||
},
|
||||
)
|
||||
|
||||
@final
|
||||
async def async_handle_select_option(self, option: str) -> None:
|
||||
"""Service call wrapper to set a new value."""
|
||||
self._valid_option_or_raise(option)
|
||||
await self.async_select_option(option)
|
||||
|
||||
def select_option(self, option: str) -> None:
|
||||
"""Change the selected option."""
|
||||
raise NotImplementedError
|
||||
|
||||
async def async_select_option(self, option: str) -> None:
|
||||
"""Change the selected option."""
|
||||
await self.hass.async_add_executor_job(self.select_option, option)
|
||||
|
||||
@final
|
||||
async def async_first(self) -> None:
|
||||
"""Select first option."""
|
||||
await self._async_select_index(0)
|
||||
|
||||
@final
|
||||
async def async_last(self) -> None:
|
||||
"""Select last option."""
|
||||
await self._async_select_index(-1)
|
||||
|
||||
@final
|
||||
async def async_next(self, cycle: bool) -> None:
|
||||
"""Select next option.
|
||||
|
||||
If there is no current option, first item is the next.
|
||||
"""
|
||||
if self.current_option is None:
|
||||
await self.async_first()
|
||||
return
|
||||
await self._async_offset_index(1, cycle)
|
||||
|
||||
@final
|
||||
async def async_previous(self, cycle: bool) -> None:
|
||||
"""Select previous option.
|
||||
|
||||
If there is no current option, last item is the previous.
|
||||
"""
|
||||
if self.current_option is None:
|
||||
await self.async_last()
|
||||
return
|
||||
await self._async_offset_index(-1, cycle)
|
||||
|
||||
@final
|
||||
async def _async_offset_index(self, offset: int, cycle: bool) -> None:
|
||||
"""Offset current index."""
|
||||
current_index = 0
|
||||
current_option = self.current_option
|
||||
options = self._options_or_raise()
|
||||
if current_option is not None and current_option in options:
|
||||
current_index = options.index(current_option)
|
||||
|
||||
new_index = current_index + offset
|
||||
if cycle:
|
||||
new_index = new_index % len(options)
|
||||
elif new_index < 0:
|
||||
new_index = 0
|
||||
elif new_index >= len(options):
|
||||
new_index = len(options) - 1
|
||||
|
||||
await self.async_select_option(options[new_index])
|
||||
|
||||
@final
|
||||
async def _async_select_index(self, idx: int) -> None:
|
||||
"""Select new option by index."""
|
||||
options = self._options_or_raise()
|
||||
new_index = idx % len(options)
|
||||
await self.async_select_option(options[new_index])
|
||||
|
||||
@@ -8,7 +8,7 @@ from homeassistant.util.hass_dict import HassKey
|
||||
if TYPE_CHECKING:
|
||||
from homeassistant.helpers.entity_component import EntityComponent
|
||||
|
||||
from . import SelectEntity
|
||||
from .entity import SelectEntity
|
||||
|
||||
DOMAIN: Final = "select"
|
||||
DATA_COMPONENT: HassKey[EntityComponent[SelectEntity]] = HassKey(DOMAIN)
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
"""Base entity for the Select platform."""
|
||||
|
||||
from typing import Any, final, override
|
||||
|
||||
from propcache.api import cached_property
|
||||
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.exceptions import ServiceValidationError
|
||||
from homeassistant.helpers.entity import Entity, EntityDescription
|
||||
|
||||
from .const import DOMAIN, SelectEntityCapabilityAttribute
|
||||
|
||||
|
||||
class SelectEntityDescription(EntityDescription, frozen_or_thawed=True):
|
||||
"""A class that describes select entities."""
|
||||
|
||||
options: list[str] | None = None
|
||||
|
||||
|
||||
CACHED_PROPERTIES_WITH_ATTR_ = {
|
||||
"current_option",
|
||||
"options",
|
||||
}
|
||||
|
||||
|
||||
class SelectEntity(Entity, cached_properties=CACHED_PROPERTIES_WITH_ATTR_):
|
||||
"""Representation of a Select entity."""
|
||||
|
||||
_entity_component_unrecorded_attributes = frozenset(
|
||||
{SelectEntityCapabilityAttribute.OPTIONS}
|
||||
)
|
||||
|
||||
entity_description: SelectEntityDescription
|
||||
_attr_current_option: str | None = None
|
||||
_attr_options: list[str]
|
||||
_attr_state: None = None
|
||||
|
||||
@property
|
||||
@override
|
||||
def capability_attributes(self) -> dict[str, Any]:
|
||||
"""Return capability attributes."""
|
||||
return {
|
||||
SelectEntityCapabilityAttribute.OPTIONS: self.options,
|
||||
}
|
||||
|
||||
@property
|
||||
@final
|
||||
@override
|
||||
def state(self) -> str | None:
|
||||
"""Return the entity state."""
|
||||
current_option = self.current_option
|
||||
if current_option is None or current_option not in self.options:
|
||||
return None
|
||||
return current_option
|
||||
|
||||
@cached_property
|
||||
def options(self) -> list[str]:
|
||||
"""Return a set of selectable options."""
|
||||
if hasattr(self, "_attr_options"):
|
||||
return self._attr_options
|
||||
if (
|
||||
hasattr(self, "entity_description")
|
||||
and self.entity_description.options is not None
|
||||
):
|
||||
return self.entity_description.options
|
||||
raise AttributeError
|
||||
|
||||
@cached_property
|
||||
def current_option(self) -> str | None:
|
||||
"""Return the selected entity option to represent the entity state."""
|
||||
return self._attr_current_option
|
||||
|
||||
@final
|
||||
@callback
|
||||
def _options_or_raise(self) -> list[str]:
|
||||
"""Return the options, raise ServiceValidationError if there are none."""
|
||||
if not (options := self.options):
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="no_options",
|
||||
translation_placeholders={"entity_id": self.entity_id},
|
||||
)
|
||||
return options
|
||||
|
||||
@final
|
||||
@callback
|
||||
def _valid_option_or_raise(self, option: str) -> None:
|
||||
"""Raise ServiceValidationError on invalid option."""
|
||||
options = self.options
|
||||
if not options or option not in options:
|
||||
friendly_options: str = ", ".join(options or [])
|
||||
raise ServiceValidationError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="not_valid_option",
|
||||
translation_placeholders={
|
||||
"entity_id": self.entity_id,
|
||||
"option": option,
|
||||
"options": friendly_options,
|
||||
},
|
||||
)
|
||||
|
||||
@final
|
||||
async def async_handle_select_option(self, option: str) -> None:
|
||||
"""Service call wrapper to set a new value."""
|
||||
self._valid_option_or_raise(option)
|
||||
await self.async_select_option(option)
|
||||
|
||||
def select_option(self, option: str) -> None:
|
||||
"""Change the selected option."""
|
||||
raise NotImplementedError
|
||||
|
||||
async def async_select_option(self, option: str) -> None:
|
||||
"""Change the selected option."""
|
||||
await self.hass.async_add_executor_job(self.select_option, option)
|
||||
|
||||
@final
|
||||
async def async_first(self) -> None:
|
||||
"""Select first option."""
|
||||
await self._async_select_index(0)
|
||||
|
||||
@final
|
||||
async def async_last(self) -> None:
|
||||
"""Select last option."""
|
||||
await self._async_select_index(-1)
|
||||
|
||||
@final
|
||||
async def async_next(self, cycle: bool) -> None:
|
||||
"""Select next option.
|
||||
|
||||
If there is no current option, first item is the next.
|
||||
"""
|
||||
if self.current_option is None:
|
||||
await self.async_first()
|
||||
return
|
||||
await self._async_offset_index(1, cycle)
|
||||
|
||||
@final
|
||||
async def async_previous(self, cycle: bool) -> None:
|
||||
"""Select previous option.
|
||||
|
||||
If there is no current option, last item is the previous.
|
||||
"""
|
||||
if self.current_option is None:
|
||||
await self.async_last()
|
||||
return
|
||||
await self._async_offset_index(-1, cycle)
|
||||
|
||||
@final
|
||||
async def _async_offset_index(self, offset: int, cycle: bool) -> None:
|
||||
"""Offset current index."""
|
||||
current_index = 0
|
||||
current_option = self.current_option
|
||||
options = self._options_or_raise()
|
||||
if current_option is not None and current_option in options:
|
||||
current_index = options.index(current_option)
|
||||
|
||||
new_index = current_index + offset
|
||||
if cycle:
|
||||
new_index = new_index % len(options)
|
||||
elif new_index < 0:
|
||||
new_index = 0
|
||||
elif new_index >= len(options):
|
||||
new_index = len(options) - 1
|
||||
|
||||
await self.async_select_option(options[new_index])
|
||||
|
||||
@final
|
||||
async def _async_select_index(self, idx: int) -> None:
|
||||
"""Select new option by index."""
|
||||
options = self._options_or_raise()
|
||||
new_index = idx % len(options)
|
||||
await self.async_select_option(options[new_index])
|
||||
Reference in New Issue
Block a user