Trying to use timestamp with offset as a trigger

As I’m not good with templating I’ve exhausted all my abilities with many hours trying various things in the template dev tool and reading previous posts etc.

I have a sensor from the Android companion app which provides my next alarm and I’d like to use that along with an offset (which I’d like to grab from an input datetime) to use as a trigger for an automation. I want to trigger an automation to gradually turn a light on based on subtracting the offset from the alarm time.

Sensor to use from the companion app: sensor.dave_s_s22_next_alarm currently has this state: 2024-07-31T21:05:00+00:00

I’ve created input_datetime.daves_next_alarm_offset which is currently set at 00:15:00

If someone can please help me create the template to subtract the input datetime offset from the alarm time and use that as a trigger, that would be great.

Here’s one way to do it:

alias: example
trigger:
  - platform: template
    value_template: >
      {% set t = (states('sensor.dave_s_s22_next_alarm') | as_timestamp
        - state_attr('input_datetime.daves_next_alarm_offset', 'timestamp'))
        | timestamp_custom('%H:%M') %}
      {{ now().strftime('%H:%M') == t }}
condition: []
action:
  ... your actions ...
2 Likes

A totally different approach for a similar outcome is with the Sleep as Android app. I’ve got it sending events via MQTT and it has events for “before alarm” which is 60 minutes early I think, as well as delays for the sound alarm.

My bed heater kicks on way early to get me out of deep sleep, then the lights fade in and a bit later the alarm sounds.

Using the template is definitely more flexible, but a similar outcome. :coffee:

I do actually use this app which is where the alarm time is coming from, via the companion app. I’ll look into this ‘before alarm’ entity. It currently doesn’t exist in my HA but I’m guessing it must need to be configured in the app first.

Awesome, thanks for this. I’ll give it a test run and report back.

On further investigation, this is enabled in the app so I guess I just need to listen for the MQTT event create a trigger based on the sensor changing to this state. It’s a shame the docs are almost non-existent.

I think I’ll still with the template option given I will have more flexibility.

Yeah, I ended up figuring out how to make the MQTT events work by following some thread about a totally different Automation platform. I tinkered and it finally worked. Then I later found there’s a HACS integration with the events pre-configured. I haven’t messed with that as I’d already got things working by that point. Here’s the trigger I use based on that thread I’d found linked from the SAA docs.

trigger:
  - platform: mqtt
    topic: SleepAsAndroid
condition:
  - condition: template
    value_template: "{{ trigger.payload_json.event == \"before_smart_period\" }}"

I change the "before_smart_period" part for whichever event from SAA I’m trying to be triggered by.

For some reason this trigger hasn’t seemed to work on both last Friday and this morning…

I didn’t get to see the state of this sensor before this mornings alarm but it is showing ready to go for tomorrow.

On further inspection it was unavailable for days:

Something going on with Sleep As Android it would seem, or the Companion app not sending through updates.

It’s been a few more days and this automation is still no longer triggering and I have no idea why it stopped.

Automation code
alias: Wake up morning lighting
description: ""
trigger:
  - platform: template
    value_template: |
      {% set t = (states('sensor.dave_s_s22_next_alarm') | as_timestamp
        - state_attr('input_datetime.daves_next_alarm_offset', 'timestamp'))
        | timestamp_custom('%H:%M') %}
      {{ now().strftime('%H:%M') == t }}
condition:
  - condition: state
    entity_id: binary_sensor.workday_sensor
    state: "on"
  - condition: state
    entity_id: person.dave
    state: home
action:
  - target:
      entity_id: light.tube_lamp
    data:
      brightness_pct: 1
      kelvin: 2000
    action: light.turn_on
  - metadata: {}
    data:
      lampBrightnessScale: zeroToOneHundred
      easingTypeInput: easeInOutSine
      endBrightnessPercent: 20
      endBrightnessEntityScale: zeroToOneHundred
      shouldResetTheStopEntityToOffAtStart: false
      minimumStepDelayInMilliseconds: 100
      isDebugMode: false
      light: light.tube_lamp
      transitionTime:
        hours: 0
        minutes: 10
        seconds: 0
    action: script.1704844855114
  - delay:
      hours: 0
      minutes: 30
      seconds: 0
      milliseconds: 0
  - action: light.turn_on
    metadata: {}
    data:
      brightness_pct: 1
      kelvin: 2000
    target:
      entity_id:
        - light.daves_bedside_lamp
        - light.rowes_bedside_lamp
  - action: script.1704844855114
    metadata: {}
    data:
      lampBrightnessScale: zeroToTwoFiftyFive
      easingTypeInput: easeInOutSine
      endBrightnessPercent: 12
      endBrightnessEntityScale: zeroToOneHundred
      shouldResetTheStopEntityToOffAtStart: false
      minimumStepDelayInMilliseconds: 100
      isDebugMode: false
      light: light.daves_bedside_lamp
      transitionTime:
        hours: 0
        minutes: 5
        seconds: 0
  - action: script.1704844855114
    metadata: {}
    data:
      lampBrightnessScale: zeroToTwoFiftyFive
      easingTypeInput: easeInOutSine
      endBrightnessPercent: 12
      endBrightnessEntityScale: zeroToOneHundred
      shouldResetTheStopEntityToOffAtStart: false
      minimumStepDelayInMilliseconds: 100
      isDebugMode: false
      light: light.rowes_bedside_lamp
      transitionTime:
        hours: 0
        minutes: 5
        seconds: 0
  - condition: state
    entity_id: sensor.sleepasandroid_dave
    state: sleep_tracking_stopped
  - target:
      entity_id: light.tube_lamp
    data:
      transition: 180
      brightness_pct: 80
      kelvin: 6500
    action: light.turn_on
