The example from tom_I is the correct answr here. As an example of a slightly different way of using it than Tom’s example, I also offer one here:
I have a situation that I only want to know when a light is turned OFF how it was turned off - if it was done by a dashboard, automation or physically. If it is on, I change the value to N/A for my purposes - but this code could be used in the opposite fashion as well:
#
# Bathroom Lights (for accessing these and with the last_changed value):
# {{ states('sensor.bathroom_lights_off_context') }}
# {{ states.sensor['bathroom_lights_off_context'].last_changed }}
#
# 1. Track the 'off' context changing (has to be triggered even if turning on,
# so any change at all will cause logic to be triggered if subsequent objects
# already set as "physical" will still be updated)
#
template:
- trigger:
- platform: state
entity_id: light.bathroom_shelly_1_relay
sensor:
- name: "Bathroom Lights Off 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 states('light.bathroom_shelly_1_relay') == 'on' %}
n/a
{% elif 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 %}
unique_id: bathroom_lights_off_context