Sunrise sunset

Started by jmburton2001, April 04, 2021, 09:01:08 AM

Previous topic - Next topic

jmburton2001

Has anyone ever used sunrise and sunset as a trigger to run a script? I currently have a batch file that I can run from a command prompt, so I set it up in Task Manager. I have to go into Task Manager every few days and manually change the execution time to mimic sunrise and sunset.

I can also run this batch file through Winbatch but I'd need it to run at sunrise and sunset.

All of that to ask -> how can I get the sunrise and sunset times for my location so I can use it in a script?


td

There are several, maybe many, sites that offer sunrise/sunset information for any lat/longs. Some also offer annual tables.  There are also several open-source astronomical software packages that do the math for you. I use one written in Python on one of my Debian Linux Rasberry Pis but unless you want to install Python on your system it is not of much use to you. There are several Github projects that purport to do the job including C# .Net projects. You could check those out. 

In short, perform a Web search and you eventually find something useful or you can wait to see if a forum member reports a useful solution.

FWIW, We do have an astronomical extender on the to-do list but don't know when or if it will ever get implemented.
"No one who sees a peregrine falcon fly can ever forget the beauty and thrill of that flight."
  - Dr. Tom Cade

JTaylor

No knowledge of this site but looks like it has possibilities...

         https://sunrise-sunset.org/api

If you still need to change Task Manager there ways are to automate that...at least I assume that can still be done in Win10.

Jim

td

It is also possible to perform the calculations in pure WinBatch given the latitude, longitude, and the sun's zenith. However, it's a lot of arithmetic. 
"No one who sees a peregrine falcon fly can ever forget the beauty and thrill of that flight."
  - Dr. Tom Cade

jmburton2001

Quote from: JTaylor on April 04, 2021, 07:50:46 PM
No knowledge of this site but looks like it has possibilities...

         https://sunrise-sunset.org/api

If you still need to change Task Manager there ways are to automate that...at least I assume that can still be done in Win10.

Oh. My. Goodness. That's perfect!  ;)

I just need want to run a simple batch file at sunrise and sunset. I'm doing this on an old Win 7 Pro machine so updating the task should be doable. Worst case scenario is deleting the previous task and creating a new one with the updated execution time.

Quote from: td on April 05, 2021, 07:21:34 AM
It is also possible to perform the calculations in pure WinBatch given the latitude, longitude, and the sun's zenith. However, it's a lot of arithmetic.

This project is so trivial that it only requires the most basic scripting. If there were no solution (or an extremely complex solution), I'd continue to go into Task Manager and manually update the execution times. I only use it sporadically for a few months at a time throughout the year.

ROFL -> Think about this... I'm so lazy I'm trying to figure out how to "set it and forget it" instead of exerting the (less than a minute) time and effort it would take me to manually change it every five days or so.  ::)

Thank you both for your insights! Once again, they were invaluable!

JTaylor

If you change your mind take a look at
       
        schtasks.exe

It has the necessary command line options to manage tasks.   Just  run "schtasks.exe /?" from the command prompt to see the options.

Jim

td

Don't know that there is any interest in this sort of thing. But math can be fun and needing a  distraction, I hack this script together last evening. It is a combination of somebody else's algorithm laying around on the workstation begging to be converted to WIL and a few UDF's stolen from other projects. The times are off by a couple of minutes but I am too lazy to figure out why. Per as usual typos and bugs are provided at no extra charge.

Code (winbatch) Select
;;; SunriseSet.wbt
gosub UDPS ; Define functions

; Convert longitude to hour.
longitude = -122.69  ; Longitude is positive for East and negative for West.
latitude  =  47.66
zenith    = 90.8 ; Rough guess. Should be caclulated.
Date      = TimeYmdHms()

SunRise = SunRiseSetTime( longitude, latitude, zenith, Date, @True)
SunSet  = SunRiseSetTime( longitude, latitude, zenith, Date, @False)
Message("Today's Sunrise and SunSet", 'Rise ':SunRise:@lf:'Set  ': SunSet)

