Use collection helpers for input_boolean (#30514)

* Refactor input_boolean to use config dict for instantiation.

* Refactor input_boolean to use YamlCollection.

* Add storage collection to input_boolean.

* Update homeassistant/components/input_boolean/__init__.py

Co-Authored-By: Paulus Schoutsen <paulus@home-assistant.io>

* Doh.

* Address comments.

* Add editable device state attribute.

* Clean up entities from entity registry on removal.

Reload yaml from correct source.

* Add tests.

* Update homeassistant/components/input_boolean/__init__.py

Co-Authored-By: Paulus Schoutsen <paulus@home-assistant.io>

* Don't reset entity state on updates.

Co-authored-by: Paulus Schoutsen <paulus@home-assistant.io>
This commit is contained in:
Alexei ChetroiandPaulus Schoutsen authored and Paulus Schoutsen committed 2020-01-07 08:53:43 +01:00
1 parent 345cc244ed
commit 6740249bef
3 files changed
+215 -47

No files matched your search

@@ -1,10 +1,13 @@
"""Support to keep track of user controlled booleans for within automation."""
import logging
import typing
import voluptuous as vol
from homeassistant.const import (
ATTR_EDITABLE,
CONF_ICON,
CONF_ID,
CONF_NAME,
SERVICE_RELOAD,
SERVICE_TOGGLE,
@@ -12,11 +15,15 @@ from homeassistant.const import (
SERVICE_TURN_ON,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.helpers import collection, entity_registry
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import ToggleEntity
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
from homeassistant.loader import bind_hass
DOMAIN = "input_boolean"
@@ -27,23 +34,47 @@ _LOGGER = logging.getLogger(__name__)
CONF_INITIAL = "initial"
CREATE_FIELDS = {
vol.Required(CONF_NAME): vol.All(str, vol.Length(min=1)),
vol.Optional(CONF_INITIAL): cv.boolean,
vol.Optional(CONF_ICON): cv.icon,
}
UPDATE_FIELDS = {
vol.Optional(CONF_NAME): cv.string,
vol.Optional(CONF_INITIAL): cv.boolean,
vol.Optional(CONF_ICON): cv.icon,
}
CONFIG_SCHEMA = vol.Schema(
{
DOMAIN: cv.schema_with_slug_keys(
vol.Any(
{
vol.Optional(CONF_NAME): cv.string,
vol.Optional(CONF_INITIAL): cv.boolean,
vol.Optional(CONF_ICON): cv.icon,
},
None,
)
)
},
{DOMAIN: cv.schema_with_slug_keys(vol.Any(UPDATE_FIELDS, None))},
extra=vol.ALLOW_EXTRA,
)
RELOAD_SERVICE_SCHEMA = vol.Schema({})
STORAGE_KEY = DOMAIN
STORAGE_VERSION = 1
class InputBooleanStorageCollection(collection.StorageCollection):
"""Input boolean collection stored in storage."""
CREATE_SCHEMA = vol.Schema(CREATE_FIELDS)
UPDATE_SCHEMA = vol.Schema(UPDATE_FIELDS)
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 {**data, **update_data}
@bind_hass
@@ -52,20 +83,57 @@ def is_on(hass, entity_id):
return hass.states.is_state(entity_id, STATE_ON)
async def async_setup(hass, config):
async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
"""Set up an input boolean."""
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, lambda conf: InputBoolean(conf, from_yaml=True)
)
async def reload_service_handler(service_call):
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[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
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:
"""Remove all input booleans and load new ones from config."""
conf = await component.async_prepare_reload()
conf = await component.async_prepare_reload(skip_reset=True)
if conf is None:
return
new_entities = await _async_process_config(conf)
if new_entities:
await component.async_add_entities(new_entities)
await yaml_collection.async_load(
[{CONF_ID: id_, **(conf or {})} for id_, conf in conf[DOMAIN].items()]
)
homeassistant.helpers.service.async_register_admin_service(
hass,
@@ -81,38 +149,20 @@ async def async_setup(hass, config):
component.async_register_entity_service(SERVICE_TOGGLE, {}, "async_toggle")
if entities:
await component.async_add_entities(entities)
return True
async def _async_process_config(config):
"""Process config and create list of entities."""
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))
return entities
class InputBoolean(ToggleEntity, RestoreEntity):
"""Representation of a boolean input."""
def __init__(self, object_id, name, initial, icon):
def __init__(self, config: typing.Optional[dict], from_yaml: bool = False):
"""Initialize a boolean input."""
self.entity_id = ENTITY_ID_FORMAT.format(object_id)
self._name = name
self._state = initial
self._icon = icon
self._config = config
self._editable = True
self._state = config.get(CONF_INITIAL)
if from_yaml:
self._editable = False
self.entity_id = ENTITY_ID_FORMAT.format(self.unique_id)
@property
def should_poll(self):
@@ -122,18 +172,28 @@ class InputBoolean(ToggleEntity, RestoreEntity):
@property
def name(self):
"""Return name of the boolean input."""
return self._name
return self._config.get(CONF_NAME)
@property
def state_attributes(self):
"""Return the state attributes of the entity."""
return {ATTR_EDITABLE: self._editable}
@property
def icon(self):
"""Return the icon to be used for this entity."""
return self._icon
return self._config.get(CONF_ICON)
@property
def is_on(self):
"""Return true if entity is on."""
return self._state
@property
def unique_id(self):
"""Return a unique ID for the person."""
return self._config[CONF_ID]
async def async_added_to_hass(self):
"""Call when entity about to be added to hass."""
# If not None, we got an initial value.
@@ -153,3 +213,8 @@ class InputBoolean(ToggleEntity, RestoreEntity):
"""Turn the entity off."""
self._state = False
await self.async_update_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()