Templates as automation triggers with time

Apologies if this has been asked a thousand times already. I have checked the forums and seen several answers, but I just cannot wrap my head around this. It is probably something very simple.

I have set up an alarm to an Android-phone, which gives sensor.sm_j500fn_next_alarm to Home assistant. I want to use it to turn on the lights ten (or some other, easily changeable amount of) minutes before the alarm.

Then, after perusing the forums and countless examples, I managed to create the following, which works quite well in the developer tool template tester:

{% set timenow = as_timestamp(now()) %}
{% set settime = states('sensor.sm_j500fn_next_alarm')|as_timestamp|int %}
{% set starttime = settime - (10*60) %}
{% set slot = (starttime <= timenow < settime) %}
{% if slot %}
True 
{% else %}
False
{% endif %}

It works very well, and does exactly what I’d expect it to do. True when within the time window, and false otherwise.
Oddly enough, the above did not work as an automation trigger.

Then I thought, hmm, maybe the last line should be another type of question, to give a boolean result. At least there are several examples in the forums that provide a question as the last line…

This led to the code below:

{% set timenow = as_timestamp(now()) %}
{% set settime = states('sensor.sm_j500fn_next_alarm')|as_timestamp|int %}
{% set starttime = settime - (10*60) %}
{{(starttime <= timenow < settime)}}

It does not work either, but does give a nice and correct True/False in the template tester.

Templates seem to be pretty logical in every other sense, except here.

I’ve tested that the outcome, i.e. lights turning on, does execute correctly. Please do not suggest making a binary sensor, unless it’s the only way to do it: I’d rather get the trigger-question to work properly, because it’s a really curious problem to be solved, and also because having a binary sensor would require changes to two places with every new sensor or change to them.

Hmm, this the resulting configuration from automations.yaml:

- id: '1603141492156'
  alias: wake up lights
  description: ''
  trigger:
  - platform: template
    value_template: '{% set timenow = as_timestamp(now()) %}

      {% set settime = states(''sensor.sm_j500fn_next_alarm'')|as_timestamp|int %}

      {% set starttime = settime - (10*60) %}

      {{(starttime <= timenow < settime)}}'
  condition: []
  action:
  - service: light.turn_on
    data: {}
    entity_id: light.study
  mode: single

Perhaps that is missing something essential, but I am just too tired to see it at the moment.

Could someone kindly shed some light on this one, as I’m still learning the ropes? Being able to parameterize time would be essential for what I’ve planned for the future. :slight_smile:

Well, as I read your post, I thought: oh, binary sensor would work here. :slight_smile:

The other thought I had after looking at your sample code, and I’m not a templating expert, is that the examples in the documentation for multi-line statements have a “>-” at the end, and then the template code begins on the next line. Have you tried this?

And here is my way of templating one minute before alarm time:

Actually, it’s not odd at all. The template relies on now() to supply the current time. That’s a function, not an entity. For Template Triggers, Home Assistant only listens for state-changes of entities, not functions.

For more information, see: Templates without entities using now()

The quickest way to fix it is to add this as the first line:

{% set x = states('sensor.time') %}

Ensure you have configured sensor.time as part of the Time & Date integration (otherwise my suggestion won’t work).

Your template can be streamlined a bit:

{% set x = states('sensor.time') %}
{% set settime = states('sensor.sm_j500fn_next_alarm')|as_timestamp|int %}
{% set starttime = settime - (10*60) %}
{{ starttime <= now().timestamp() < settime) }}
2 Likes

Here mine

I cant take the credit for it found in here somewhere

I have the sensor

#=======================================================================
#
#=======================================================================
  - platform: template
    sensors:
      minutes_next_alarm_stephan:
        friendly_name: "Minutes until Next Alarm Stephan"
        unit_of_measurement: 'm'
        value_template: >-
          {% set dummy = states("sensor.time") %}
          {{((states('sensor.stephan_phone_next_alarm')|as_timestamp|int - now()|as_timestamp|int)/60)|int}}
        availability_template: "{{ not is_state('sensor.stephan_phone_next_alarm','unavailable') }}"
        attribute_templates:
          time: "{{ state_attr('sensor.stephan_phone_next_alarm','Local Time') }}"

image

now the automation to turn the kettle on and lights in the kitchen
with a choose option if its nite time

#=======================================================================
#
#=======================================================================
- id: '85cf493e-b8eb-4a8b-8645-b384b752d0fd'
  alias: My Phone Alarm about to go off
  description: ''
  trigger:
  - platform: numeric_state
    entity_id: sensor.minutes_next_alarm_stephan
    below: '2'
  action:
  - data:
      entity_id: switch.kettle_power
    service: switch.turn_on
  - delay: '00:00:50'  
  - data:
      entity_id: light.his_side
    service: light.turn_on
  - choose:
      - conditions:
          - condition: state
            entity_id: sensor.day_night
            state: 'Night'
        sequence:
          - service: light.turn_on
            entity_id: light.kitchen
  mode: single

2 Likes

And here is my template sensor on the next alarm to get a human friendly time. (Today, tomorrow, Friday, 2020…)

Thanks, this had all the missing elements! I got it to work nicely, thank you.

1 Like

Thanks for this as well, I tried it and it also worked, and made me better understand the state-dependent triggering in general.

Thanks, will try these out once I’ve more time.

I do have the time_date integration enabled (in configuration.yaml):

sensor:
  - platform: time_date
    display_options:
      - 'time'
      - 'date'
      - 'date_time'

and used in automation template trigger:

alias: Lighting - Halloween - unset
description: ""
trigger:
  - platform: template
    value_template: |+
      {% set x = states('sensor.time') %}
      {% set n = now() %}
      {{ 10 != n.month or n.day != 31 }}

condition: []
action:
  - service: input_boolean.turn_off
    data: {}
    target:
      entity_id: input_boolean.halloween_mode
mode: single

however, the automation never triggers. Am running home assistant 2023.9.2. Viewing traces in the automation dropdown menu shows no activity.

according to Templating - Home Assistant :

Not supported in limited templates.

so maybe this functionality has since been removed?

As a workaround, by making the trigger any change to sensor.date_time and moving the template trigger into the condition, i.e.:

alias: Lighting - Halloween - unset
description: ""
trigger:
  - platform: state
    entity_id:
      - sensor.date_time
condition:
  - condition: template
    value_template: |
      {% set n = now() %}
      {{ 10 != n.month or n.day != 31 }}
action:
  - service: input_boolean.turn_off
    data: {}
    target:
      entity_id: input_boolean.halloween_mode
mode: single

the automation triggers properly and it stops (or continues) further execution due to the condition check.

You have replied to a post I made three years ago and, since then, Home Assistant has gone through three dozen revisions.

Instead of resurrecting a long-dead topic, post your question in a new topic.