Extracting Event data from a "state_changed" event with a template sensor. How?

In NodeRED, I can use an event node and a switch to filter out specific event types (state_changed) so I can pull the data from the event bus, then store it in context variables.

I’m wondering how I can also do the same thing using yaml.

I have the following template sensor, but I’m struggling with the syntax, I think. I’m getting “unavailable” as the state.

- trigger:
    - platform: event
      event_type: "state_changed"
      event_data:
        entity_id: input_button.fair_play_task_home_garbage
  sensor:
    - name: "Fair Play Task Home Garbage Last"
      state: "{{trigger}}"
      attributes:
        old_state: "{{trigger.event.old_state.state}}"
        new_state: "{{trigger.event.new_state.state}}"

As you can see, I want to watch the input_button only for a change of state. Then, I want to assign various values of that event to the attributes of the sensor.

I must be missing something in how this works.

You have forgotten the data in your templates:

        old_state: "{{trigger.event.data.old_state.state}}"

Also, you should probably not use trigger as the state… it’s just going to be a mess.

It can be a bit more concise with a State Trigger.

- trigger:
    - platform: state
      target:
        entity_id: input_button.fair_play_task_home_garbage
      to:
  sensor:
    - name: "Fair Play Task Home Garbage Last"
      state: "{{trigger}}"
      attributes:
        old_state: "{{trigger.from_state.state}}"
        new_state: "{{trigger.to_state.state}}"
1 Like

With “event” I believe I have access to more data, correct?

Like what exactly?

Here are the State object’s properties.

Did the concise example I posted above answer your question or is there something more you require?

I chose this path, and it works:

- trigger:
    - platform: event
      event_type: "state_changed"
      event_data:
        entity_id: input_button.fair_play_task_home_garbage
  sensor:
    - name: "Fair Play Task Home Garbage"
      state: "Hello"
      attributes:
        old_state: "{{as_local(as_datetime(trigger.event.data.old_state.state))}}"
        new_state: "{{as_local(as_datetime(trigger.event.data.new_state.state))}}"
        timer: "Handled by NodeRED"

As you can see, the state of the sensor really doesn’t matter. I just wanted to create a sensor that I can use to create a new sensor that will serve as a measure of how much time passes between each state change, which will be written to a spreadsheet.

It’s my understanding there’s a performance penalty for employing an Event Trigger, compared to a State Trigger, with no added benefit for this application (which happens to be an ideal candidate for a State Trigger).

Anyway, you asked for advice and you’re free to ignore it. Glad to hear it works for you.

That makes perfect sense event if it is filtered. I’ll switch it up to the state since the result would be the same.