Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions custom_components/pyscript/decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,12 @@ async def _call(self, data: DispatchData) -> None:
accepted = {a.arg for a in func_args.args + func_args.kwonlyargs}
call_kwargs = {k: v for k, v in data.func_args.items() if k in accepted}
result = await data.call_ast_ctx.call_func(self.eval_func, None, **call_kwargs)
except asyncio.CancelledError:
# the call was killed while running; let result handlers answer their callers
self.logger.debug("Call cancelled for %s", self.name)
for result_handler_dec in result_handlers:
await self.safe_await(result_handler_dec.handle_call_canceled(data))
raise
except Exception as e:
for result_handler_dec in result_handlers:
await self.safe_await(result_handler_dec.handle_call_exception(data, e))
Expand Down Expand Up @@ -325,4 +331,5 @@ async def dispatch(self, data: DispatchData) -> None:
)

task = Function.create_task(self._call(data), ast_ctx=action_ast_ctx)
data.call_task = task
Function.task_done_callback_ctx(task, action_ast_ctx)
3 changes: 3 additions & 0 deletions custom_components/pyscript/decorator_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

from abc import ABC, abstractmethod
import asyncio
from collections.abc import Awaitable
from dataclasses import dataclass, field
from enum import StrEnum
Expand Down Expand Up @@ -46,6 +47,8 @@ class DispatchData:

call_ast_ctx: AstEval | None = field(default=None, kw_only=True)
hass_context: Context | None = field(default=None, kw_only=True)
# the task running the function, set by the manager once the call is started
call_task: asyncio.Task | None = field(default=None, kw_only=True)


class Decorator(ABC):
Expand Down
72 changes: 51 additions & 21 deletions custom_components/pyscript/decorators/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,29 @@
from __future__ import annotations

import ast
import asyncio
from collections import OrderedDict
import io
import logging
import typing
from typing import Any

import voluptuous as vol
import yaml

from homeassistant.const import SERVICE_RELOAD
from homeassistant.core import ServiceCall, SupportsResponse
from homeassistant.core import ServiceCall, ServiceResponse, SupportsResponse
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.service import async_set_service_schema

from .. import DOMAIN, SERVICE_JUPYTER_KERNEL_START, AstEval, Function, State
from .. import DOMAIN, SERVICE_JUPYTER_KERNEL_START, Function, State
from ..decorator import FunctionDecoratorManager
from ..decorator_abc import Decorator
from ..decorator_abc import CallResultHandlerDecorator, DispatchData, TriggerDecorator

_LOGGER = logging.getLogger(__name__)

_SERVICE_RESULT_FUTURE = "service_result_future"


def service_validator(args: list[str]) -> list[str]:
"""Validate and normalize service name."""
Expand All @@ -37,7 +42,7 @@ def service_validator(args: list[str]) -> list[str]:
return [domain, name]


class ServiceDecorator(Decorator):
class ServiceDecorator(TriggerDecorator, CallResultHandlerDecorator):
"""Implementation for @service."""

name = "service"
Expand Down Expand Up @@ -89,31 +94,56 @@ async def validate(self) -> None:
fields[arg.arg] = OrderedDict(description=f"argument {arg.arg}")
self.description = {"description": desc, "fields": fields}

async def _service_callback(self, call: ServiceCall) -> None:
async def _service_callback(self, call: ServiceCall) -> ServiceResponse:
_LOGGER.info("Service callback: %s", call.service)

# use a new AstEval context so it can run fully independently
# of other instances (except for global_ctx which is common)
global_ctx = self.dm.eval_func.global_ctx
ast_ctx = AstEval(self.dm.name, global_ctx)
Function.install_ast_funcs(ast_ctx)
func_args = {
"trigger_type": "service",
"context": call.context,
}
func_args.update(call.data)

async def do_service_call(func, ast_ctx, data):
try:
_LOGGER.debug("Service call start: %s", func.name)
return await func.call(ast_ctx, **data)
except Exception as exc:
await self.dm.handle_exception(exc)
return None

task = Function.create_task(do_service_call(self.dm.eval_func, ast_ctx, func_args))
await task
return task.result()
future = self.dm.hass.loop.create_future()
data = DispatchData(func_args, trigger_context={_SERVICE_RESULT_FUTURE: future})
await self.dispatch(data)
try:
result = await future
except asyncio.CancelledError:
# the caller was cancelled (e.g. a restarted script): stop the function too
if data.call_task is not None:
data.call_task.cancel()
raise
if call.return_response and result is None:
# like HA scripts: a call that was skipped or returned nothing gives an empty response
return {}
return result

async def handle_call_result(self, data: DispatchData, result: Any) -> None:
"""
Return the function result as the service response.

A call that was skipped or cancelled (@state_active, @time_active, @task_unique)
gets None via the default handle_call_canceled.
"""
if data.trigger is not self:
return
future = data.trigger_context.get(_SERVICE_RESULT_FUTURE)
if future is not None and not future.done():
future.set_result(result)

async def handle_call_exception(self, data: DispatchData, exc: Exception) -> None:
"""Fail the service call when the function raised; the manager still logs the exception."""
if data.trigger is not self:
return
future = data.trigger_context.get(_SERVICE_RESULT_FUTURE)
if future is None or future.done():
return
if isinstance(exc, HomeAssistantError):
future.set_exception(exc)
return
error = HomeAssistantError(f"{self.dm.name}() raised {type(exc).__name__}: {exc}")
error.__cause__ = exc
future.set_exception(error)

async def start(self) -> None:
"""Register the service."""
Expand Down
22 changes: 17 additions & 5 deletions docs/reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1183,13 +1183,25 @@ default), ``"only"``, or ``"optional"``, depending on whether the service provid
provides a response, or sometimes provides a response. Services responses were added in HASS 2023.7.
The service response is a dictionary returned by the function.

Other trigger decorators like ``@state_active`` and ``@time_active`` don't affect the service.
Those still allow state, time or other triggers to be specified in addition.
A service call is handled like any other trigger, so ``@state_active``, ``@time_active`` and
``@task_unique`` apply to it, and other triggers like ``@state_trigger`` or ``@time_trigger`` can be
added to the same function. If ``@state_active`` or ``@time_active`` evaluates to ``False``, or
``@task_unique(kill_me=True)`` finds the task already running, the function is not called. A call
that is cancelled by a newer call with the same ``@task_unique`` name doesn't complete either. In
these cases, and whenever the function returns ``None``, a caller that requested a response gets an
empty dictionary, as with Home Assistant scripts. If the function raises an exception, the service
call fails with a ``HomeAssistantError`` (shown in the UI and stopping a calling automation or
script), and the exception is also logged by pyscript. Like other triggers, each service call fires a
``pyscript_running`` event, which is shown in the logbook.

With ``@time_active(hold_off_send_last=True)``, a service call that arrives during the hold-off
window is answered right away like a skipped call, but the function still runs with its parameters
when the window ends.

The function is called with keyword parameters set to the service call parameters, plus
``trigger_type`` is set to ``"service"``. The function definition should specify all the
expected keyword arguments to match the service call parameters, or use the ``**kwargs``
argument declaration to capture all the keyword arguments.
``trigger_type`` is set to ``"service"``. The function receives only the service call parameters
it declares; others are ignored unless the function uses the ``**kwargs`` argument declaration to
capture all of them.

The ``doc_string`` (the string immediately after the function declaration) is used as the service
description that appears is in the Services tab of the Developer Tools page. The function argument
Expand Down
Loading
Loading