How to trigger automation BEFORE set time?

All right, here goes… I only edited out parts that are not relevant, for example recorded includes etc… And cleaned all the code that was commented out anyway. Also, there still might be some remains from my tests, for example that input_datetime…

# Alarm clock
input_number:
  alarm_clock_hour:
    initial: 6
    min: 0
    max: 23
    step: 1
  alarm_clock_minute:
    initial: 58
    min: 0
    max: 59
    step: 1
  kesto:
    initial: 32
    min: 0
    max: 60

# My car heater
  alarm_clock2_hour:
    initial: 7
    min: 0
    max: 23
    step: 1
  alarm_clock2_minute:
    initial: 30
    min: 0
    max: 59
    step: 1

# Her car heater
  alarm_clock3_hour:
    initial: 6
    min: 0
    max: 23
    step: 1
  alarm_clock3_minute:
    initial: 50
    min: 0
    max: 59
    step: 1

# Kahvinkeitin
  kahvinkeitin_hour:
    initial: 6
    min: 0
    max: 23
    step: 1
  kahvinkeitin_minute:
    initial: 10
    min: 0
    max: 59
    step: 1

input_datetime:
  departure_time:
    name: Input with both date and time
    has_time: true
    initial: "08:00"

sensor:
  - platform: mitemp_bt
    mac: 'XX:XX:XX:XX:XX'
    name: Xiaomei sensori 1
    force_update: true
    median: 1
    monitored_conditions:
      - temperature
      - humidity
      - battery


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


  - platform: template
    sensors:
      alarm_clock_time:
        value_template: >
          {% set h = states('input_number.alarm_clock_hour') | int %}
          {% set m = states('input_number.alarm_clock_minute') | int %}
          {{ '{0:0=2d}:{1:0=2d}'.format(h, m) }}

      alarm_clock2_time:
        value_template: >
          {% set h = states('input_number.alarm_clock2_hour') | int %}
          {% set m = states('input_number.alarm_clock2_minute') | int %}
          {{ '{0:0=2d}:{1:0=2d}'.format(h, m) }}

      alarm_clock3_time:
        value_template: >
          {% set h = states('input_number.alarm_clock3_hour') | int %}
          {% set m = states('input_number.alarm_clock3_minute') | int %}
          {{ '{0:0=2d}:{1:0=2d}'.format(h, m) }}

      kahvinkeitin_time:
        value_template: >
          {% set h = states('input_number.kahvinkeitin_hour') | int %}
          {% set m = states('input_number.kahvinkeitin_minute') | int %}
          {{ '{0:0=2d}:{1:0=2d}'.format(h, m) }}

automation: !include automations.yaml
automation old: !include_dir_merge_list automations

