Template sensor with two different trigger events?

I’ve been struggling with this one for a while now. Any help would be very appreciate.

Situation:
I have a sensor that accumlates the rain at the house. After some conditions are met, this sensor is reset to 0mm (the conditions are controlled by the smart rain gauge - an ecowitt). This has the affect of accumulating the rain for a particular “rain event”.

Mission:
I want to create a template sensor that stores the date and time when the “rain event” rises above 0 and is set to 0 when the “rain event” returns back to 0. The value of the new template sensor should only change when the “rain event” goes from 0 to a value greater than 0 or if the “rain event” becomes 0.

Execution:
My template sensor currently does one of these things (stores the date/time when the “rain event” rises above 0). See code below.

Question:
How do I do the second part of this problem - set the value of the template sensor to ‘0’ when the “rain event” falls to 0?

  # Trigger based template sensor that updates when rain event rises above 0 
template: 
  - trigger:
    - platform: numeric_state
      entity_id: sensor.gw1100c_v2_2_1_event_rain_rate
      above: 0
    sensor:
      - name: "Date Rain Event Began"
        state: "{{ now().strftime('%a %d-%b-%y %H:%M:%S') }}"
# Trigger based template sensor that updates when rain event rises above 0 
template: 
  - trigger:
    - platform: numeric_state
      entity_id: sensor.gw1100c_v2_2_1_event_rain_rate
      above: 0
    - platform: state
      entity_id: sensor.gw1100c_v2_2_1_event_rain_rate
      to: '0'
    sensor:
      - name: "Date Rain Event Began"
        state: "{{ now().strftime('%a %d-%b-%y %H:%M:%S') if trigger.platform == 'numeric_state' else 0 }}"

Amazing! and thanks for the quick reply. The

if trigger.platform == 'numeric_state'

is a neat trick! How do you test/troubleshoot this? Asking so I can be more self-sufficient with this stuff. But other then using the Templates area in Developer Tools, I struggle with testing stuff like this.

1 Like

Reference: Automation Trigger Variables

The trigger variable contains a property named platform. The value of this property is the name of the trigger platform that triggered the automation.

Thanks @123. How do you normally test with this stuff? or you don’t and you’re just that good? :joy:

Unless I am certain, I use the Template Editor when possible.

Obviously it’s not possible to test the template if it contains the trigger variable (because it’s defined only by an actual trigger). In that case I may replace it with a substitute variable just for testing purposes.

Yeah very cool. Ok well it’s good to know that there isn’t some other magic way to do this stuff.

While I’ve got you here, I hope I’m not pushing the friendship if I ask a related question?

Is there a way to develop a second template sensor that calculates and updates every minute "the time since Date_Rain_Event_Began" ?

The template sensor would display (as a string) something like
Time Since Rain Event Began: 3mins
or
Time Since Rain Event Began: 1hr, 45mins
or
Time Since Rain Event Began: 2days, 8hr, 33mins

etc

And while I’ve got you here, please consider marking my post above with the Solution tag. It will automatically place a check-mark next to the topic’s title which signals to other users that this topic has been resolved. This helps users find answers to similar questions.

Yes. I suggest you familiarize yourself with the relative_time filter.

Done! and thank you very much again! You will be remembered as a true legend!

@123 Trying to get this working but running into issues. I’ve created an input_number helper to act as the Rain_Event_Sensor. But for some reason, the other template sensors aren’t showing up in the States tab in Developer Tools

  # store the datetime object when the event event sensor rises above 0  
template:
  - trigger:
    - platform: numeric_state
      entity_id: input_number.test_rain_event_input
      above: 0
    sensor:
      - name: "Rain Event Began Timestamp"
        unique_id: test_rain_event_timestamp
        state: "{{ now() }}"
  # use the stored datetime object above to calculate relative time since the rain event sensor rose above 0 
  - sensor: 
    - name: "Time Since Rain Event Began" 
      unique_id: test_rain_event_delta 
      state: "{{as_datetime(as_timestamp(now()) - as_timestamp(sensor.test_rain_event_timestamp)) | relative_time}}"

I checked the logs and it’s because test_rain_event_timestamp sensor hasn’t been given a default value and so it’s set to ‘unknown’ which makes the second template sensor fail. struggling with how to fix this.

homeassistant.exceptions.TemplateError: ValueError: Template error: as_timestamp got invalid input 'unknown' when rendering template '{{as_datetime(as_timestamp(now()) - as_timestamp(states('sensor.test_rain_event_timestamp'))) | relative_time}}' but no default was specified

Ok i’ve got it to a point now that the sensor is updating and showing the relative time (see code below). The issue is now the sensor only updates when the the test_rain_event_timestamp updates, and it only updates when the input_number.test_rain_event_automation goes rises above 0.

What I really want is the test_rain_event_delta sensor to update each minute or something like that.

  # store the datetime object when the event event sensor rises above 0  
  - trigger:
    - platform: numeric_state
      entity_id: input_number.test_rain_event_automation
      above: 0
    sensor:
      - name: "Rain Event Began Timestamp"
        unique_id: test_rain_event_timestamp
        state: "{{now()}}"
   # use the stored datetime object above to calculate relative time since the rain event sensor rose above 0 
  - sensor: 
    - name: "Time Since Rain Event Began" 
      unique_id: test_rain_event_delta 
      state: "{{as_datetime(states('sensor.test_rain_event_timestamp')) | relative_time }}"

