Current "sunrise" or "sunset" state?

Hey all, i’m updating and app of mine to use some newer APIs available to streamline the app. Was wondering if you all could help.

Is it possible to read the current state of the sun at the hub location? I was thinking something like:

if (location.latestValue("sunrise"))  {
*action here*

Not sure if this is possible, and i have tried many variations of the above snippet and can’t seem to get the right syntax. Any help would be appreciated!! :smile:

1 Like

You can do something like this, though I’ll warn you it may not be super helpful:


But, the return value (if there is a value) will always be “true”. A little more helpful would be:


which will return a time. To note, this will be in UTC time.

What I’d recommend would be to subscribe to 2 events to be notified when it is sunrise/sunset:

subscribe(location, "sunrise", setSunrise)
subscribe(location, "sunset", setSunset)

When that happens you could set a flag in the state. Then you could do something like:

if(state.sun == 'sunrise') {
    // action to do after sunrise
} else if(state.sun == 'sunset') {
    // action to do after sunset

Hope that helps!

1 Like

@matthewnohr - Is it possible to get the time in Unix for easier comparison? Subscribing is great - but then you’re left with an unknown state till that event fires.

Edit: I’ve been playing with this quite a bit with no success. It seems the subscribe(location, "sunrise", setSunrise) isn’t working for me.

As I understand it, this will fire at sunrise, however, the value of the event passed to setSunrise() will just be TRUE. If you subscribe to ‘sunriseTime’, the event will include the time of tomorrow’s sunrise. You can store that in state and use it as needed. Not sure if that addresses your question.

Thanks for the reply, @AaronZON
I think I’m able to work around not getting the specific time. I’m now just trying to figure out how to fire an event when it’s sunrise/sunset. The docs are lacking - but the code examples are very easy to understand. Unfortunately, it doesn’t work for me - and to test, it takes basically a full day to wait for when you think the event will fire.

I’m trying to update my app for publication. It had previously just polled weather once a day to figure out the next time it should run the methods. The new method is much cleaner (if I could get it working) - albeit much harder to test.

UPDATE: Found the issue. Had to troll ST log to see I wasn’t passing the evt to the subscribed method. Doh!

1 Like

Thanks @AaronZON for helping here. You’re becoming the sunrise/sunset expert!

Here’s another post with more details on sunrise/sunset: Sunrise/Sunset magic?

1 Like