Trigger event source determination

I have an automation that triggers when a smart plug is turned on.

I’d really only like it to perform its actions if the switch turns on because of events outside of Home Assistant’s control e.g. if the user presses the button on the smart plug. I don’t want it to perform the action if the switch is turned on by someone using the Home Assistant web or app GUI or if another automation turns it on for other reasons.

Is there any way of determining in the automation whether Home Assistant turned on the switch or if it just turned on without HA having asked it to?

It’s normally done by examining the properties of the context object produced when the automation’s trigger fires.

Based on the table here, your automation’s condition should look like this:

alias: example 
triggers:
  - platform: state
    entity_id: switch.your_smart_plug
    from: 'off'
    to: 'on'
conditions:
  - "{{ trigger.to_state.context.id != none }}"
  - "{{ trigger.to_state.context.parent_id == none }}"
  - "{{ trigger.to_state.context.user_id == none }}"
action:
  ... your actions ..

EDIT

Correction. Changed second condition’s test to ==

Ah. Lovely, thanks. I’ll give that a go although shouldn’t it be !=, ==, == according to the table?

And might it not be more efficient to do a single template?

conditions:
  - template: |-
      {{
          trigger.to_state.context.id != none and
          trigger.to_state.context.parent_id == none and
          trigger.to_state.context.user_id == none
      }}

I’l do some logging in the automation as I may want to consider other cases in future automations.

If you wish; either way, the critical thing is if the template achieves your stated goal.

FWIW, if you ever want to inspect the automation’s trace, your version will report a single boolean value whereas the other reports three (makes it easier to inspect each one separately). Plus it’s slightly less verbose because the logical ANDing is implicit. However if you feel those benefits don’t outweigh any minor performance improvement, use your consolidated version.

I come from a C/C++/assember bare-metal embedded design background so looking for efficiency is automatic. Not all of us have gigabytes RAM and gigahertz CPUs. :wink: Some of the stuff I work with still has kilobytes and megahertz or even less.

Good point about the tracing though for debug.

Thanks again.

1 Like

Yes, sorry I got that wrong in my example. You want to detect when someone manually changes the state of the physical device.

I’ll correct the example to prevent misleading other users.