Allow templates to be used with above:,below: & for: in trigger

This has been mentioned in discussions, but I can’t find it under feature requests, so I’m entering it as a feature request. Please upvote if you agree.

The basic issue is described at [Input_slider value used in automation for a delayed switch off doesn’t work] (Input_slider value used in automation for a delayed switch off doesn't work)

The request is to allow a template to work following “for:” as below. For completeness, templates should work for “above” and “below” also.

trigger:
  platform: state
  entity_id: sensor.vision_zp3111_multisensor_4in1_burglar_10_10
  above: '0'
  below: '8'
  for:
    minutes: '{{ states.input_slider.nachspielzeit.state | int }}'

The workarounds I have seen add complication which makes things harder to maintain.

You’ll probably get more votes if you change the title to:
Allow templates to be used with "for:"

Thanks. Changed,

I’ve actually been considering trying to implement this (for the for: option.) I’ve seen many, many requests for help where a template in the for: option would have made things much simpler.

The first question that might come up is, when should the template be evaluated? My thought would be, when the trigger fires, that’s when the template would be evaluated and the value would be used in the async_track_same_state call.

This would be awesome! I agree it would make things much simpler. I have about a dozen automations that I can use this in.

I’m not familiar with the underlying code, io I can’t comment on the use of async_track_same_state. My use cases are primarily to test how long an entity has been in a specific state and fire a trigger if appropriate, so it is part of the the trigger evaluation; e.g. when a window has been open for X minutes, then turn off the air conditioner

I think I have it working for the for: parameter of the template trigger. It provides the same variables to the template(s) in the for: option as it does to the automation’s conditions and actions. If anyone would like to give it a try, let me know. Basically you’d have to (at least temporarily) replace <ha_install_dir>/components/automation/template.py

PR submitted:

https://github.com/home-assistant/home-assistant/pull/24810

Still need to update documentation.

I was requested to submit this one trigger type at a time. I started with the template trigger. I’ll do the same for the other triggers that have a for: option.

UPDATE: The PR mentioned above for the template trigger was accepted.

I’ve also submitted PR 24912 adding template support to the state trigger’s for option. numeric_state is next.

1 Like

I just submitted PR 24955 adding template support to the numeric_state trigger’s for option.

UPDATE: PRs 24912 & 24995 have been accepted and merged, so hopefully the ability to use templates with the for: option in the template, state & numeric_state triggers will be available starting in 0.96.

Does this mean I can use a template for ‘above’ and ‘below’ now?
such as

above: '{{ state_attr("input_number.blah", "max") | float }}'

No, just the for option.

I think the before: and after: are ‘nigh on’ impossible (okay that’s hyperbole). You have to calculate them at say 00:01 then work out the offsets (I assume that this would be (say) 20 mins before sunrise ? So a lot more involved. I think any ‘fair’ coder could do it - but it would be 2 automations and an input_datetime required)

The topic title is misleading. Based on the first post I think the OP meant to say above: and below:, not before: and after:.

I suppose it might be possible to allow templates for above: and below:, but it’s a little more involved because the theshold(s) could then change dynamically (i.e., after the trigger is initialized.) I think the implementation would be reasonably doable, but I’m not sure users would always understand the ramification of the threshold(s) changing.

Since this can easily be done with a template trigger already it’s probably better not to add this functionality and just leave it as an “advanced” capability.

I absolutely agree, if you are that involved in HA to require these, your skills should already be adequate to the task. (templating in general was a brilliant idea, there should be HA awards (like an HA Nobel) awarded each year voted by the members)
The for: template was a nice bonus (Thank you ! Though I haven’t actually needed it as yet, again because of templates)
I didn’t realise you’d added these so ‘long ago’ (last July) though I think I remember the discussion, :beer: .

I think the topic is now dead enough for you to quietly ‘cleanse’ the title, just to aid in others searching :smiley:

For anyone looking at this trying to figure out how to make this work…

This is how you may want it to work, but it doesn’t.

 trigger:
   - platform: numeric_state
     entity_id: 
       - sensor.office_computer_power
     above: "{{ states( 'input_number.office_active_level' ) | float }}"

You can get the same functionality you desire, but working from

trigger:
  - platform: template
    value_template: "{% if ( states( 'sensor.office_computer_power' ) | float) >
    ( states( 'input_number.office_active_level' ) | float ) %}true
    {% endif %}"
1 Like

Actually, what I want is both to use a template in “above” and “below”, but also use the input_numbers directly, like you can do with platform time and an input_datetime:

