Skip to content

state_trigger only triggers on value changes (using StateVar) #82

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 32 commits into from
Nov 7, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
5de420b
progress
dlashua Nov 5, 2020
bf0543b
progress
dlashua Nov 5, 2020
300c39f
pull upstream master
dlashua Nov 5, 2020
57c04b1
send strings in new_var
dlashua Nov 5, 2020
8941b00
issue when value/old_value is None
dlashua Nov 5, 2020
08f334d
attrib change checking when new/old value is None
dlashua Nov 5, 2020
8f9a323
restore notify_var_get to original
dlashua Nov 5, 2020
7f8ffa0
cleanup unused vars
dlashua Nov 5, 2020
e5a0bfa
provide default when attribute doesn't exist
dlashua Nov 5, 2020
3296f74
cleanup change detecting logic
dlashua Nov 5, 2020
8c2bd0e
handle state_check_now correctly
dlashua Nov 5, 2020
f06c0c4
adjust test for StateVar
dlashua Nov 5, 2020
c49310d
add domain.entity.* tracking
dlashua Nov 5, 2020
d43c79d
if we don't find d.e.* matches, keep looking normally.
dlashua Nov 5, 2020
67cc67b
cleaner syntax
dlashua Nov 5, 2020
5d1d4d8
let STATE_RE catch d.e.any
dlashua Nov 5, 2020
eeb6a6d
logic correction
dlashua Nov 5, 2020
3228934
more readable
dlashua Nov 5, 2020
00de489
properly determine all attributes
dlashua Nov 6, 2020
c57a311
break out variables to reduce repetition
dlashua Nov 6, 2020
a591ddc
break change check logic into functions and move above trig eval
dlashua Nov 6, 2020
cc9615d
deal with old_value/value is None
dlashua Nov 6, 2020
50a083a
skip ident change check if also in ident_any
dlashua Nov 6, 2020
2497f0a
correct trig eval logic
dlashua Nov 6, 2020
ba79200
formatting
dlashua Nov 6, 2020
b063ff6
debugging and pass tests
dlashua Nov 6, 2020
a18e253
make state_check_now logic more readable
dlashua Nov 6, 2020
729f522
better STATE_RE
dlashua Nov 7, 2020
0da11b9
make and use STATE_VIRTUAL_ATTRS
dlashua Nov 7, 2020
6d57457
first pass at wait_until and global ident checks
dlashua Nov 7, 2020
0d4e32c
correct logic
dlashua Nov 7, 2020
fe03993
Merge branch 'master' into only-changes
dlashua Nov 7, 2020
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
12 changes: 9 additions & 3 deletions custom_components/pyscript/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
from .global_ctx import GlobalContext, GlobalContextMgr
from .jupyter_kernel import Kernel
from .requirements import install_requirements
from .state import State
from .state import State, StateVar
from .trigger import TrigTime

_LOGGER = logging.getLogger(LOGGER_PATH)
Expand Down Expand Up @@ -193,8 +193,14 @@ async def state_changed(event):
# state variable has been deleted
new_val = None
else:
new_val = event.data["new_state"].state
old_val = event.data["old_state"].state if event.data["old_state"] else None
new_val = StateVar(event.data['new_state'])

if "old_state" not in event.data or event.data["old_state"] is None:
# no previous state
old_val = None
else:
old_val = StateVar(event.data['old_state'])

