Exemplo n.º 1
0
class ScriptEntity(ToggleEntity):
    """Representation of a script entity."""
    def __init__(self, hass, object_id, name, sequence):
        """Initialize the script."""
        self.object_id = object_id
        self.entity_id = ENTITY_ID_FORMAT.format(object_id)
        self.script = Script(hass, sequence, name, self.async_update_ha_state)

    @property
    def should_poll(self):
        """No polling needed."""
        return False

    @property
    def name(self):
        """Return the name of the entity."""
        return self.script.name

    @property
    def state_attributes(self):
        """Return the state attributes."""
        attrs = {}
        attrs[ATTR_LAST_TRIGGERED] = self.script.last_triggered
        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
        return attrs

    @property
    def is_on(self):
        """Return true if script is on."""
        return self.script.is_running

    async def async_turn_on(self, **kwargs):
        """Turn the script on."""
        context = kwargs.get("context")
        self.async_set_context(context)
        self.hass.bus.async_fire(
            EVENT_SCRIPT_STARTED,
            {
                ATTR_NAME: self.script.name,
                ATTR_ENTITY_ID: self.entity_id
            },
            context=context,
        )
        try:
            await self.script.async_run(kwargs.get(ATTR_VARIABLES), context)
        except Exception as err:  # pylint: disable=broad-except
            self.script.async_log_exception(
                _LOGGER, f"Error executing script {self.entity_id}", err)
            raise err

    async def async_turn_off(self, **kwargs):
        """Turn script off."""
        self.script.async_stop()

    async def async_will_remove_from_hass(self):
        """Stop script and remove service when it will be removed from HASS."""
        if self.script.is_running:
            self.script.async_stop()

        # remove service
        self.hass.services.async_remove(DOMAIN, self.object_id)