exit

:UDPS   ; User-defined procedure definitions.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; SunRiseSetTime
;;   Calculates sunrise or sunset for the
;;   given location on the given date.
;;
;; Intput - longitude: longitude of the location to calculate(Positive
;;                      for East and negative for West)
;;          latitude:  latitude of location to calculate
;;          zenith:    sun's zenith at location
;;          date:      date to calculate for
;;          bRise:     @True to return sunrise @False for sunset
;;
;; Returns - hour:minute:second am/pm of sunrise or set.
;;         
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#DefineFunction SunRiseSetTime( _longitude, _latitude, _zenith, _Date, _bRise)
   Doy=DayOfYear(_Date)

   lngHour = _longitude / 15
   if _bRise then t = Doy + ((6 - lngHour) / 24)
   else t = Doy + ((18 - lngHour) / 24)
   
   ; Calculate the Sun's mean anomaly.
   m = (0.9856 * t) - 3.289
   
   ; Calculate the Sun's true longitude.
   l = ((m + (1.916 * sin(m*@Deg2Rad)) + (0.020 * sin(2 * m*@Deg2Rad)) + 282.634))
   if l > 360 then l -= 360
   else if l < 0 then l += 360
   
   ; Calculate the Sun's right ascension.
   ra = (atan(0.91764 * tan(l*@Deg2Rad)))* @Rad2Deg
   
   ; Right ascension value needs to be in the same quadrant as L
   Lquadrant  = (floor( l/90)) * 90
   RAquadrant = (floor(ra/90)) * 90
   ra = ra + (Lquadrant - RAquadrant)
   
   ; Right ascension value needs to be converted into hours.
   ra = ra / 15
   
   ; Calculate the Sun's declination.
   sinDec = 0.39782 * sin(l*@Deg2Rad)
   cosDec = cos(asin(sinDec))
   
   ; Calculate the Sun's local hour angle using the zenith.
   csH = (cos(_zenith*@Deg2Rad) - (sinDec * sin(_latitude*@Deg2Rad)) / (cosDec * cos(_latitude*@Deg2Rad)))
   if (csH  >  1)
      Message('SunRiseSetTime', 'the sun never rises at this location (on the specified date)')
      return 0
   elseif (csH  < -1)
      Message('SunRiseSetTime', 'the sun never sets at this location (on the specified date)')
      return 0
   endif
   
   ; Finish calculating H and convert into hours.
   if _bRise then H = 360 - (acos(csH )/@Deg2Rad)
   else H =  acos(csH)/@Deg2Rad
   H /= 15
   
   ; Calculate the local mean time of rising/setting.   
   T = H + ra  - (0.06571 * t) - 6.622
   
   ; Adjust back to UTC
   UT = T - lngHour ;
   
   ;NOTE: UT potentially needs to be adjusted into the range [0,24) by adding/subtracting 24.
   if UT < 0 then UT += 24
   else if UT > 24 then UT -= 24
   
   LT = TimeFloatToHms(UT, _Date)
   LT = TimeAdjustCurrentZone(LT)
   LT = TimeFormat(LT, 'hh:mm:ss t')
   
   return LT ; Finally.
#EndFunction

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Day of the year
;; Input - Today's date in YMDHMS
;;
;; Return - the day of the year
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#DefineFunction DayOfYear(_ToDate)
    ThisYear=ItemExtract(1,_ToDate,":")
    JanFirst="%thisyear%:01:01:00:00:00"
    JanFirstJulian=TimeJulianDay(JanFirst)
    ToJulian=TimeJulianDay(_ToDate)
    doy=ToJulian-JanFirstJulian+1
    return (doy)
