Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Custom trigger decorators #464

Unanswered
j-steve asked this question in Show and tell
Apr 15, 2023 · 1 comments · 1 reply
Discussion options

I've been using some custom trigger decorators that I've found useful, sharing in case others might want to do similar things:

def zha_trigger(device_ieee, command=None):
 def trigger_builder(func):
 event_command_suffix = '' if not command else f' and command == "{command}"'
 @event_trigger('zha_event', f'device_ieee=="{device_ieee}" {event_command_suffix}')
 def trigger_function(**kwargs):
 func(**kwargs)
 return trigger_function
 return trigger_builder
def on_off_trigger(entity_id, minutes=0):
 def trigger_builder(func):
 @state_trigger(entity_id, state_hold=minutes * 60, state_check_now=minutes > 0)
 def trigger_function(value=None, **kwargs):
 if value in ['on', 'off']:
 func(value == 'on')
 else:
 log.info(
 f'Entity "{entity_id}" changed to unexpected value "{value}".')
 return trigger_function
 return trigger_builder

Example usage:

@zha_trigger("05:bf:8c:df:4c:72:28:ff")
def button_1_triggered():
 pass
@zha_trigger("05:bf:8c:df:4c:72:28:ff", "button_1_press")
def button_1_pressed():
 pass
@on_off_trigger("sensor.kitchen_motion", minutes=5)
def kitchen_motion_changed(value):
 pass

zha_trigger just simplifies the syntax for listening for Zigbee events, which is quite common in my code.

on_off_trigger is a wrapper around state_trigger which only responds to "on" and "off" values (so it won't be triggered for anomolous states like "unknown") and converts the state to a boolean for easier handling, It also converts hold duration to minutes, and always enables state_check_now (so it plays nicely with unexpected system reboots).

These are pretty minor but they do simplify the syntax within my code!

You must be logged in to vote

Replies: 1 comment 1 reply

Comment options

I'm a noob here, I do grok how you set this up. Could you point me to a documentation place or a more expanded example? Thx.

You must be logged in to vote
1 reply
Comment options

I updated my example, it was missing the code for zha_trigger so it should be more Grok-able now, assuming you are familiar with decorators in Python.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /