Access to trigger.to_state.context from a different entity?

You do. All Some automation triggers (see the exception list here) change the context.

What you need to do is store the context when the switch turns on. You need to check all three contexts as per the table:

Screenshot 2022-06-21 081430

Then use that when your no-motion automation runs.

e.g. this triggered template sensor will save the switch context when it turns on:

(configuration.yaml)

template:
  - trigger:
      - platform: state
        entity_id: switch.shelly_1pm_garage_switch_0
		to: "on"
    sensor:
      - name: "Garage Switch On Context"
        state: >
		  {% set c_id = trigger.to_state.context.id %}
		  {% set c_parent = trigger.to_state.context.parent_id %}
          {% set c_user = trigger.to_state.context.user_id %}
		  {% if c_id != none and c_parent == none and c_user == none %}
		    physical
		  {% elif c_id != none and c_parent == none and c_user != none %}
		    dashboard_ui
		  {% elif c_id != none and c_parent != none and c_user == none %}
		    automation
		  {% else %}
		    unknown
		  {% endif %}

You then use this sensor in a state condition in your “no motion” automation.

e.g. if you want the switch turned off automatically after three minutes of no motion, but only when an automation turned the switch on:

alias: "Garage Light Auto Off"
trigger:
  - platform: state
    entity_id: binary_sensor.lumi_lumi_sensor_motion_aq2_motion
    to: "off"
    for:
      minutes: 3
condition:
  - condition: state
    entity_id: sensor.garage_switch_on_context
    state: "automation"
action:
  - service: switch.turn_off
    target:
      entity_id: switch.shelly_1pm_garage_switch_0
mode: single

You could remove the condition and use a choose action depending on the state of sensor.garage_switch_on_context if you want different things to happen depending on how it was turned on.

8 Likes