core/homeassistant/components/script/__init__.py

366 lines
11 KiB
Python
Raw Normal View History

"""Support for scripts."""
import asyncio
import logging
from typing import List
import voluptuous as vol
2016-02-19 05:27:50 +00:00
from homeassistant.const import (
2019-07-31 19:25:30 +00:00
ATTR_ENTITY_ID,
ATTR_NAME,
CONF_ALIAS,
2020-02-17 16:44:36 +00:00
CONF_ICON,
CONF_MODE,
CONF_QUEUE_SIZE,
SERVICE_RELOAD,
SERVICE_TOGGLE,
2019-07-31 19:25:30 +00:00
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_ON,
)
from homeassistant.core import HomeAssistant, callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.config_validation import make_entity_service_schema
from homeassistant.helpers.entity import ToggleEntity
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.script import (
SCRIPT_BASE_SCHEMA,
SCRIPT_MODE_LEGACY,
Script,
validate_queue_size,
warn_deprecated_legacy,
)
from homeassistant.helpers.service import async_set_service_schema
from homeassistant.loader import bind_hass
2016-04-21 22:52:20 +00:00
_LOGGER = logging.getLogger(__name__)
2015-10-15 06:09:52 +00:00
2019-07-31 19:25:30 +00:00
DOMAIN = "script"
ATTR_CAN_CANCEL = "can_cancel"
ATTR_LAST_ACTION = "last_action"
ATTR_LAST_TRIGGERED = "last_triggered"
ATTR_VARIABLES = "variables"
CONF_DESCRIPTION = "description"
CONF_EXAMPLE = "example"
CONF_FIELDS = "fields"
2019-07-31 19:25:30 +00:00
CONF_SEQUENCE = "sequence"
2019-07-31 19:25:30 +00:00
ENTITY_ID_FORMAT = DOMAIN + ".{}"
EVENT_SCRIPT_STARTED = "script_started"
def _deprecated_legacy_mode(config):
legacy_scripts = []
for object_id, cfg in config.items():
mode = cfg.get(CONF_MODE)
if mode is None:
legacy_scripts.append(object_id)
cfg[CONF_MODE] = SCRIPT_MODE_LEGACY
if legacy_scripts:
warn_deprecated_legacy(_LOGGER, f"script(s): {', '.join(legacy_scripts)}")
return config
SCRIPT_ENTRY_SCHEMA = vol.All(
SCRIPT_BASE_SCHEMA.extend(
{
vol.Optional(CONF_ALIAS): cv.string,
vol.Optional(CONF_ICON): cv.icon,
vol.Required(CONF_SEQUENCE): cv.SCRIPT_SCHEMA,
vol.Optional(CONF_DESCRIPTION, default=""): cv.string,
vol.Optional(CONF_FIELDS, default={}): {
cv.string: {
vol.Optional(CONF_DESCRIPTION): cv.string,
vol.Optional(CONF_EXAMPLE): cv.string,
}
},
}
),
validate_queue_size,
2019-07-31 19:25:30 +00:00
)
2019-07-31 19:25:30 +00:00
CONFIG_SCHEMA = vol.Schema(
{
DOMAIN: vol.All(
cv.schema_with_slug_keys(SCRIPT_ENTRY_SCHEMA), _deprecated_legacy_mode
)
},
extra=vol.ALLOW_EXTRA,
2019-07-31 19:25:30 +00:00
)
SCRIPT_SERVICE_SCHEMA = vol.Schema(dict)
SCRIPT_TURN_ONOFF_SCHEMA = make_entity_service_schema(
2019-07-31 19:25:30 +00:00
{vol.Optional(ATTR_VARIABLES): dict}
)
RELOAD_SERVICE_SCHEMA = vol.Schema({})
@bind_hass
2015-10-15 06:09:52 +00:00
def is_on(hass, entity_id):
"""Return if the script is on based on the statemachine."""
2015-10-15 06:09:52 +00:00
return hass.states.is_state(entity_id, STATE_ON)
@callback
def scripts_with_entity(hass: HomeAssistant, entity_id: str) -> List[str]:
"""Return all scripts that reference the entity."""
if DOMAIN not in hass.data:
return []
component = hass.data[DOMAIN]
return [
script_entity.entity_id
for script_entity in component.entities
if entity_id in script_entity.script.referenced_entities
]
@callback
def entities_in_script(hass: HomeAssistant, entity_id: str) -> List[str]:
"""Return all entities in script."""
if DOMAIN not in hass.data:
return []
component = hass.data[DOMAIN]
script_entity = component.get_entity(entity_id)
if script_entity is None:
return []
return list(script_entity.script.referenced_entities)
@callback
def scripts_with_device(hass: HomeAssistant, device_id: str) -> List[str]:
"""Return all scripts that reference the device."""
if DOMAIN not in hass.data:
return []
component = hass.data[DOMAIN]
return [
script_entity.entity_id
for script_entity in component.entities
if device_id in script_entity.script.referenced_devices
]
@callback
def devices_in_script(hass: HomeAssistant, entity_id: str) -> List[str]:
"""Return all devices in script."""
if DOMAIN not in hass.data:
return []
component = hass.data[DOMAIN]
script_entity = component.get_entity(entity_id)
if script_entity is None:
return []
return list(script_entity.script.referenced_devices)
async def async_setup(hass, config):
2016-03-07 17:49:31 +00:00
"""Load the scripts from the configuration."""
hass.data[DOMAIN] = component = EntityComponent(_LOGGER, DOMAIN, hass)
await _async_process_config(hass, config, component)
2015-10-15 06:09:52 +00:00
async def reload_service(service):
"""Call a service to reload scripts."""
conf = await component.async_prepare_reload()
if conf is None:
return
2015-10-15 06:09:52 +00:00
await _async_process_config(hass, conf, component)
2015-10-15 06:09:52 +00:00
async def turn_on_service(service):
2016-03-08 16:55:57 +00:00
"""Call a service to turn script on."""
variables = service.data.get(ATTR_VARIABLES)
for script_entity in await component.async_extract_from_service(service):
if script_entity.script.is_legacy:
await hass.services.async_call(
DOMAIN, script_entity.object_id, variables, context=service.context
)
else:
await script_entity.async_turn_on(
variables=variables, context=service.context, wait=False
)
2015-10-15 06:09:52 +00:00
async def turn_off_service(service):
2016-03-08 16:55:57 +00:00
"""Cancel a script."""
# Stopping a script is ok to be done in parallel
scripts = await component.async_extract_from_service(service)
if not scripts:
return
2019-07-31 19:25:30 +00:00
await asyncio.wait([script.async_turn_off() for script in scripts])
async def toggle_service(service):
2016-03-08 16:55:57 +00:00
"""Toggle a script."""
for script_entity in await component.async_extract_from_service(service):
await script_entity.async_toggle(context=service.context)
2019-07-31 19:25:30 +00:00
hass.services.async_register(
DOMAIN, SERVICE_RELOAD, reload_service, schema=RELOAD_SERVICE_SCHEMA
)
hass.services.async_register(
DOMAIN, SERVICE_TURN_ON, turn_on_service, schema=SCRIPT_TURN_ONOFF_SCHEMA
)
hass.services.async_register(
DOMAIN, SERVICE_TURN_OFF, turn_off_service, schema=SCRIPT_TURN_ONOFF_SCHEMA
)
hass.services.async_register(
DOMAIN, SERVICE_TOGGLE, toggle_service, schema=SCRIPT_TURN_ONOFF_SCHEMA
)
return True
async def _async_process_config(hass, config, component):
"""Process script configuration."""
2019-07-31 19:25:30 +00:00
async def service_handler(service):
"""Execute a service call to script.<script name>."""
entity_id = ENTITY_ID_FORMAT.format(service.service)
script_entity = component.get_entity(entity_id)
if script_entity.script.is_legacy and script_entity.is_on:
_LOGGER.warning("Script %s already running", entity_id)
return
await script_entity.async_turn_on(
variables=service.data, context=service.context
)
script_entities = []
for object_id, cfg in config.get(DOMAIN, {}).items():
script_entities.append(
2020-02-17 16:44:36 +00:00
ScriptEntity(
hass,
object_id,
cfg.get(CONF_ALIAS, object_id),
cfg.get(CONF_ICON),
cfg[CONF_SEQUENCE],
cfg[CONF_MODE],
cfg.get(CONF_QUEUE_SIZE, 0),
2020-02-17 16:44:36 +00:00
)
)
await component.async_add_entities(script_entities)
# Register services for all entities that were created successfully.
for script_entity in script_entities:
object_id = script_entity.object_id
if component.get_entity(script_entity.entity_id) is None:
_LOGGER.error("Couldn't load script %s", object_id)
continue
cfg = config[DOMAIN][object_id]
hass.services.async_register(
2019-07-31 19:25:30 +00:00
DOMAIN, object_id, service_handler, schema=SCRIPT_SERVICE_SCHEMA
)
# Register the service description
service_desc = {
CONF_DESCRIPTION: cfg[CONF_DESCRIPTION],
CONF_FIELDS: cfg[CONF_FIELDS],
}
async_set_service_schema(hass, DOMAIN, object_id, service_desc)
2016-04-21 22:52:20 +00:00
class ScriptEntity(ToggleEntity):
"""Representation of a script entity."""
2016-03-08 16:55:57 +00:00
2020-02-17 16:44:36 +00:00
icon = None
def __init__(self, hass, object_id, name, icon, sequence, mode, queue_size):
2016-03-08 16:55:57 +00:00
"""Initialize the script."""
self.object_id = object_id
2020-02-17 16:44:36 +00:00
self.icon = icon
2015-10-28 19:24:33 +00:00
self.entity_id = ENTITY_ID_FORMAT.format(object_id)
Add support for simultaneous runs of Script helper (#31937) * Add tests for legacy Script helper behavior * Add Script helper if_running and run_mode options - if_running controls what happens if Script run while previous run has not completed. Can be: - error: Raise an exception - ignore: Return without doing anything (previous run continues as-is) - parallel: Start run in new task - restart: Stop previous run before starting new run - run_mode controls when call to async_run will return. Can be: - background: Returns immediately - legacy: Implements previous behavior, which is to return when done, or when suspended by delay or wait_template - blocking: Returns when run has completed - If neither is specified, default is run_mode=legacy (and if_running is not used.) Otherwise, defaults are if_running=parallel and run_mode=background. If run_mode is set to legacy then if_running must be None. - Caller may supply a logger which will be used throughout instead of default module logger. - Move Script running state into new helper classes, comprised of an abstract base class and two concrete clases, one for legacy behavior and one for new behavior. - Remove some non-async methods, as well as call_from_config which has only been used in tests. - Adjust tests accordingly. * Change per review - Change run_mode default from background to blocking. - Make sure change listener is called, even when there's an unexpected exception. - Make _ScriptRun.async_stop more graceful by using an asyncio.Event for signaling instead of simply cancelling Task. - Subclass _ScriptRun for background & blocking behavior. Also: - Fix timeouts in _ScriptRun by converting timedeltas to float seconds. - General cleanup. * Change per review 2 - Don't propagate exceptions if call from user has already returned (i.e., for background runs or legacy runs that have suspended.) - Allow user to specify if exceptions should be logged. They will still be logged regardless if exception is not propagated. - Rename _start_script_delay and _start_wait_template_delay for clarity. - Remove return value from Script.async_run. - Fix missing await. - Change call to self.is_running in Script.async_run to direct test of self._runs. * Change per review 3 and add tests - Remove Script.set_logger(). - Enhance existing tests to check all run modes. - Add tests for new features. - Fix a few minor bugs found by tests.
2020-02-24 22:56:00 +00:00
self.script = Script(
hass,
sequence,
name,
self.async_change_listener,
mode,
queue_size,
logging.getLogger(f"{__name__}.{object_id}"),
Add support for simultaneous runs of Script helper (#31937) * Add tests for legacy Script helper behavior * Add Script helper if_running and run_mode options - if_running controls what happens if Script run while previous run has not completed. Can be: - error: Raise an exception - ignore: Return without doing anything (previous run continues as-is) - parallel: Start run in new task - restart: Stop previous run before starting new run - run_mode controls when call to async_run will return. Can be: - background: Returns immediately - legacy: Implements previous behavior, which is to return when done, or when suspended by delay or wait_template - blocking: Returns when run has completed - If neither is specified, default is run_mode=legacy (and if_running is not used.) Otherwise, defaults are if_running=parallel and run_mode=background. If run_mode is set to legacy then if_running must be None. - Caller may supply a logger which will be used throughout instead of default module logger. - Move Script running state into new helper classes, comprised of an abstract base class and two concrete clases, one for legacy behavior and one for new behavior. - Remove some non-async methods, as well as call_from_config which has only been used in tests. - Adjust tests accordingly. * Change per review - Change run_mode default from background to blocking. - Make sure change listener is called, even when there's an unexpected exception. - Make _ScriptRun.async_stop more graceful by using an asyncio.Event for signaling instead of simply cancelling Task. - Subclass _ScriptRun for background & blocking behavior. Also: - Fix timeouts in _ScriptRun by converting timedeltas to float seconds. - General cleanup. * Change per review 2 - Don't propagate exceptions if call from user has already returned (i.e., for background runs or legacy runs that have suspended.) - Allow user to specify if exceptions should be logged. They will still be logged regardless if exception is not propagated. - Rename _start_script_delay and _start_wait_template_delay for clarity. - Remove return value from Script.async_run. - Fix missing await. - Change call to self.is_running in Script.async_run to direct test of self._runs. * Change per review 3 and add tests - Remove Script.set_logger(). - Enhance existing tests to check all run modes. - Add tests for new features. - Fix a few minor bugs found by tests.
2020-02-24 22:56:00 +00:00
)
self._changed = asyncio.Event()
2015-10-15 06:09:52 +00:00
@property
def should_poll(self):
2016-03-07 17:49:31 +00:00
"""No polling needed."""
2015-10-15 06:09:52 +00:00
return False
@property
def name(self):
2016-03-07 17:49:31 +00:00
"""Return the name of the entity."""
2016-04-21 22:52:20 +00:00
return self.script.name
2015-10-15 06:09:52 +00:00
@property
def state_attributes(self):
2016-03-07 17:49:31 +00:00
"""Return the state attributes."""
attrs = {ATTR_LAST_TRIGGERED: self.script.last_triggered}
2016-04-21 22:52:20 +00:00
if self.script.can_cancel:
attrs[ATTR_CAN_CANCEL] = self.script.can_cancel
if self.script.last_action:
attrs[ATTR_LAST_ACTION] = self.script.last_action
2015-10-15 06:09:52 +00:00
return attrs
@property
def is_on(self):
2016-03-08 16:55:57 +00:00
"""Return true if script is on."""
2016-04-21 22:52:20 +00:00
return self.script.is_running
2015-10-15 06:09:52 +00:00
@callback
def async_change_listener(self):
"""Update state."""
self.async_write_ha_state()
self._changed.set()
async def async_turn_on(self, **kwargs):
"""Turn the script on."""
variables = kwargs.get("variables")
2019-07-31 19:25:30 +00:00
context = kwargs.get("context")
wait = kwargs.get("wait", True)
self.async_set_context(context)
2019-07-31 19:25:30 +00:00
self.hass.bus.async_fire(
EVENT_SCRIPT_STARTED,
{ATTR_NAME: self.script.name, ATTR_ENTITY_ID: self.entity_id},
context=context,
)
coro = self.script.async_run(variables, context)
if wait:
await coro
return
# Caller does not want to wait for called script to finish so let script run in
# separate Task. However, wait for first state change so we can guarantee that
# it is written to the State Machine before we return. Only do this for
# non-legacy scripts, since legacy scripts don't necessarily change state
# immediately.
self._changed.clear()
self.hass.async_create_task(coro)
if not self.script.is_legacy:
await self._changed.wait()
2015-10-15 06:09:52 +00:00
async def async_turn_off(self, **kwargs):
2016-03-07 17:49:31 +00:00
"""Turn script off."""
Add support for simultaneous runs of Script helper (#31937) * Add tests for legacy Script helper behavior * Add Script helper if_running and run_mode options - if_running controls what happens if Script run while previous run has not completed. Can be: - error: Raise an exception - ignore: Return without doing anything (previous run continues as-is) - parallel: Start run in new task - restart: Stop previous run before starting new run - run_mode controls when call to async_run will return. Can be: - background: Returns immediately - legacy: Implements previous behavior, which is to return when done, or when suspended by delay or wait_template - blocking: Returns when run has completed - If neither is specified, default is run_mode=legacy (and if_running is not used.) Otherwise, defaults are if_running=parallel and run_mode=background. If run_mode is set to legacy then if_running must be None. - Caller may supply a logger which will be used throughout instead of default module logger. - Move Script running state into new helper classes, comprised of an abstract base class and two concrete clases, one for legacy behavior and one for new behavior. - Remove some non-async methods, as well as call_from_config which has only been used in tests. - Adjust tests accordingly. * Change per review - Change run_mode default from background to blocking. - Make sure change listener is called, even when there's an unexpected exception. - Make _ScriptRun.async_stop more graceful by using an asyncio.Event for signaling instead of simply cancelling Task. - Subclass _ScriptRun for background & blocking behavior. Also: - Fix timeouts in _ScriptRun by converting timedeltas to float seconds. - General cleanup. * Change per review 2 - Don't propagate exceptions if call from user has already returned (i.e., for background runs or legacy runs that have suspended.) - Allow user to specify if exceptions should be logged. They will still be logged regardless if exception is not propagated. - Rename _start_script_delay and _start_wait_template_delay for clarity. - Remove return value from Script.async_run. - Fix missing await. - Change call to self.is_running in Script.async_run to direct test of self._runs. * Change per review 3 and add tests - Remove Script.set_logger(). - Enhance existing tests to check all run modes. - Add tests for new features. - Fix a few minor bugs found by tests.
2020-02-24 22:56:00 +00:00
await self.script.async_stop()
async def async_will_remove_from_hass(self):
"""Stop script and remove service when it will be removed from Home Assistant."""
Add support for simultaneous runs of Script helper (#31937) * Add tests for legacy Script helper behavior * Add Script helper if_running and run_mode options - if_running controls what happens if Script run while previous run has not completed. Can be: - error: Raise an exception - ignore: Return without doing anything (previous run continues as-is) - parallel: Start run in new task - restart: Stop previous run before starting new run - run_mode controls when call to async_run will return. Can be: - background: Returns immediately - legacy: Implements previous behavior, which is to return when done, or when suspended by delay or wait_template - blocking: Returns when run has completed - If neither is specified, default is run_mode=legacy (and if_running is not used.) Otherwise, defaults are if_running=parallel and run_mode=background. If run_mode is set to legacy then if_running must be None. - Caller may supply a logger which will be used throughout instead of default module logger. - Move Script running state into new helper classes, comprised of an abstract base class and two concrete clases, one for legacy behavior and one for new behavior. - Remove some non-async methods, as well as call_from_config which has only been used in tests. - Adjust tests accordingly. * Change per review - Change run_mode default from background to blocking. - Make sure change listener is called, even when there's an unexpected exception. - Make _ScriptRun.async_stop more graceful by using an asyncio.Event for signaling instead of simply cancelling Task. - Subclass _ScriptRun for background & blocking behavior. Also: - Fix timeouts in _ScriptRun by converting timedeltas to float seconds. - General cleanup. * Change per review 2 - Don't propagate exceptions if call from user has already returned (i.e., for background runs or legacy runs that have suspended.) - Allow user to specify if exceptions should be logged. They will still be logged regardless if exception is not propagated. - Rename _start_script_delay and _start_wait_template_delay for clarity. - Remove return value from Script.async_run. - Fix missing await. - Change call to self.is_running in Script.async_run to direct test of self._runs. * Change per review 3 and add tests - Remove Script.set_logger(). - Enhance existing tests to check all run modes. - Add tests for new features. - Fix a few minor bugs found by tests.
2020-02-24 22:56:00 +00:00
await self.script.async_stop()
# remove service
self.hass.services.async_remove(DOMAIN, self.object_id)