trigger:
  - platform: numeric_state
    entity_id: sensor.office_power
    above: input_number.office_active_level 

(But full templates could of course be used to create more advanced triggers, like kicking in when something is between 10 - 15% of soemthing else and whatnot)

In v0.115 it became possible to use input * helpers for a numeric state condition which is very powerfull. It should be nice if numeric state triggers also allow input* helpers directly or with the use of a template.

Actually it is not quite the same. Lets asume that the amount of power is already below input_number.office_active_level. If the amount of power drops any further it will trigger. A numeric state would not trigger because it only triggers if the state crosses the threshold.

You are correct. I didn’t catch that. Would this added condition fix that?

trigger:
  - platform: template
    value_template: "{% if ( states( 'sensor.office_computer_power' ) | float) >
    ( states( 'input_number.office_active_level' ) | float ) %}true
    {% endif %}"
condition:
  - condition: template
    value_template: >-
      {{ trigger.from_state.state != true }}

Hi, I am trying to use your method to see if attribute ‘media position’ is bigger than ‘media duration -5s’, since I had the same problem that the above/below does not accept a state, only numbers. I got the following, but it is not working. Any idea what I am doing wrong?

trigger:
  - platform: template
    value_template: >-
      {% if (
      states('media_player.plex_plex_for_apple_tv_living_room.attributes.media_position'
      ) | float) > ((
      states('media_player.plex_plex_for_apple_tv_living_room.attributes.media_duration'
      ) | float ) - 5 | float) %}true {% endif %}

Your template isn’t accessing the media_player’s attributes correctly. In addition, it’s unnecessary to make the template explicitly report true. It can report true or false implicitly.

trigger:
  - platform: template
    value_template: >
      {% set player = 'media_player.plex_plex_for_apple_tv_living_room' %}
      {{ state_attr(player, 'media_position') | float > state_attr(player, 'media_duration') | float - 5 }}

NOTE

An entity’s attributes can have a type other than string. Therefore the values may already be integers or floats in which case it isn’t required to convert them with the float filter (I don’t have a media_player entity handy to check its attributes).

Hi :slight_smile:
Anyone care to elaborate? I have a script that defines in each moment of time when run: do we want to switch to cooling mode, venting or heating. The problem I had before - is that in the morning when waking up the script decides once. But the weather keeps changing. Using that same comparison will lead to the temperature line up somewhere on the limit of let’s say cooling and venting. So I am looking into redoing the script to be slightly more dynamic. to forgive thresholds for 0.5celsius. But considering above: {{…}} template is not possible, what are the optimal ways to do it? Create a local variable, where I would use a template to do the “if” I need and then pass it to above? Don’t know much about variables and would prefer not to make copy of the whole script. Please let me know if you have any solutions to that :slight_smile:

studio_wakeup_define_ac_mode:
  sequence:
    #check climate control
  - condition: state
    entity_id: input_boolean.automatic_climate_control
    state: "on"
    #Window closed
  - type: is_not_open
    condition: device
    device_id: 34f7c1f01e3c6e0502a6ce22adbf8f20
    entity_id: binary_sensor.lumi_aq2_f128_magnet_sensor
    domain: binary_sensor
    #depending on temp
  - choose:
    - conditions:
      - type: is_temperature
        condition: device
        device_id: f3837ef5edcdd360a0ee0aae75325781
        entity_id: sensor.temperature_lumi_158d0003f0530a
        domain: sensor
        above: input_number.temp_day_upper_threshold #would like to pass a lower by 0.5 value here based on some other variable settings
      sequence:
      - service: script.studio_ac_cool27fresh
      - service: input_select.select_option
        entity_id: input_select.temp_feels_like
        data_template:
          option: hot
    - conditions:
      - type: is_temperature
        condition: device
        device_id: f3837ef5edcdd360a0ee0aae75325781
        entity_id: sensor.temperature_lumi_158d0003f0530a
        domain: sensor
        above: input_number.temp_day_lower_threshold #would like to pass a higher by 0.5 value here  based on some other variable settings
      sequence:
      - service: script.studio_ac_fresh
      - service: input_select.select_option
        entity_id: input_select.temp_feels_like
        data_template:
          option: normal
    - conditions: []
      sequence:
      - service: script.studio_ac_heat24fresh
      - service: input_select.select_option
        entity_id: input_select.temp_feels_like
        data_template:
          option: cold
    default: []
  mode: single
  alias: Wake up - Define Studio AC mode
  icon: mdi:sleep-off