-
Notifications
You must be signed in to change notification settings - Fork 58
Custom trigger decorators #464
-
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!
Beta Was this translation helpful? Give feedback.
All reactions
-
🎉 1
Replies: 1 comment 1 reply
-
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.
Beta Was this translation helpful? Give feedback.
All reactions
-
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.
Beta Was this translation helpful? Give feedback.