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 27 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
115 changes: 113 additions & 2 deletions custom_components/pyscript/trigger.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
_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\*]?[a-zA-Z]*)?$")


def dt_now():
Expand Down Expand Up @@ -644,6 +644,112 @@ def start(self):
self.task = Function.create_task(self.trigger_watch())
_LOGGER.debug("trigger %s is active", self.name)

def ident_any_values_changed(self, func_args):
"""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:
_LOGGER.debug(
"%s ident_any change not detected because no var_name",
self.name,
)
return False

for check_var in self.state_trig_ident_any:
if check_var == var_name and old_value != value:
_LOGGER.debug(
"%s ident_any change detected at state",
self.name,
)
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 -= {"last_updated", "last_changed"}
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:
_LOGGER.debug(
"%s ident_any change detected in * at %s",
self.name,
attribute,
)
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:
_LOGGER.debug(
"%s ident_any change detected at %s",
self.name,
var_pieces[2],
)
return True

_LOGGER.debug(
"%s no ident_any change detected",
self.name,
)
return False

def ident_values_changed(self, func_args):
"""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:
_LOGGER.debug(
"%s ident changes not detected because no var_name",
self.name,
)
return False

for check_var in self.state_trig_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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this whole if clause necessary? In this case ident_any_values_changed() would already have returned True.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My thought process was that ident_any_values_changed() checked it, but the value did not change. Therefore, it didn't return True. So, in ident_values_changed() we can skip it (and save some CPU) since they were already checked. If we take the if out, since it didn't return True before, it won't return True now either.

var_pieces = check_var.split('.')
if len(var_pieces) == 2 and check_var == var_name:
if value != old_value:
_LOGGER.debug(
"%s ident change detected at state",
self.name
)
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:
_LOGGER.debug(
"%s ident change detected at attribute %s",
self.name,
var_pieces[2]
)
return True

_LOGGER.debug(
"%s no ident change detected",
self.name,
)

return False

async def trigger_watch(self):
"""Task that runs for each trigger, waiting for the next trigger and calling the function."""

Expand Down Expand Up @@ -739,7 +845,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 self.ident_any_values_changed(func_args):
# if var_name not in func_args we are state_check_now
if "var_name" in func_args and not self.ident_values_changed(func_args):
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 @@ -748,6 +858,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