automation old:
  - alias: 'Car heater test'
    trigger:
      - platform: template
        value_template:  >-
          {% set temp = states('sensor.sonoffth3_am2301_temperature') | float %}
          {% set time = as_timestamp((now().date() ~ 'T' ~ states('sensor.alarm_clock2_time') ~':00') | timestamp_custom('%H:%M') %}
          {{ states('sensor.time') == t and temp > -10 }}

    condition:
      condition: and
      conditions:
        - condition: numeric_state
          entity_id: sensor.sonoffth3_am2301_temperature
          above: -10
    action:
      - service: switch.turn_on
        entity_id: switch.sonoffpow3_2
      - delay: '02:00:00'
      - service: switch.turn_off
        entity_id: switch.sonoffpow3_2


switch:
  - platform: wake_on_lan
    mac: "XX-XX-XX-XX-XX-XX"
    name: TheKone hereille
    host: 192.168.0.11
    broadcast_address: 192.168.0.255

group: !include groups.yaml
#automation: !include automations.yaml
script: !include scripts.yaml
scene: !include scenes.yaml

So, I have managed to do all other automations via Lovelace, but for this car heater thing I went back to configuration.yaml.

Your first problem is that you have two automation olds. can’t have that.

Second I think the issue is that date() doesn’t return a string so try this:

          {% set temp = states('sensor.sonoffth3_am2301_temperature') | float %}
          {% set time = as_timestamp((now().date() | string ~ 'T' ~ states('sensor.alarm_clock2_time') ~':00') | timestamp_custom('%H:%M') %}
          {{ states('sensor.time') == t and temp > -10 }}

Actually that’s how I had it in my old configuration.yaml and after tinkering with it for a while, the only way it actually works. The first two are include lines, and they have to be right there so that I can see both manual and Lovelace automations on my frontend.

I tried your code but I think there is something wrong with the formatting (and it bugs me because I cannot figure out why. So my automation is now like this:

automation old:
  - alias: 'My car test'
    trigger:
      - platform: template
        value_template:  >-
          {% set temp = states('sensor.sonoffth3_am2301_temperature') | float %}
          {% set time = as_timestamp((now().date() | string ~ 'T' ~ states('sensor.alarm_clock2_time') ~':00') | timestamp_custom('%H:%M') %}
          {{ states('sensor.time') == t and temp > -10 }}

    condition:
      condition: and
      conditions:
        - condition: numeric_state
          entity_id: sensor.sonoffth3_am2301_temperature
          above: -10
    action:
      - service: switch.turn_on
        entity_id: switch.sonoffs203
      - delay: '02:00:00'
      - service: switch.turn_off
        entity_id: switch.sonoffs203

And check config returns error: Invalid config for [automation]: invalid template (TemplateSyntaxError: unexpected ‘}’, expected ‘)’) for dictionary value @ data[‘trigger’][0][‘value_template’]. Got None. (See /config/configuration.yaml, line 229).

Also I am not sure how HASS counts those lines as line 229 is empty line just before that first automation include line. When I comment out those three lines in template, configuration is valid again.

By the way, shouldn’t the last line be a comparison between sensor.time and the time that is 1-3 hours before now? Temperature is already covered in conditions.

put that value_template in Developer Tools → Template and see what it says in HA log.

I believe that’s the way it works unfortunately. From my experience sometimes it cannot point you to a string with error and refers to the line a file with error is included in configuration.yaml

p.s this

automation: !include automations.yaml
automation old: !include_dir_merge_list automations

looks weird. HA accepts that (just tried) but to avoid any confusion I’d rather have all automations in automations and remove automation completely (and rename automation old to just automation), but that’s me.

It says pretty much the same: Error rendering template: TemplateSyntaxError: unexpected ‘}’, expected ‘)’

Yes, I have noticed that too, but in this case, the problematic code is in configuration.yaml.

That’s how home assistant documentation advices to use it.: Automation editor - Home Assistant

My Lovelace-created automations (all those work flawlessly) are in automations.yaml, and that’s why I have to include that. But because this complex automation seemingly needs to be in configuration.yaml, I have to use that automation_old, so that will be included as well. Tried without, and then HA couldn’t see this automation anymore.

