How to trigger automation BEFORE set time?

I reinstalled Hass.io from scratch (updated from resinos to hassos) and at the same time I wanted to do a transition from traditional yaml to lovelace (including automations). And now everything works, except my car heater automation, where I want those automations to trigger X minutes BEFORE set time in UI. Basically, I set up time when I am going to leave from home in UI, and then, based on outdoor temperature (celcius), the car heater turns itself on 3, 2 or 1 hour before, like this:

  1. If outdoor temperature is below -10, then turn on heater 3 hours before
  2. If outdoor temperature is above -10 but below -5, then turn on heater 2 hours before
  3. If outdoor temperature is above -5 but below 2, then turn on heater 1 hour before

With yaml automations I got this to work (using three different automations because I donā€™t know how I could put all those conditions in one automation), but now in Lovelace, where everything should be oh so smooth and easy :wink: I donā€™t seem to get this to work. I think itā€™s because of my trigger that for some reason gets broken in Lovelace because it has several lines.

My trigger (in yaml) is:

    trigger:
      - platform: template
        value_template: >
          {% set d = now().strftime("%m/%d/%Y ") %}
          {% set t = strptime(d+states.sensor.alarm_clock3_time_long.state,"%m/%d/%Y %H:%M") %}
          {{ states('sensor.time') == ( as_timestamp(t) - 180*60 )|timestamp_custom('%H:%M') }}`

And that used to work. That 180 * 60 means three hours, and I just had three of these (in three different automations), one had 120 * 60 and one had 60 * 60 respectively. But when I enter that in Lovelace automation in YAML mode, it switches to UI mode and then it looks like this (and yaml gets messed up as well):
hassiokoodi
So I think my problem is that I havenā€™t figured out how to put multiple lines in Lovelace automation trigger correctly :confused: But at the same time, I cannot help but think that it should be possible to do this automation a bit easier than using three different automationsā€¦ And also that why donā€™t HASS support ā€œnegative delayā€? :slight_smile: It would be so much easier just to use -3:00:00 in delay so that automation would trigger three hours before given timeā€¦ :slight_smile:

1 Like

I would make a trigger for every minute and add multiple or conditions. Lovelace shouldnā€™t change how automations work.

Could you give me an example of how to do that?

I was thinking something like thisā€¦just add the action and change the condition sensor to whatever outdoor temperature sensor you are using. Note, I havenā€™t tested this but it should get you going. If not, Iā€™ll help out more tomorrow.

  - alias: 'Turn Car on'
    initial_state: on
    trigger:
      platform: time_pattern
      minutes: '/1'
      seconds: '0'
    condition:
      condition: or
      conditions:
        - condition: template
          value_template:  >-
            {% set temp = states.sensor.temperature.state %}
            {% set d = now().strftime("%m/%d/%Y ") %}
            {% set t = strptime(d+states.sensor.alarm_clock3_time_long.state,"%m/%d/%Y %H:%M") %}
            {% if states('sensor.time') == ( as_timestamp(t) - 180*60 )|timestamp_custom('%H:%M') and temp <= -10 %}true{%else%}false{% endif %}
    action:
      - service: ...
1 Like

Do I get it right that youā€™re trying to use Automation Editor and it does not allow you to achieve the result you could achieve previously by editing your automation.yaml? Iā€™m using HA in Lovelace mode but change all my configs manually.
Why donā€™t you carry on with the latter?
Also, where are the three automations youā€™re talking about - I can only see one trigger. Do post them here.

And what is that sensor.alarm_clock3_time_long?

P.S I think this topic is more suitable to Configuration than to Hass.io

Good for you, but some less experienced members do not yet have this as an option, they need to get up to speed in their own way (though I do admit that it limits what assistance they can get as only a few members are battling with the new gui editors)

The OP asked for an example, that is what Jer78 provided, he also explained his concept. This is to allow the OP to compare what he asked for with the example, see how it is done and extend it. This is to help the OP grow. Itā€™s often best not to give them a fish but show them how to fish.

AND yes you are right that this 'should have been under configuration, all new members should read the guidelines FAQ - Home Assistant Community but also (and more importantly in my book) the sticky by Tinkerer at the top of the forum.

Edit: though looking at his profile, heā€™s been a member nearly as long as you (Mar 2018) everyone delelops at their own pace and some simply canā€™t devote that much time to a hobby.

Edit2: Though it would be nice if at the end of the solution the OP posted back the full automation as this shows that he has understood the advice given and itā€™s there as a resource to the next guy.
It would also be very nice if he credited Jer78 with the solution (which is rarely the actual finished code, but the post that gave them the biggest clue to solving the problem)

Eh? Did I do anything wrong here? 8()

Thanks for replies, I have been trying to get this to work without success. Also apologies if this went into wrong thread :confused: I have been here for a while, yes, but I set up all my automations back in the day and then left them as they were as everything worked perfect :slight_smile: But now because I installed new version of Home Assistant and switched to SSD drive, and because I eventually decided to build everything up from scratch, I thought that using Lovelace in everything wasā€¦ simpler and also preferred method of using HASS nowadays (no need to worry about formatting etc), but I guess thatā€™s not the caseā€¦

For me, this automation for my car heater is the only thing I cannot get to work. And it seems like now even my old code doesnā€™t work anymore when I just paste it into configuration.yaml. AhmadK, I had that sensor.alarm_clock3_time_long in my old code and it worked. But letā€™s focus on my new code as itā€™s tidier :slight_smile: and the code that Jer78 kindly typed.

This is what I have in sensors now:

sensor:
  - platform: template
    sensors:  
      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) }}

Then, this is the automation part, the code Jer78 provided (I gave in and put this in configuration.yaml, as it is much clearer compared to Lovelace automation when things are a bit complicated like in this automationā€¦):

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

automation old:
  - alias: 'Turn Car on'
    initial_state: on
    trigger:
      platform: time_pattern
      minutes: '/1'
      seconds: '0'
    condition:
      condition: or
      conditions:
        - condition: template
          value_template:  >-
            {% set temp = states.sensor.sonoffth3_am2301_temperature.state %}
            {% set d = now().strftime("%m/%d/%Y ") %}
            {% set t = strptime(d+states.sensor.alarm_clock3_time.state,"%m/%d/%Y %H:%M") %}
            {% if states('sensor.time') == ( as_timestamp(t) - 180*60 )|timestamp_custom('%H:%M') and temp >= -10 %}true{%else%}false{% endif %}
    action:
      - service: switch.turn_on
        entity_id: switch.sonoffpow3_2
      - delay: '03:00:00'
      - service: switch.turn_off
        entity_id: switch.sonoffpow3_2

I have to say that I have no clue about those time conversions and there is probably a simple reason why this automation never triggersā€¦ Note that I changed condition for temperature to above -10 so it would trigger when I want (itā€™s warmer than that now :slight_smile: ).

No, absolutely not. I was merely explaining why Jer78 did what he did and why it did not ā€˜tickā€™ all your boxes. No blame to be placed, just an alternate perspective. :smiley:

Okay, Jer78 is Canadian so heā€™s probably at work now, give me 10 mins and Iā€™ll sit down at a workstation. I can explain what I think can be optimised and what I think is redundant.
A couple of questions though : - you have two input numbers set up, one for hours and one for minutes - why ? - I mean you could just use an input datetime ? Then thereā€™s the creation of this sensor in the first place (my own method would use a binary sensor but that was a completely different path and there are many ways to skin a cat) Jer78ā€™s method sets an automation that fires every minute, tests conditions and then determines actions. You merely use you ā€˜set timeā€™ in here.
How do you present this in your front end ?
Some people like to use input number sliders because itā€™s easier when used from a phone (for instance) so your two input number 's may be valid for your usage.
Another point, say its -11 at -3hrs but itā€™s -7 at -2hrs and -4 at -1hrs - what do you think should happen ?
Oh and does this only run on weekdays?

But my ā€˜boxesā€™ were addressed to the OP :wink:
Anyway, no worries.

Hello Mutt,

Hereā€™s how it looks like in my front end (or the idea, I will clean it later when it works :slight_smile: ):
sliders

So yes, thatā€™s why I use two input numbers. I set time when I want to leave home, and then automation warms up my car as needed beforehand. As for creating the sensor, I thought thatā€™s what needs to be done so I can form time from hour and minute values? And then I could use alarm_clock3_time for something else as well if needed.

I am not 100% sure I understand why automation needs to be fired every minute (well, I guess it isnā€™t as like you said, there are many ways to skin a cat :slight_smile: ), but if I have understood right, somehow using that method I can get by using only one automation instead of three that I used to have (1: start heater 3 hours earlier if temperature is below -10, 2: start heater 2 hours earlier if temperature is between -10 and -5 and 3: start heater 1 hour earlier if temperature is between -5 and +2)? That would be great :slight_smile:

This is meant to run whenever I want, not only weekdays, earlier I just toggled automation on or off as needed. As for your point about if temperature changes like thatā€¦ Yes, earlier none of my three automations fired in case of your scenario, but luckily that didnā€™t happen often :slight_smile:

Solved this awhile back

EDIT: The whole thread has about 80 different ways to solve the problem.

This being the final condition i believe.

Oh, thank you petro! I donā€™t know how I didnā€™t find THAT thread since OP there wants to do exactly the same as me, but maybe thatā€™s because I started to search for Lovelace solutionsā€¦

And I am sure there are many different ways to solve this problem, but to me they all seem overly complicated considering that itā€™s pretty simple thing I want to achieve, just trigger something early based instead of delayed, and I thought as time has passed, Lovelace introduced quite a while back already etc etc, that there would be some simple solution to this kind of problem already that I just wasnā€™t aware of :slight_smile: Well, maybe one day there will be ā€œnegative delayā€ in HASS out-of-box :slight_smile:

Anyway, I am going to read that thread now and return back if (and hopefully when!) I get my automation working.

What you want to do is not simple. Anytime you want to do something dynamically in any software package, it changes the process from simple to complex.

And yet there are only ā€œ50 ways to leave your loverā€ :rofl:

1 Like

All right, I have tried pretty much everything here and although configuration seems always to be okay, the automation just does not trigger. So I figured out I should use template editor and test those things that I suspect might cause problems. I ended up using code that @Jer78 gave because that seems to give right values for me, for example this template here:

value_template:  >-
  {% set temp = states.sensor.sonoffth3_am2301_temperature.state %}
  {% set d = now().strftime("%m/%d/%Y ") %}
 {% set t = strptime(d+states.sensor.alarm_clock3_time.state,"%m/%d/%Y %H:%M") %}
 {% if states('sensor.time') == ( as_timestamp(t) - 180*60 )|timestamp_custom('%H:%M') and temp >= -10 %}true{%else%}false{% endif %}

I get right values from every variable until last line. see here:

Now, when sensor.time is exactly three hours before set time (that is, when this automation should trigger), template editor just returns ā€œunknown error rendering templateā€. When that minute passes, template shows values again. So I think thereā€™s something wrong with that if-statement but I have no idea what it isā€¦ :confused:

read the errors from your logs. Also your spacing is off. And youā€™re comparing a string to a float. This can also be optimized.

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

All right, I have some errors in my logs but I assume thatā€™s because of one binary sensor experiment still active (that error fires off once every minute). I will comment that part out, and probably everything else regarding this as well, as I am quitting for today I think :confused: 80 ways to do this and I cannot get even one way to work, greatā€¦

Spacing was off only in my post, in configuration.yaml it is right.

I tried that value_template provided by @petro but that gives strange error when I try to validate my code. It says: "Invalid config for [automation]: invalid template (TemplateSyntaxError: unexpected ā€˜}ā€™, expected ā€˜)ā€™) for dictionary value @ data[ā€˜triggerā€™][0][ā€˜value_templateā€™]. Got None. (See /config/configuration.yaml, line 230). "

Well, on line 230 there is nothing but empty line :confused: When I comment out those three lines under that value_template, then my code is valid again. But those rows are on lines 262-264ā€¦

Post your entire code.