mode: single

Before going to sleep last night I checked that the ‘next alarm’ entity had the correct state for my morning alarm and all looked good, but this morning nothing happened and the last automation trace is still back from days ago.

When I loo in the history for that sensor, there is nothing because I’m guessing I don’t have it included in the history settings. I didn’t think that would cause this issue…?

Unfortunately I’m still having trouble with this automation randomly not triggering in the mornings. Yesterday it worked, this morning it didn’t…

trigger:

platform: template
value_template: |-
  {% set t = (states('sensor.dave_s_s22_next_alarm') | as_timestamp
          - state_attr('input_datetime.daves_next_alarm_offset', 'timestamp'))
          | timestamp_custom('%H:%M') %}
        {{ now().strftime('%H:%M') == t }}

State of my alarm entity:

There is simply no sign of it trying to trigger this morning (ie: no Trace), only yesterday when it worked perfectly…

I checked the error log and there is nothing at the time the alarm should have triggered this automation.

Copy-paste the following into the Template Editor and confirm it reports the correct alarm time.

{{ (states('sensor.dave_s_s22_next_alarm') | as_timestamp
  - state_attr('input_datetime.daves_next_alarm_offset', 'timestamp')) | timestamp_custom('%H:%M') }}

Yep, it gives me 04:50 ready for tomorrow morning.

Did it work today at 04:50?

It’s a fairly straightforward template (compare two time strings) so I am puzzled that it occasionally fails to work.
The template updates every minute due to its use of now().

Grasping at straws here; is there a pattern to the trigger failures (like every other day)?

When do you change the value of sensor.dave_s_s22_next_alarm? The day/evening before the next morning? How often do you change it (like every day, or every other day)?

I think I’m probably about 12 hours different to you, but yes it worked this morning.

So:
Monday - worked
Tuesday - didnt’t work
Wednesday - worked…

However last week this pattern didn’t occur as I had multiple days in a row where it didn’t trigger.

The alarm time doesn’t change at all. It’s set to wake me up at 0450 every weekday, so the automation should only NOT trigger on a weekend.

Let’s try something a little bit different.

Create a Template Sensor helper (or in YAML; your choice) like this:

Here’s the template to make it easier to copy-paste:

{{ (states('sensor.dave_s_s22_next_alarm') | as_timestamp
  - state_attr('input_datetime.daves_next_alarm_offset', 'timestamp')) | as_datetime | as_local }}

It’s important that you set the Template Sensor’s device_class to timestamp.

Change the automation’s trigger from a Template Trigger to a Time Trigger.

alias: example
trigger:
  - platform: time
    at: sensor.dave_wakeup
condition: []
action:
  ... your actions ...

Now that the wakeup time is calculated by a Template Sensor, it makes it easy to see the resulting time in advance.

NOTE

Pay attention to what is shown on the bottom of the form where it say “This template listens for the following state changed events”.

In my case, it only listed the sensor and not the input_datetime. Perhaps it’s because my system doesn’t contain either of the two entities.

If it says the same thing on your system then that may present a problem. If it’s not monitoring the input_datetime then the template will not be evaluated whenever the input_datetime’s value changes.

Thanks for this. I’ve added the template and updated the automation. I’ll see how it performs.

With the previous config it did work fine again this morning, so that’s two days in a row.

Monday - worked
Tuesday - didn’t work
Wednesday - worked
Thursday - worked

Just to satisfy my curiosity, does your automation have any conditions?

It does, but on the days it hasn’t worked it wasn’t even triggered. Ie: no automation trace at all.

The conditions are just:
I have to be home
Its a weekday

On my phone right now so hard to paste the code… Plus it’s nearly bedtime. Hopefully it works again in the morning using your new code

It just worked again this morning, using the updated code so I think we are on a winner.

Thanks so much for the help

1 Like