What I want to achieve:
I have a terrarium full of plants that normally reside in tropical or sub-tropical areas. I thought it would be pretty cool to give them a daylight cycle that is the same as some place close to the equator. So I want the lights to turn on when the sun goes up at some specified place and turn off when the sun sets.
What I have done:
I found an open API that gives me sunrise and sunset times as JSON (for some random spot in Africa), here: https://api.sunrise-sunset.org/json?lat=9.757452&lng=16.415384
I use the RESTful integration to “extract” the variables sunrise and sunset respectively to two entities that I call “sensor.sun_tropic_sunrise” and “sensor.sun_tropic_sunset”.
This is where I am lost. I have tried a couple of different ways I found here on the forum, one was using a template for the “action” that had an if-else-clause checking if the current time is before or after sunset and sunrise, setting switch off or on. That partly worked; I got it to print the right switch state but it never triggered. I can’t remember what I set the trigger to… I believe I even tried setting trigger to template sensor.sun_tropic_sunrise == True and still nothing.
I’ve also tried this:
trigger:
- platform: time
at: "{{ as_datetime(states('sensor.sun_tropic_sunset')[:19]) }}"
Set the device_class of both sensors to timestamp and ensure the reported date and time are in ISO format. This allows them to be referenced directly by a Time Trigger.
Then it’s very easy to create a simple automation from this:
- id: run_scene_at_sunset
alias: Turn on lights at sunset
trigger:
- platform: state
entity_id: binary_sensor.daytime
from: 'on'
to: 'off'
condition: []
action:
blah blah
sun2 allows you to adjust how you define day and night in various ways - I use elevation as it’s most accurate for lights where I live, but you may want to tune it as you see fit.
How does sun2 know it’s supposed to track the sun’s position? Does adding the features latitude, longitude, elevation and time_zone make home assistant automatically treat it as a sun “object” at the given location?
I used this last night and this morning the light went on just as planned! Thanks! BTW I added a timedelta to get it from UTC to my time by appending this:
..... .isoformat() + as_timedelta('02:00:00')
I’m sure the sun2 as recommended below would work just as well, but this is the one I went for.
You’re welcome but it appears you have misunderstood the purpose of the Solution tag.
You marked your own post with the Solution ta using the solution I had suggested. It’s the community’s custom to assign the Solution tag to the first post that answers/resolves the original question/problem.