Ok final update. Everything is working now :joy:

  # store the datetime object when the event event sensor rises above 0  
  - trigger:
    - platform: numeric_state
      entity_id: sensor.gw1100c_v2_2_1_event_rain_rate
      above: 0
    sensor:
      - name: "Rain Event Began Timestamp"
        unique_id: rain_event_began_timestamp
        state: "{{now()}}"
  # Trigger based template sensor that updates when rain event goes above 0 or is set to 0 
  - trigger:
    - platform: numeric_state
      entity_id: sensor.gw1100c_v2_2_1_event_rain_rate
      above: 0
    - platform: state
      entity_id: sensor.gw1100c_v2_2_1_event_rain_rate
      to: '0'
    sensor:
      - name: "Date Rain Event Began"
        unique_id: date_rain_event_began
        state: "{{ now().strftime('%a %d-%b %H:%M') if trigger.platform == 'numeric_state' else 0 }}"
        
   # use the stored datetime object above to calculate relative time since the rain event sensor rose above 0 
  - trigger:
    - platform: time_pattern  # update the sensor every 60 seconds 
      seconds: "/59"    
    - platform: numeric_state # update the sensor when the rain event raises above 0 
      entity_id: sensor.gw1100c_v2_2_1_event_rain_rate
      above: 0
    sensor: 
      - name: "Time Since Rain Event Began" 
        unique_id: time_since_rain_event_began
        state: "{{as_datetime(states('sensor.rain_event_began_timestamp')) | relative_time }}"

I am also trying to use multiple triggers in a template. I can’t use the approach above as all of my platforms will be “state”. I will eventually have 4 triggers here, but for now I am trying to make this work with just 2.

Here is my code:

#
# FRONT DOOR CHANGED EXPERIMENTAL TEMPLATE
#
  - trigger:
      - platform: state
        entity_id: lock.lock_front_door
        from: 'unlocked'
        to: 'locked'     
        id: front_door_locked
      - platform: state
        entity_id: lock.lock_front_door
        from: 'locked'
        to: 'unlocked'     
        id: front_door_unlocked        
    sensor:
      - name: Front door last changed
        state:  "{{ now() }}"
        attributes: 
          display_name_for_table: >
            {% if(trigger.id =='locked') %}
            "Front unlocked"
            {% elif (trigger.id =='unlocked') %}
              "Front locked"
            {% else %}
              "trigger.id is not defined"
            {% endif %}            
          master_sort_value: 5  

When the template is triggered (by either the door unlocking or locking) - the template state is not set as I would expect. It seems that trigger.id is not getting set. Any suggestions on what I am missing please?

Thanks
Ken

Your trigger id’s don’t match what you are using in the template comparisons.

image

vs.

image

Your attribute template should be:

...
        attributes: 
          display_name_for_table: >
            {% if(trigger.id =='front_door_locked') %}
              Front locked
            {% elif (trigger.id =='front_door_unlocked') %}
              Front unlocked
            {% else %}
              trigger.id is not defined
            {% endif %}    
...
1 Like

Thanks! I actually realized this shortly after posting :frowning: and should have edited my question. I do though have a related issue. It seems when my trigger is based on the state of a binary sensor, I have real trouble getting it to trigger consistently (it works if I only have a single trigger - but never triggers with multiple triggers).

Here is my current code:

# MUD ROOM DOOR OPENED / CLOSED
#
  - trigger:
      - platform: state
        entity_id: binary_sensor.door_sensor_mud_room_state
        from: 'on'
        to: 'off'     
        id: mud_room_door_closed
      - platform: state
        entity_id: binary_sensor.door_sensor_mud_room_state
        from: 'off'
        to: 'on'    
        id: mud_room_door_opened        
    sensor:
      - name: Mud Room door last opened
        state:  "{{ now() }}"
        attributes: 
          display_name_for_table: >
            {% if(trigger.id =='mud_room_door_closed') %}
              'Mud Room closed'
            {% elif (trigger.id =='mud_room_door_opened') %}
              'Mud Room opened'
            {% else %}
              trigger.id is not defined
            {% endif %}            

This works for entities other than binary sensors, or with binary sensors as long as there is only a single trigger.

I’m getting the impression you cannot use binary sensors as multiple triiggers in a template. The (ugly) alternative might be to create a helper text field, and an automation with the multiple triggers (to set the value of the helper), and then use that helper to trigger my original template. Really ugly given I have 13 door sensors I would need to do this with.

There must be a cleaner way to accomplish this?

You can but your application doesn’t need to use multiple triggers.

# MUD ROOM DOOR OPENED / CLOSED
#
  - trigger:
      - platform: state
        entity_id: binary_sensor.door_sensor_mud_room_state
        from:
          - 'on'
          - 'off'     
        to:
          - 'off' 
          - 'on'            
    sensor:
      - name: Mud Room door last opened
        state:  "{{ now() }}"
        attributes: 
          display_name_for_table: "Mud Room {{ iif(trigger.to_state.state == 'on', 'opened', 'closed') }}"
1 Like

Beautiful (and much more elegant)! I will give that a try.

It worked!! Now to simplify a lot of other templates I created previously!

Many thanks!