Trigger Template For Sunset Offset

I want to trigger an automation having a random offset after sunset. I got some help but still not working.

I want to trigger the automation having a random offset between 5 and 25 minutes after sunset.

trigger:
    platform: template
    value_template: "{{ states('sensor.time') == (as_timestamp(state_attr('sun.sun','next_setting')) + (range(5,25)|random|int )) | timestamp_custom('%H:%M', False) }}"  

I would rather try fixed trigger (at sunset) and then random delay as the first step of the automation.

2 Likes

There’s a potential problem with a trigger that employs a random time because there’s a chance that it may never trigger.

The template is evaluated every minute and each time the random function generates a different value within the range. Imagine that it is evaluated when the time is 6 minutes after sunset but the random value at that moment is 10. It won’t trigger because 6 < 10.

Now the time is 7 minutes past sunset and the random value is 22. Once again, it won’t trigger because 7 < 22. Now it’s 8 minutes after sunset and the random value is 16. Again, no trigger.

You can see how this pattern can continue for quite awhile before the time is finally greater than the random value. You can also see that there’s a possibility that the random value is always greater than the time and never causes a trigger.

Anyway, if that doesn’t deter you from using a random value in a trigger, you can try this:

Try this:

trigger:
- platform: template
  value_template: "{{ utcnow() > as_datetime(state_attr('sun.sun', 'next_setting')) + timedelta(minutes = range(5,26)|random) }}"  

However, konradr’s suggestion circumvents the problem I explained and shifts the randomness out of the trigger and into the action (using a delay). Just be aware that if Home Assistant restarts while a delay is in progress (or automations are reloaded), the delay will be terminated and whatever actions come after the delay are not executed.

trigger:
- platform: sun
  event: sunset
action:
- delay:
    minutes: '{{ range(5,26) | random }}'
... etc ...

EDIT

I overlooked to mention that there’s another potential problem with using a random time value in a Template Trigger is that it can trigger more than once during the time range of 5 to 25 minutes after sunset.

2 Likes

Thanks for the feedback and explanation. I did what @konradr suggested. It’s a simple solution and it accomplishes what I needed. Thanks!