#EndFunction

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; TimeAdjustCurrentZone
;; Input - WIL YMDHMS UTC time.
;;
;; Returns - WIL YMDHMS time converted to local
;;           time.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#DefineFunction TimeAdjustCurrentZone(_strUtcTime)
   nActiveBias =  RegQueryDword(@regmachine,"SYSTEM\CurrentControlSet\Control\TimeZoneInformation[ActiveTimeBias]", 0)
   If nActiveBias >= 0
      Return TimeSubtract(_strUtcTime,"0000:00:00:00:":nActiveBias:":00")
   Else
      Return TimeAdd(_strUtcTime,"0000:00:00:00:":Abs(nActiveBias):":00")
#EndFunction

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Floating point time of day to date.
;; Input - Floating point time of day
;;         Date of day
;;
;; Return - Current YMDHMS date using input 
;;           time of day.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#DefineFunction TimeFloatToHms(_FloatHour, _now)
   Hour   = floor(_FloatHour)
   Rem    = _FloatHour - Hour
   Minu   = floor(Rem*60)
   Rem    = (Rem*60) - Minu
   Sec    = floor(Rem * 60)
   Result = ItemReplace(Int(Hour), 4, _now, ':')
   Result = ItemReplace(Int(Minu) , 5, Result, ':')
   Result = ItemReplace(Int(Sec), 6, Result, ':')
   return Result
#EndFunction

return ; UDP gosub return.
"No one who sees a peregrine falcon fly can ever forget the beauty and thrill of that flight."
  - Dr. Tom Cade

td

Found the source of the algorithm so giving credit where credit is due,

   Almanac for Computers, 1990
   published by Nautical Almanac Office
   United States Naval Observatory
   Washington, DC 20392

   and Ed Williams (ATP-MEL Comm-SEL CFII)
"No one who sees a peregrine falcon fly can ever forget the beauty and thrill of that flight."
  - Dr. Tom Cade

kdmoyers

<<is any interest in this sort of thing>>
Love this solution.  It is, after all, a predictable thing. 

In my reading, people use various values for that zenith.  I saw 90.833 on this page: https://www.esrl.noaa.gov/gmd/grad/solcalc/solareqns.PDF
Maybe that accounts for the few minutes difference?

If I use 91.5, I agree with google.

-Kirby
The mind is everything; What you think, you become.

stanl

The interesting thing about the site Jim referenced:  if you run the API query [with your own lat/long]


https://api.sunrise-sunset.org/json?lat=35.608237&lng=-78.647497&formatted=0


it gives UTC:


{"results":{"sunrise":"2021-04-06T10:52:34+00:00","sunset":"2021-04-06T23:40:53+00:00","solar_noon":"2021-04-06T17:16:44+00:00","day_length":46099,"civil_twilight_begin":"2021-04-06T10:26:45+00:00","civil_twilight_end":"2021-04-07T00:06:43+00:00","nautical_twilight_begin":"2021-04-06T09:56:08+00:00","nautical_twilight_end":"2021-04-07T00:37:19+00:00","astronomical_twilight_begin":"2021-04-06T09:24:40+00:00","astronomical_twilight_end":"2021-04-07T01:08:48+00:00"},"status":"OK"}





just take off formatted=0
https://api.sunrise-sunset.org/json?lat=35.608237&lng=-78.647497



{"results":{"sunrise":"10:52:34 AM","sunset":"11:40:53 PM","solar_noon":"5:16:44 PM","day_length":"12:48:19","civil_twilight_begin":"10:26:45 AM","civil_twilight_end":"12:06:43 AM","nautical_twilight_begin":"9:56:08 AM","nautical_twilight_end":"12:37:19 AM","astronomical_twilight_begin":"9:24:40 AM","astronomical_twilight_end":"1:08:48 AM"},"status":"OK"}




td

Quote from: kdmoyers on April 06, 2021, 01:04:38 PM
If I use 91.5, I agree with google.

