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.