Remove one of the “(” after as_timestamp like this:

{% set time = as_timestamp(now().date() | string ~ 'T' ~ states('sensor.alarm_clock2_time') ~':00') | timestamp_custom('%H:%M') %}

2 Likes

Thank you Burningstone, that did the trick! Although I am not sure what is that “t” in third line of that template: In template editor, it returns “false” even when time is exactly the same as sensor.alarm_clock2_time (if I have understood right, it SHOULD return “true” when those times are the same, and temperature is above -10 (that is true as well).

Of course, what I wanted was that automation would trigger 1-3 hours before based on temperature, but for now I would just like to see “true” in that template editor :smiley:

that contradicts yours

Got it. No problem then, that’s a special case for Automation Editor.

you mean it doesn’t work with the editor? then yes, you probably have no choice (but I suspect that you can easily copy the working automation from your automation old and add it to automations.yaml and it should work (not sure about the editor though :wink:
and btw, it’s possibly a bug in the editor so if it does not let you do what you want, open a new issue on Github to let the developers know.

correct, it only sees what you include.

I think it should be time

1 Like

Well, the editor seems to mess up lines , so if I choose to use yaml in automation editor, everything looks nice, but when I save, it switches back to UI where lines are like I posted in my first post, AND when I look back at yaml, lines are messed up there as well :confused: My other templates use only one line so those work just fine, but for this one I thought it was best to use configuration.yaml… And, my old automation, which used to work at least in my previous HASS installation, used several value_templates under sensor, so I thought there has to be smarter way of doing things…

D’oh! Of course! I seem to think that you guys write flawless code so didn’t notice that :smiley: Now when I set sensor.alarm_clock2_time to same as current time, this template returns true!

          {% set temp = states('sensor.sonoffth3_am2301_temperature') | float %}
          {% set time = as_timestamp((now().date() | string ~ 'T' ~ states('sensor.alarm_clock2_time') ~':00') | timestamp_custom('%H:%M') %}
          {{ states('sensor.time') == time and temp > -10 }}

So now that the above template works, I would need to think how I can use this one template to determine if the trigger should happen one, two or three hours before sensor.alarm_clock2_time based on outdoor temperature…

that’s how any HA editor works, same applies to Lovelace editor (it also removes any comments) - and that’s why many people prefer to edit their configs manually.

glad that your template is finally functional :wink:
btw, if using it you don’t need condition in your automation old

1 Like

I did notice that condition now checks the outdoor temperature, same as template, but I thought condition just HAVE to be there as it’s automation :slight_smile: Apparently that’s not the case!

mate, you should read docs - without understanding the basics it’s hard to progress.
condition is optional.

well, I thought sensor.sonoffth3_am2301_temperature is your outdoor temperature. and therefore in your template one of the conditions is outdoor temperature is above -10.
so you probably need to modify it

Oh believe me, I have read a lot! It’s just that the learning curve is quite steep and it’s easy to forget something that you have already read… :confused: What’s more, there are lots of old information around net, which is understandable with product such as HASS that is updating and changing all the time…

Yes, that’s what I thought as well, and that’s also why this template returned true when two times were identical. But I don’t know how to write that it returns true when time is three hours BEFORE current time, and when outdoor temperature is above -10 (of course, in reality I would change it to less than -10C but this is for testing purposes), and then add other conditions (if temperature is between -10 and -5 AND time is 2 hours before alarm time, and when temperature is between -5 and +2 AND time is one hour before alarm time… I know I should use if - then - else -logic somehow (or, in home assistant, if, elif, endif or something like that :slight_smile: )

based on that, I think you need to consider reading this post and adapting it according to your circumstances (asking for help here if needed) as it’s something similar to yours, isn’t it?
alternatively, create your own using Jinja’s if :wink:

You should only rely on information in the official documentation, don’t get your info from reddit, youtube videos or whatever.

1 Like

wanted to say the same. however, that does not 100% guarantee as documentation is currently a little step behind the process because it’s FAST so keep it in mind. the best source of information is code but that’s another story :wink:

2 Likes

I agree, however the docs will at least be the most updated information you can get if you are not a coder.

2 Likes

I have read that thread already and tried yesterday those solutions but they didn’t work for me… However, I was planning to do just what you suggested, that is to adapt those solutions to this template…

Basically my problem with this whole thing is that Jinja syntax is very alien to me, but I thought I start reading Jinja documentation next… I might have done that anyway, but I was just in a hurry with this because it’s winter and our cars need to be heated before we leave to work every morning :smiley: BUT now that this template works as it is, at least I can program it to trigger when we are still asleep, and estimate when exactly our cars are leaving home :slight_smile: And then tweak the automation later! But I WILL get this to work, as I hate to give up! And I want to mark something as solution here as well so others will benefit :slight_smile:

I know, unfortunately official documentation is not very…comprehensive, and many times it’s easier to search for actual examples from somewhere else :confused:

1 Like