Tried the 91.5 and it makes the calculations for sunrise accurate within about 30 seconds and the sunset to within 3 seconds. I am using the Pyephem library output for comparison. That library is based on the "libastro" Unix library with accuracy down to about 1 arcsecond.  There is a newer Python astronomy library with even more accuracy but is also much more computationally intensive. Now I am wondering if adding a few more digits to the longitude and latitude may get it even closer.
"No one who sees a peregrine falcon fly can ever forget the beauty and thrill of that flight."
  - Dr. Tom Cade

JTaylor

Probably should get it closer or else your vampire customers may become very cross with you.

Jim

kdmoyers

Or make it way off and eliminate your vampire customers altogether!
-Kirby
The mind is everything; What you think, you become.

td

"No one who sees a peregrine falcon fly can ever forget the beauty and thrill of that flight."
  - Dr. Tom Cade

JTaylor

Yeah but that would create a lot of openings on the graveyard shift and most people don't like filling those slots.

Jim

jmburton2001

All of this discussion is why I love this board.

If you hadn't already figured it out... this is for starting (sunrise) and stopping (sunset) an outdoor camera's "bird watching" recordings. I have a tripod mounted Hikvision that I set up when I get the notion and use a batch file to turn off the recording software at night and then turn it back on in the morning. Birds are funny, interesting, and I thoroughly enjoy them!  :D

There were a few occasions the last time I set it up that I missed their morning antics because I didn't adjust the times.  ::)

ChuckC

Unless the camera is low-light / night-vision, would an alternative solution using a sensor to detect sufficient daylight for taking pictures/video work better than strictly adhering to the local sunrise/sunset times?  I'm thinking of situations where cloud cover present at dawn/dusk would make pre-dawn and post-sunset time periods unsuitable for bird watching.

kdmoyers

Whoa whoa whoa Chuck... that almost sounds like your are suggesting... (whispers) hardware.
Please! This is a family forum!

(but seriously, how would one rig that up? some sort of USB thing?)
The mind is everything; What you think, you become.

stanl

Again, referencing the site Jim brought up...  a simple Power Query to https://sunrise-sunset.org/calendar?location=Raleigh&month=April&year=2021


gets [excel file in attached zip]. Could be automated in WB with variable location / month / year

jmburton2001

Quote from: ChuckC on April 07, 2021, 12:07:13 PM
Unless the camera is low-light / night-vision, would an alternative solution using a sensor to detect sufficient daylight for taking pictures/video work better than strictly adhering to the local sunrise/sunset times?  I'm thinking of situations where cloud cover present at dawn/dusk would make pre-dawn and post-sunset time periods unsuitable for bird watching.

Birds continue their shenanigans (and their entertainment value) whether there's cloud cover or not. Most of them settle down around sunset and then start up again in the morning. It seems that they're most active just after they drag themselves out of bed and just before they retire. Cloud cover and semi-bad weather don't appear to affect them.

The camera is night vision and detects the ambient light and then switches on its IR emitter and continues to stream in low/no light conditions. I can go in and change its "active" hours but I'm in the same boat as far as having to go in occasionally and change them. There's no easy way to do that programmatically.

The recording software on the other hand is very configurable as far as zones, motion detection, etc. It can also be told to ignore or acknowledge the video stream through the aforementioned batch file. If I don't disregard the video stream overnight, every moth, or other insect, that comes to check out the IR emitter triggers a recording. That's just a waste of drive writes and processor cycles.

Occam's razor suggests that running that batch file at sunrise and sunset is the simplest solution...  ;)

td

I solved that problem with my weather cam by using its sensitivity feature. But is an old pre-cloud (a.k.a. pre-corporate-spyware/servalanceware) model. I do catch the occasional hummingbird. We have a lot of them year-round in this part of North America and they seem to like to check out the camera by hovering in front of the enclosure.
"No one who sees a peregrine falcon fly can ever forget the beauty and thrill of that flight."
  - Dr. Tom Cade