new_vars = {var_name: new_val, f"{var_name}.old": old_val}
func_args = {
"trigger_type": "state",
Expand Down
1 change: 0 additions & 1 deletion custom_components/pyscript/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

STATE_VIRTUAL_ATTRS = {"last_changed", "last_updated"}


class StateVar(str):
"""Class for representing the value and attributes of a state variable."""

Expand Down
100 changes: 89 additions & 11 deletions custom_components/pyscript/trigger.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@
from .eval import AstEval
from .event import Event
from .function import Function
from .state import State
from .state import State, STATE_VIRTUAL_ATTRS

_LOGGER = logging.getLogger(LOGGER_PATH + ".trigger")


STATE_RE = re.compile(r"[a-zA-Z]\w*\.[a-zA-Z]\w*$")
STATE_RE = re.compile(r"[a-zA-Z]\w*\.[a-zA-Z]\w*(\.(([a-zA-Z]\w*)|\*))?$")


def dt_now():
Expand All @@ -48,6 +48,74 @@ def parse_time_offset(offset_str):
return value * scale


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

if var_name is None:
return False

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_attributes = set()
if value is not None:
all_attributes |= set(value.__dict__.keys())
if old_value is not None:
all_attributes |= set(old_value.__dict__.keys())
all_attributes -= STATE_VIRTUAL_ATTRS
for attribute in all_attributes:
attrib_val = getattr(value, attribute, None)
attrib_old_val = getattr(old_value, attribute, None)
if attrib_old_val != attrib_val:
return True
else:
attrib_val = getattr(value, var_pieces[2], None)
attrib_old_val = getattr(old_value, var_pieces[2], None)
if attrib_old_val != attrib_val:
return True

return False

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

if var_name is None:
return False

for check_var in ident:
# if check_var in self.state_trig_ident_any:
# _LOGGER.debug(
# "%s ident change skipping %s because also ident_any",
# self.name,
# check_var,
# )
# continue
var_pieces = check_var.split('.')
if len(var_pieces) == 2 and check_var == var_name:
if value != old_value:
return True
elif len(var_pieces) == 3 and f"{var_pieces[0]}.{var_pieces[1]}" == var_name:
attrib_val = getattr(value, var_pieces[2], None)
attrib_old_val = getattr(old_value, var_pieces[2], None)
if attrib_old_val != attrib_val:
return True

return False



class TrigTime:
"""Class for trigger time functions."""

Expand Down Expand Up @@ -252,14 +320,19 @@ async def wait_until(
else:
new_vars, func_args = None, {}

state_trig_ok = False
if func_args.get("var_name", "") in state_trig_ident_any:
state_trig_ok = True
elif state_trig_eval:
state_trig_ok = await state_trig_eval.eval(new_vars)
exc = state_trig_eval.get_exception_obj()
if exc is not None:
break
state_trig_ok = True

if not ident_any_values_changed(func_args, state_trig_ident_any):
# if var_name not in func_args we are state_check_now
if "var_name" in func_args and not ident_values_changed(func_args, state_trig):
state_trig_ok = False

if state_trig_eval:
state_trig_ok = await state_trig_eval.eval(new_vars)
exc = state_trig_eval.get_exception_obj()
if exc is not None:
break

if state_hold is not None:
if state_trig_ok:
if not state_trig_waiting:
Expand Down Expand Up @@ -738,7 +811,11 @@ async def trigger_watch(self):
elif notify_type == "state":
new_vars, func_args = notify_info

if "var_name" not in func_args or func_args["var_name"] not in self.state_trig_ident_any:
if not ident_any_values_changed(func_args, self.state_trig_ident_any):
# if var_name not in func_args we are state_check_now
if "var_name" in func_args and not ident_values_changed(func_args, self.state_trig_ident):
continue

if self.state_trig_eval:
trig_ok = await self.state_trig_eval.eval(new_vars)
exc = self.state_trig_eval.get_exception_long()
Expand All @@ -747,6 +824,7 @@ async def trigger_watch(self):
trig_ok = False
else:
trig_ok = False

if self.state_hold_dur is not None:
if trig_ok:
if not state_trig_waiting:
Expand Down
10 changes: 1 addition & 9 deletions tests/test_decorator_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,15 +194,7 @@ def func_wrapup():
"""Exception in <file.hello.func6 @state_active()> line 1:
1 / pyscript.var1
^
TypeError: unsupported operand type(s) for /: 'int' and 'str'"""
in caplog.text
)

assert (
"""Exception in <file.hello.func6 @state_active()> line 1:
1 / pyscript.var1
^
TypeError: unsupported operand type(s) for /: 'int' and 'str'"""
TypeError: unsupported operand type(s) for /: 'int' and 'StateVar'"""
in caplog.text
)

Expand Down