Use storage collections for input_select entity management (#30604)
* Refactor input_select to use _config dict. * Use collections for input_select. * Add tests. * Move async_setup to top. * Cleanup. * async_write_ha_state() * Update homeassistant/components/input_select/__init__.py Co-Authored-By: Paulus Schoutsen <paulus@home-assistant.io>
This commit is contained in:
1 parent
e793ed9ab0
commit
7d506bc38b
3 files changed
+322
-43
No files matched your search
@@ -1,13 +1,24 @@
|
||||
"""Support to select an option from a list."""
|
||||
import logging
|
||||
import typing
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.const import CONF_ICON, CONF_NAME, SERVICE_RELOAD
|
||||
from homeassistant.const import (
|
||||
ATTR_EDITABLE,
|
||||
CONF_ICON,
|
||||
CONF_ID,
|
||||
CONF_NAME,
|
||||
SERVICE_RELOAD,
|
||||
)
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.helpers import collection, entity_registry
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.helpers.entity_component import EntityComponent
|
||||
from homeassistant.helpers.restore_state import RestoreEntity
|
||||
import homeassistant.helpers.service
|
||||
from homeassistant.helpers.storage import Store
|
||||
from homeassistant.helpers.typing import ConfigType, HomeAssistantType, ServiceCallType
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -21,13 +32,24 @@ ATTR_OPTION = "option"
|
||||
ATTR_OPTIONS = "options"
|
||||
|
||||
SERVICE_SELECT_OPTION = "select_option"
|
||||
|
||||
|
||||
SERVICE_SELECT_NEXT = "select_next"
|
||||
|
||||
SERVICE_SELECT_PREVIOUS = "select_previous"
|
||||
|
||||
SERVICE_SET_OPTIONS = "set_options"
|
||||
STORAGE_KEY = DOMAIN
|
||||
STORAGE_VERSION = 1
|
||||
|
||||
CREATE_FIELDS = {
|
||||
vol.Required(CONF_NAME): vol.All(str, vol.Length(min=1)),
|
||||
vol.Required(CONF_OPTIONS): vol.All(cv.ensure_list, vol.Length(min=1), [cv.string]),
|
||||
vol.Optional(CONF_INITIAL): cv.string,
|
||||
vol.Optional(CONF_ICON): cv.icon,
|
||||
}
|
||||
UPDATE_FIELDS = {
|
||||
vol.Optional(CONF_NAME): cv.string,
|
||||
vol.Optional(CONF_OPTIONS): vol.All(cv.ensure_list, vol.Length(min=1), [cv.string]),
|
||||
vol.Optional(CONF_INITIAL): cv.string,
|
||||
vol.Optional(CONF_ICON): cv.icon,
|
||||
}
|
||||
|
||||
|
||||
def _cv_input_select(cfg):
|
||||
@@ -65,20 +87,57 @@ CONFIG_SCHEMA = vol.Schema(
|
||||
RELOAD_SERVICE_SCHEMA = vol.Schema({})
|
||||
|
||||
|
||||
async def async_setup(hass, config):
|
||||
async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
|
||||
"""Set up an input select."""
|
||||
component = EntityComponent(_LOGGER, DOMAIN, hass)
|
||||
id_manager = collection.IDManager()
|
||||
|
||||
entities = await _async_process_config(config)
|
||||
yaml_collection = collection.YamlCollection(
|
||||
logging.getLogger(f"{__name__}.yaml_collection"), id_manager
|
||||
)
|
||||
collection.attach_entity_component_collection(
|
||||
component, yaml_collection, InputSelect.from_yaml
|
||||
)
|
||||
|
||||
async def reload_service_handler(service_call):
|
||||
"""Remove all entities and load new ones from config."""
|
||||
conf = await component.async_prepare_reload()
|
||||
if conf is None:
|
||||
storage_collection = InputSelectStorageCollection(
|
||||
Store(hass, STORAGE_VERSION, STORAGE_KEY),
|
||||
logging.getLogger(f"{__name__}.storage_collection"),
|
||||
id_manager,
|
||||
)
|
||||
collection.attach_entity_component_collection(
|
||||
component, storage_collection, InputSelect
|
||||
)
|
||||
|
||||
await yaml_collection.async_load(
|
||||
[{CONF_ID: id_, **cfg} for id_, cfg in config[DOMAIN].items()]
|
||||
)
|
||||
await storage_collection.async_load()
|
||||
|
||||
collection.StorageCollectionWebsocket(
|
||||
storage_collection, DOMAIN, DOMAIN, CREATE_FIELDS, UPDATE_FIELDS
|
||||
).async_setup(hass)
|
||||
|
||||
async def _collection_changed(
|
||||
change_type: str, item_id: str, config: typing.Optional[typing.Dict]
|
||||
) -> None:
|
||||
"""Handle a collection change: clean up entity registry on removals."""
|
||||
if change_type != collection.CHANGE_REMOVED:
|
||||
return
|
||||
new_entities = await _async_process_config(conf)
|
||||
if new_entities:
|
||||
await component.async_add_entities(new_entities)
|
||||
|
||||
ent_reg = await entity_registry.async_get_registry(hass)
|
||||
ent_reg.async_remove(ent_reg.async_get_entity_id(DOMAIN, DOMAIN, item_id))
|
||||
|
||||
yaml_collection.async_add_listener(_collection_changed)
|
||||
storage_collection.async_add_listener(_collection_changed)
|
||||
|
||||
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[DOMAIN].items()]
|
||||
)
|
||||
|
||||
homeassistant.helpers.service.async_register_admin_service(
|
||||
hass,
|
||||
@@ -95,11 +154,11 @@ async def async_setup(hass, config):
|
||||
)
|
||||
|
||||
component.async_register_entity_service(
|
||||
SERVICE_SELECT_NEXT, {}, lambda entity, call: entity.async_offset_index(1),
|
||||
SERVICE_SELECT_NEXT, {}, lambda entity, call: entity.async_offset_index(1)
|
||||
)
|
||||
|
||||
component.async_register_entity_service(
|
||||
SERVICE_SELECT_PREVIOUS, {}, lambda entity, call: entity.async_offset_index(-1),
|
||||
SERVICE_SELECT_PREVIOUS, {}, lambda entity, call: entity.async_offset_index(-1)
|
||||
)
|
||||
|
||||
component.async_register_entity_service(
|
||||
@@ -112,35 +171,46 @@ async def async_setup(hass, config):
|
||||
"async_set_options",
|
||||
)
|
||||
|
||||
if entities:
|
||||
await component.async_add_entities(entities)
|
||||
return True
|
||||
|
||||
|
||||
async def _async_process_config(config):
|
||||
"""Process config and create list of entities."""
|
||||
entities = []
|
||||
class InputSelectStorageCollection(collection.StorageCollection):
|
||||
"""Input storage based collection."""
|
||||
|
||||
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))
|
||||
CREATE_SCHEMA = vol.Schema(vol.All(CREATE_FIELDS, _cv_input_select))
|
||||
UPDATE_SCHEMA = vol.Schema(UPDATE_FIELDS)
|
||||
|
||||
return entities
|
||||
async def _process_create_data(self, data: typing.Dict) -> typing.Dict:
|
||||
"""Validate the config is valid."""
|
||||
return self.CREATE_SCHEMA(data)
|
||||
|
||||
@callback
|
||||
def _get_suggested_id(self, info: typing.Dict) -> str:
|
||||
"""Suggest an ID based on the config."""
|
||||
return info[CONF_NAME]
|
||||
|
||||
async def _update_data(self, data: dict, update_data: typing.Dict) -> typing.Dict:
|
||||
"""Return a new updated data object."""
|
||||
update_data = self.UPDATE_SCHEMA(update_data)
|
||||
return _cv_input_select({**data, **update_data})
|
||||
|
||||
|
||||
class InputSelect(RestoreEntity):
|
||||
"""Representation of a select input."""
|
||||
|
||||
def __init__(self, object_id, name, initial, options, icon):
|
||||
def __init__(self, config: typing.Dict):
|
||||
"""Initialize a select input."""
|
||||
self.entity_id = ENTITY_ID_FORMAT.format(object_id)
|
||||
self._name = name
|
||||
self._current_option = initial
|
||||
self._options = options
|
||||
self._icon = icon
|
||||
self._config = config
|
||||
self.editable = True
|
||||
self._current_option = config.get(CONF_INITIAL)
|
||||
|
||||
@classmethod
|
||||
def from_yaml(cls, config: typing.Dict) -> "InputSelect":
|
||||
"""Return entity instance initialized from yaml storage."""
|
||||
input_select = cls(config)
|
||||
input_select.entity_id = ENTITY_ID_FORMAT.format(config[CONF_ID])
|
||||
input_select.editable = False
|
||||
return input_select
|
||||
|
||||
async def async_added_to_hass(self):
|
||||
"""Run when entity about to be added."""
|
||||
@@ -162,12 +232,17 @@ class InputSelect(RestoreEntity):
|
||||
@property
|
||||
def name(self):
|
||||
"""Return the name of the select input."""
|
||||
return self._name
|
||||
return self._config.get(CONF_NAME)
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""Return the icon to be used for this entity."""
|
||||
return self._icon
|
||||
return self._config.get(CONF_ICON)
|
||||
|
||||
@property
|
||||
def _options(self) -> typing.List[str]:
|
||||
"""Return a list of selection options."""
|
||||
return self._config[CONF_OPTIONS]
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
@@ -177,7 +252,12 @@ class InputSelect(RestoreEntity):
|
||||
@property
|
||||
def state_attributes(self):
|
||||
"""Return the state attributes."""
|
||||
return {ATTR_OPTIONS: self._options}
|
||||
return {ATTR_OPTIONS: self._config[ATTR_OPTIONS], ATTR_EDITABLE: self.editable}
|
||||
|
||||
@property
|
||||
def unique_id(self) -> typing.Optional[str]:
|
||||
"""Return unique id for the entity."""
|
||||
return self._config[CONF_ID]
|
||||
|
||||
async def async_select_option(self, option):
|
||||
"""Select new option."""
|
||||
@@ -189,17 +269,22 @@ class InputSelect(RestoreEntity):
|
||||
)
|
||||
return
|
||||
self._current_option = option
|
||||
await self.async_update_ha_state()
|
||||
self.async_write_ha_state()
|
||||
|
||||
async def async_offset_index(self, offset):
|
||||
"""Offset current index."""
|
||||
current_index = self._options.index(self._current_option)
|
||||
new_index = (current_index + offset) % len(self._options)
|
||||
self._current_option = self._options[new_index]
|
||||
await self.async_update_ha_state()
|
||||
self.async_write_ha_state()
|
||||
|
||||
async def async_set_options(self, options):
|
||||
"""Set options."""
|
||||
self._current_option = options[0]
|
||||
self._options = options
|
||||
await self.async_update_ha_state()
|
||||
self._config[CONF_OPTIONS] = options
|
||||
self.async_write_ha_state()
|
||||
|
||||
async def async_update_config(self, config: typing.Dict) -> None:
|
||||
"""Handle when the config is updated."""
|
||||
self._config = config
|
||||
self.async_write_ha_state()
|
||||
Reference in new issue
Block a user