Skip to content
Merged
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
4 changes: 1 addition & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,12 @@ this [README](https://github.com/craigbarratt/hass-pyscript-jupyter/blob/master/

## Configuration

* Go to the Integrations menu in the Home Assistant Configuration UI and add `Pyscript Python scripting` from there. Alternatively, add `pyscript:` to `<config>/configuration.yaml`; pyscript has three optional configuration parameters that allow any python package to be imported if set, expose `hass` as a variable, and temporarily switch back to the legacy decorator subsystem; all three default to `false`:
* Go to the Integrations menu in the Home Assistant Configuration UI and add `Pyscript Python scripting` from there. Alternatively, add `pyscript:` to `<config>/configuration.yaml`; pyscript has two optional configuration parameters that allow any python package to be imported if set and expose `hass` as a variable; both default to `false`:
```yaml
pyscript:
allow_all_imports: true
hass_is_global: true
legacy_decorators: true
```
Starting with version `2.0.0`, pyscript uses the new decorator subsystem by default. If you find a problem in the new implementation, you can temporarily set `legacy_decorators: true` to switch back to the legacy one. If you do, please also file a bug report in [GitHub Issues](https://github.com/custom-components/pyscript/issues) so the new subsystem can be fixed.
* Add files with a suffix of `.py` in the folder `<config>/pyscript`.
* Restart HASS.
* Whenever you change a script file, make a `reload` service call to `pyscript`.
Expand Down
51 changes: 29 additions & 22 deletions custom_components/pyscript/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
from homeassistant.exceptions import HomeAssistantError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.restore_state import DATA_RESTORE_STATE
from homeassistant.helpers.typing import ConfigType
from homeassistant.helpers.typing import ConfigType, NoEventData
from homeassistant.loader import bind_hass

from .const import (
Expand All @@ -50,26 +50,25 @@
)
from .decorator import DecoratorRegistry
from .eval import AstEval
from .event import Event
from .function import Function
from .global_ctx import GlobalContext, GlobalContextMgr
from .jupyter_kernel import Kernel
from .mqtt import Mqtt
from .requirements import install_requirements
from .state import State, StateVal
from .stubs.generator import StubsGenerator
from .trigger import TrigTime
from .webhook import Webhook
from .task_functions import TaskFunctions

_LOGGER = logging.getLogger(LOGGER_PATH)

PYSCRIPT_SCHEMA = vol.Schema(
{
vol.Optional(CONF_ALLOW_ALL_IMPORTS, default=False): cv.boolean,
vol.Optional(CONF_HASS_IS_GLOBAL, default=False): cv.boolean,
vol.Optional(CONF_LEGACY_DECORATORS, default=False): cv.boolean,
},
extra=vol.ALLOW_EXTRA,
PYSCRIPT_SCHEMA = vol.All(
cv.removed(CONF_LEGACY_DECORATORS, raise_if_present=False),
vol.Schema(
{
vol.Optional(CONF_ALLOW_ALL_IMPORTS, default=False): cv.boolean,
vol.Optional(CONF_HASS_IS_GLOBAL, default=False): cv.boolean,
},
extra=vol.ALLOW_EXTRA,
),
)

CONFIG_SCHEMA = vol.Schema({DOMAIN: PYSCRIPT_SCHEMA}, extra=vol.ALLOW_EXTRA)
Expand Down Expand Up @@ -139,15 +138,14 @@ async def update_yaml_config(hass: HomeAssistant, config_entry: ConfigEntry) ->
# since they affect all scripts
#
config_save = {
param: config_entry.data.get(param, False)
for param in [CONF_HASS_IS_GLOBAL, CONF_ALLOW_ALL_IMPORTS, CONF_LEGACY_DECORATORS]
param: config_entry.data.get(param, False) for param in [CONF_HASS_IS_GLOBAL, CONF_ALLOW_ALL_IMPORTS]
}
if DOMAIN not in hass.data:
hass.data.setdefault(DOMAIN, {})
if CONFIG_ENTRY_OLD in hass.data[DOMAIN]:
old_entry = hass.data[DOMAIN][CONFIG_ENTRY_OLD]
hass.data[DOMAIN][CONFIG_ENTRY_OLD] = config_save
for param in [CONF_HASS_IS_GLOBAL, CONF_ALLOW_ALL_IMPORTS, CONF_LEGACY_DECORATORS]:
for param in [CONF_HASS_IS_GLOBAL, CONF_ALLOW_ALL_IMPORTS]:
if old_entry.get(param, False) != config_entry.data.get(param, False):
return True
hass.data[DOMAIN][CONFIG_ENTRY_OLD] = config_save
Expand Down Expand Up @@ -196,12 +194,12 @@ def __init__(
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, self.shutdown)
_LOGGER.debug("watchdog init path=%s", path)

def startup(self, event: Event | None) -> None:
def startup(self, event: HAEvent[NoEventData] | None) -> None:
"""Start the observer."""
_LOGGER.debug("watchdog startup")
self._observer.start()

def shutdown(self, event: Event | None) -> None:
def shutdown(self, event: HAEvent[NoEventData] | None) -> None:
"""Stop the observer."""
self._observer.stop()
self._observer.join()
Expand Down Expand Up @@ -283,6 +281,18 @@ def check_event(event: FileSystemEvent, do_reload: bool) -> bool:
_LOGGER.debug("watchdog started job and task folder=%s", pyscript_folder)


async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
"""Migrate an old config entry."""
if config_entry.version > 1:
# downgrade from a newer major version
return False
if config_entry.minor_version < 2:
# 1.2: the legacy_decorators option was removed
data = {key: val for key, val in config_entry.data.items() if key != CONF_LEGACY_DECORATORS}
hass.config_entries.async_update_entry(config_entry, data=data, minor_version=2)
return True


async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
"""Initialize the pyscript config entry."""
global_ctx_only = None
Expand All @@ -296,14 +306,11 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
global_ctx_only = "*"

Function.init(hass)
Event.init(hass)
Mqtt.init(hass)
TrigTime.init(hass)
State.init(hass)
Webhook.init(hass)
State.register_functions()
TaskFunctions.register_functions()
GlobalContextMgr.init()
DecoratorRegistry.init(hass, config_entry)
DecoratorRegistry.init(hass)

pyscript_folder = hass.config.path(FOLDER)
if not await hass.async_add_executor_job(os_path_isdir, pyscript_folder):
Expand Down
5 changes: 2 additions & 3 deletions custom_components/pyscript/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,15 @@
CONF_ALLOW_ALL_IMPORTS,
CONF_HASS_IS_GLOBAL,
CONF_INSTALLED_PACKAGES,
CONF_LEGACY_DECORATORS,
DOMAIN,
)

CONF_BOOL_ALL = (CONF_ALLOW_ALL_IMPORTS, CONF_HASS_IS_GLOBAL, CONF_LEGACY_DECORATORS)
CONF_BOOL_ALL = (CONF_ALLOW_ALL_IMPORTS, CONF_HASS_IS_GLOBAL)

PYSCRIPT_SCHEMA = vol.Schema(
{
vol.Optional(CONF_ALLOW_ALL_IMPORTS, default=False): bool,
vol.Optional(CONF_HASS_IS_GLOBAL, default=False): bool,
vol.Optional(CONF_LEGACY_DECORATORS, default=False): bool,
},
extra=vol.ALLOW_EXTRA,
)
Expand Down Expand Up @@ -90,6 +88,7 @@ class PyscriptConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a pyscript config flow."""

VERSION = 1
MINOR_VERSION = 2

@staticmethod
@callback
Expand Down
1 change: 1 addition & 0 deletions custom_components/pyscript/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
CONF_ALLOW_ALL_IMPORTS = "allow_all_imports"
CONF_HASS_IS_GLOBAL = "hass_is_global"
CONF_INSTALLED_PACKAGES = "_installed_packages"
# removed option, only used to clean it from old configs
CONF_LEGACY_DECORATORS = "legacy_decorators"

SERVICE_JUPYTER_KERNEL_START = "jupyter_kernel_start"
Expand Down
15 changes: 1 addition & 14 deletions custom_components/pyscript/decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,11 @@
import ast
import asyncio
import logging
import os
from typing import Any, ClassVar
import weakref

from homeassistant.config_entries import ConfigEntry
from homeassistant.core import Context, HomeAssistant

from .const import CONF_LEGACY_DECORATORS
from .decorator_abc import (
CallHandlerDecorator,
CallResultHandlerDecorator,
Expand Down Expand Up @@ -53,20 +50,10 @@ class DecoratorRegistry:
hass: ClassVar[HomeAssistant]

@classmethod
def init(cls, hass: HomeAssistant, config_entry: ConfigEntry = None) -> None:
def init(cls, hass: HomeAssistant) -> None:
"""Initialize the decorator registry."""
cls.hass = hass
cls._decorators = {}
disabled = False
if config_entry is not None and config_entry.data.get(CONF_LEGACY_DECORATORS, False):
disabled = True
elif "PYTEST_CURRENT_TEST" in os.environ and "NODM" in os.environ:
disabled = True

if disabled:
_LOGGER.warning("Using legacy decorators")
return

DecoratorManager.hass = hass

Function.register_ast({"task.wait_until": DecoratorRegistry.wait_until_factory})
Expand Down
7 changes: 3 additions & 4 deletions custom_components/pyscript/decorator_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import asyncio
from collections.abc import Awaitable
from dataclasses import dataclass, field
import datetime as dt
from enum import StrEnum
import logging
from typing import Any, ClassVar, final
Expand All @@ -14,16 +15,14 @@

from homeassistant.core import Context, HomeAssistant

from . import trigger
from .eval import AstEval

_LOGGER = logging.getLogger(__name__)


def dt_now():
"""Return current time."""
# For test compatibility. The tests patch this function
return trigger.dt_now()
"""Return current time; tests patch this function."""
return dt.datetime.now()


class DecoratorManagerStatus(StrEnum):
Expand Down
79 changes: 72 additions & 7 deletions custom_components/pyscript/decorators/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,85 @@

from ..decorator import WaitUntilDecoratorManager
from ..decorator_abc import DecoratorManagerStatus, DispatchData, TriggerDecorator, TriggerHandlerDecorator
from ..state import State
from ..trigger import (
any_trigger_exprs,
ident_any_values_changed,
ident_values_changed,
strip_trigger_expr,
)
from ..state import STATE_VIRTUAL_ATTRS, State
from .base import AutoKwargsDecorator, ExpressionDecorator

STATE_RE = re.compile(r"\w+\.\w+(\.((\w+)|\*))?$")

_LOGGER = logging.getLogger(__name__)


def strip_trigger_expr(expr):
"""Strip surrounding whitespace from a trigger expression (non-strings are returned as is)."""
return expr.strip(" \t\r\n") if isinstance(expr, str) else expr


def any_trigger_exprs(exprs):
"""
Join trigger expressions into one any([...]) expression.

Each expression is stripped and goes on its own lines, so a trailing # comment can't swallow
the separator or the closing bracket that follow it.
"""
return "any([" + "\n,\n".join(strip_trigger_expr(expr) for expr in exprs) + "\n])"


def ident_any_values_changed(func_args, ident):
"""Check for any changes to state or attributes on ident vars."""
var_name = func_args.get("var_name", None)

if var_name is None:
return False
value = func_args["value"]
old_value = func_args["old_value"]

for check_var in ident:
if check_var == var_name and old_value != value:
return True

if check_var.startswith(f"{var_name}."):
var_pieces = check_var.split(".")
if len(var_pieces) == 3 and f"{var_pieces[0]}.{var_pieces[1]}" == var_name:
if var_pieces[2] == "*":
# catch all has been requested, check all attributes for change
all_attrs = set()
if value is not None:
all_attrs |= set(value.__dict__.keys())
if old_value is not None:
all_attrs |= set(old_value.__dict__.keys())
for attr in all_attrs - STATE_VIRTUAL_ATTRS:
if getattr(value, attr, None) != getattr(old_value, attr, None):
return True
elif getattr(value, var_pieces[2], None) != getattr(old_value, var_pieces[2], None):
return True

return False


def ident_values_changed(func_args, ident):
"""Check for changes to state or attributes on ident vars."""
var_name = func_args.get("var_name", None)

if var_name is None:
return False
value = func_args["value"]
old_value = func_args["old_value"]

for check_var in ident:
var_pieces = check_var.split(".")
if len(var_pieces) < 2 or len(var_pieces) > 3:
continue
var_root = f"{var_pieces[0]}.{var_pieces[1]}"
if var_root == var_name and (len(var_pieces) == 2 or var_pieces[2] == "old"):
if value != old_value:
return True
elif len(var_pieces) == 3 and var_root == var_name:
if getattr(value, var_pieces[2], None) != getattr(old_value, var_pieces[2], None):
return True

return False


class StateActiveDecorator(TriggerHandlerDecorator, ExpressionDecorator):
"""Implementation for @state_active."""

Expand Down
Loading
Loading