Triggering Automation from template-derived datetime sensor

Hey everyone. I have been working on an issue for a while now and it’s time to reach out an find out why I can’t resolve it. Any insight would be appreciated.

I have created a sensor which uses templating to take an attribute from the Next Alarm sensor on my phone (milliseconds), apply an offset from an input_number, do the necessary calculations, and output a datetime object. I then use an automation triggered by the resulting time to turn on the central heating.

The output of the sensor looks fine, but the automation isn’t triggering.
Here is the sensor code - I know it’s not elegant, but it does apparently do what I want it to do.

sensor:
  heating_phone_alarm:
        value_template: >-
          {% if states('sensor.kphone_next_alarm') == 'unavailable' %}
          Off
          {%- else -%}
          {% set ms = state_attr('sensor.kphone_next_alarm','Time in Milliseconds') | int %}
          {% set offset = states('input_number.heating_phone_alarm_offset') | int %}
          {% set ms = ms * 0.001 %}
          {% set offset = offset * 60 %}
          {% set result = ms + offset %}
          {{ result | int | as_datetime }}
          {%- endif -%}

And here is the automation trigger code:

  alias: Phone Alarm Heating Trigger
  description: ''
  trigger:
  - platform: time
    at: sensor.heating_phone_alarm

An example of the sensor output:

2022-12-03 09:40:00+00:00

Any thoughts would be appreciated!

In order for a Time Trigger to use a sensor, the sensor’s device_class must be timestamp and its value must be in a recognizable datetime format (preferably ISO format).

You can start by adding device_class: timestamp to the Template Sensor’s configuration but you also need to fix the value it reports when sensor.kphone_next_alarm is unavailable. It can’t report Off because that’s not a datetime. I suggest you replace Off with a time in the past (for example, the Unix Epoch: 1970-01-01T00:00:00+00:00).

2 Likes

Thank you very much! That makes perfect sense, I’ll give it a try