How to create a template sensor based on event data?

I have a zigbee device that publishes certain event data that is not accessible through the sensors exposed through ZHA.

I can listen to “zha_events” in the developer section and see the data coming in as an event. I want to take that data parse it and feed a template sensor attributes with it

Is that possible?

You’ll want to use a Trigger-based Template Sensor with an Event Trigger (listening for zha_events) and then get the event’s data using trigger.event.data.

thanks, i can trigger on the event, but for some reason can’t access the trigger data.

here is the payload of the event:

{
        "device_ieee": "00:15:8d:00:03:12:ec:4d",
        "unique_id": "00:15:8d:00:03:12:ec:4d:1:0x0500",
        "device_id": "6f8cf524b94f527fe35f11e31e2dd5f0",
        "endpoint_id": 1,
        "cluster_id": 1280,
        "command": "current_orientation",
        "args": [
            {
                "rawValueX": 65524,
                "rawValueY": 1056,
                "rawValueZ": 288,
                "X": 89,
                "Y": 1,
                "Z": 0
            }
        ]
    }

And here is the template sensor:

template:
  - trigger:
      - platform: event
        event_type: "zha_event"
        event_data:
          device_id: 6f8cf524b94f527fe35f11e31e2dd5f0
          command: 'current_orientation'
    sensor:
      - name: "Dog hatch movement"
        state: "{{ trigger.event_data.args[0].X }}"

the state comes as unavailable any idea why?

my bad. it was trigger.event.data NOT trigger.event_data all working now. thanks a lot :slight_smile:

1 Like

This thread has been invaluable to me setting up my Aqara vibration sensors for something very similar, so thank you for starting it now a year+ later! I have it running almost exactly as you do - but I’m wondering where is the best place to put it these kinds of “Trigger Based Template Sensors”?

The first line of the YAML you provide is template: - but I already have a template: option in my configuration.yaml and HA is throwing an error that I can’t have duplicates.

My current template: attribute uses the !include template.yaml method so that I could put all my existing templates into a separate file. But when I try to do the same with this, it doesn’t work.

Is this an automation and maybe I should add it to automation.yaml? I also have a sensors.yaml for custom sensors? Appreciate any thoughts or ideas on how I can keep this template outside of the main configuration and also have the ability to create new ones.

It’ll go in template.yaml in that case, but don’t include the template: first line. That’s covered by:

template: !include template.yaml

That file should then start with:

- trigger:
    - platform: event
      event_type: "zha_event"

if you’re using the above code.

1 Like

Wow, too obvious. Now it’s working, thank you for answering my first ever post on the forums!

1 Like