1 // sg_time.cxx -- data structures and routines for managing time related stuff.
3 // Written by Curtis Olson, started August 1997.
5 // Copyright (C) 1997 Curtis L. Olson - curt@infoplane.com
7 // This library is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU Library General Public
9 // License as published by the Free Software Foundation; either
10 // version 2 of the License, or (at your option) any later version.
12 // This library is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 // Library General Public License for more details.
17 // You should have received a copy of the GNU Library General Public
18 // License along with this library; if not, write to the
19 // Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 // Boston, MA 02111-1307, USA.
25 #include <simgear/compiler.h>
27 #include <errno.h> // for errno
29 #ifdef SG_HAVE_STD_INCLUDES
41 #ifdef HAVE_SYS_TIMEB_H
42 # include <sys/timeb.h> // for ftime() and struct timeb
45 # include <unistd.h> // for gettimeofday()
47 #ifdef HAVE_SYS_TIME_H
48 # include <sys/time.h> // for get/setitimer, gettimeofday, struct timeval
51 #include <simgear/constants.h>
52 #include <simgear/debug/logstream.hxx>
53 #include <simgear/misc/sg_path.hxx>
55 #include "sg_time.hxx"
57 #include "lowleveltime.h"
60 #define DEGHR(x) ((x)/15.)
61 #define RADHR(x) DEGHR(x*SGD_RADIANS_TO_DEGREES)
64 static const double MJD0 = 2415020.0;
65 static const double J2000 = 2451545.0 - MJD0;
66 static const double SIDRATE = 0.9972695677;
69 SGTime::SGTime( double lon, double lat, const string& root )
71 SG_LOG( SG_EVENT, SG_INFO, "Initializing Time" );
75 cur_time = time(NULL);
76 cout << "Current greenwich mean time = " << asctime(gmtime(&cur_time))
78 cout << "Current local time = "
79 << asctime(localtime(&cur_time)) << endl;
81 if ( root != (string)"" ) {
83 zone.append( "zone.tab" );
84 SG_LOG( SG_EVENT, SG_INFO, "Reading timezone info from: "
86 tzContainer = new TimezoneContainer( zone.c_str() );
88 GeoCoord location( SGD_RADIANS_TO_DEGREES * lat, SGD_RADIANS_TO_DEGREES * lon );
89 GeoCoord* nearestTz = tzContainer->getNearest(location);
92 name.append( nearestTz->getDescription() );
93 zonename = strdup( name.c_str() );
94 SG_LOG( SG_EVENT, SG_INFO, "Using zonename = " << zonename );
96 SG_LOG( SG_EVENT, SG_INFO, "*** NO TIME ZONE NAME ***" );
103 SGTime::SGTime( const string& root ) {
104 SGTime( 0.0, 0.0, root );
109 SGTime( 0.0, 0.0, "" );
115 if ( tzContainer != NULL ) {
119 if ( zonename != NULL ) {
125 // given Julian Date and Longitude (decimal degrees West) compute
126 // Local Sidereal Time, in decimal hours.
128 // Provided courtesy of ecdowney@noao.edu (Elwood Downey)
129 static double sidereal_precise( double mjd, double lng )
131 /* printf ("Current Lst on JD %13.5f at %8.4f degrees West: ",
134 // convert to required internal units
135 lng *= SGD_DEGREES_TO_RADIANS;
137 // compute LST and print
138 double gst = sgTimeCalcGST( mjd );
139 double lst = gst - RADHR( lng );
140 lst -= 24.0 * floor( lst / 24.0 );
141 // printf ("%7.4f\n", lstTmp);
147 // return a courser but cheaper estimate of sidereal time
148 static double sidereal_course( time_t cur_time, struct tm *gmt, double lng )
150 time_t start_gmt, now;
151 double diff, part, days, hours, lstTmp;
155 start_gmt = sgTimeGetGMT(gmt->tm_year, 2, 21, 12, 0, 0);
157 SG_LOG( SG_EVENT, SG_DEBUG, " COURSE: GMT = "
158 << sgTimeFormatTime(gmt, tbuf) );
159 SG_LOG( SG_EVENT, SG_DEBUG, " March 21 noon (GMT) = " << start_gmt );
161 diff = (now - start_gmt) / (3600.0 * 24.0);
163 SG_LOG( SG_EVENT, SG_DEBUG,
164 " Time since 3/21/" << gmt->tm_year << " GMT = " << diff );
166 part = fmod(diff, 1.0);
168 hours = gmt->tm_hour + gmt->tm_min/60.0 + gmt->tm_sec/3600.0;
170 lstTmp = (days - lng)/15.0 + hours - 12;
172 while ( lstTmp < 0.0 ) {
176 SG_LOG( SG_EVENT, SG_DEBUG,
177 " days = " << days << " hours = " << hours << " lon = "
178 << lng << " lst = " << lstTmp );
184 // Update the time related variables
185 void SGTime::update( double lon, double lat, long int warp ) {
186 double gst_precise, gst_course;
188 SG_LOG( SG_EVENT, SG_DEBUG, "Updating time" );
190 // get current Unix calendar time (in seconds)
191 // warp += warp_delta;
192 cur_time = time(NULL) + warp;
193 SG_LOG( SG_EVENT, SG_DEBUG,
194 " Current Unix calendar time = " << cur_time
195 << " warp = " << warp );
197 // get GMT break down for current time
198 gmt = gmtime(&cur_time);
199 SG_LOG( SG_EVENT, SG_DEBUG,
200 " Current GMT = " << gmt->tm_mon+1 << "/"
201 << gmt->tm_mday << "/" << gmt->tm_year << " "
202 << gmt->tm_hour << ":" << gmt->tm_min << ":"
205 // calculate modified Julian date
206 // t->mjd = cal_mjd ((int)(t->gmt->tm_mon+1), (double)t->gmt->tm_mday,
207 // (int)(t->gmt->tm_year + 1900));
208 mjd = sgTimeCalcMJD( (int)(gmt->tm_mon+1), (double)gmt->tm_mday,
209 (int)(gmt->tm_year + 1900) );
211 // add in partial day
212 mjd += (gmt->tm_hour / 24.0) + (gmt->tm_min / (24.0 * 60.0)) +
213 (gmt->tm_sec / (24.0 * 60.0 * 60.0));
215 // convert "back" to Julian date + partial day (as a fraction of one)
217 SG_LOG( SG_EVENT, SG_DEBUG, " Current Julian Date = " << jd );
219 // printf(" Current Longitude = %.3f\n", FG_Longitude * SGD_RADIANS_TO_DEGREES);
221 // Calculate local side real time
222 if ( gst_diff < -100.0 ) {
223 // first time through do the expensive calculation & cheap
224 // calculation to get the difference.
225 SG_LOG( SG_EVENT, SG_INFO, " First time, doing precise gst" );
226 gst_precise = gst = sidereal_precise( mjd, 0.00 );
227 gst_course = sidereal_course( cur_time, gmt, 0.00 );
229 gst_diff = gst_precise - gst_course;
231 lst = sidereal_course( cur_time, gmt, -(lon * SGD_RADIANS_TO_DEGREES) ) + gst_diff;
233 // course + difference should drift off very slowly
234 gst = sidereal_course( cur_time, gmt, 0.00 ) + gst_diff;
235 lst = sidereal_course( cur_time, gmt, -(lon * SGD_RADIANS_TO_DEGREES) ) + gst_diff;
238 SG_LOG( SG_EVENT, SG_DEBUG,
239 " Current lon=0.00 Sidereal Time = " << gst );
240 SG_LOG( SG_EVENT, SG_DEBUG,
241 " Current LOCAL Sidereal Time = " << lst << " ("
242 << sidereal_precise( mjd, -(lon * SGD_RADIANS_TO_DEGREES) )
243 << ") (diff = " << gst_diff << ")" );
247 // Given lon/lat, update timezone information and local_offset
248 void SGTime::updateLocal( double lon, double lat, const string& root )
251 time_t aircraftLocalTime;
252 GeoCoord location( SGD_RADIANS_TO_DEGREES * lat, SGD_RADIANS_TO_DEGREES * lon );
253 GeoCoord* nearestTz = tzContainer->getNearest(location);
255 zone.append ( nearestTz->getDescription() );
259 zonename = strdup( zone.c_str() );
260 currGMT = sgTimeGetGMT( gmtime(&cur_time) );
261 aircraftLocalTime = sgTimeGetGMT( (fgLocaltime(&cur_time, zone.c_str())) );
262 local_offset = aircraftLocalTime - currGMT;
263 // cout << "Using " << local_offset << " as local time offset Timezone is "
264 // << zonename << endl;
268 // given a date in months, mn, days, dy, years, yr, return the
269 // modified Julian date (number of days elapsed since 1900 jan 0.5),
270 // mjd. Adapted from Xephem.
271 double sgTimeCalcMJD(int mn, double dy, int yr) {
274 // internal book keeping data
275 static double last_mjd, last_dy;
276 static int last_mn, last_yr;
281 if (mn == last_mn && yr == last_yr && dy == last_dy) {
286 y = (yr < 0) ? yr + 1 : yr;
292 if (yr < 1582 || (yr == 1582 && (mn < 10 || (mn == 10 && dy < 15)))) {
301 c = (long)((365.25*y) - 0.75) - 694025L;
303 c = (long)(365.25*y) - 694025L;
306 d = (int)(30.6001*(m+1));
308 mjd = b + c + d + dy - 0.5;
319 // given an mjd, calculate greenwich mean sidereal time, gst
320 double sgTimeCalcGST( double mjd ) {
323 double day = floor(mjd-0.5)+0.5;
324 double hr = (mjd-day)*24.0;
327 T = ((int)(mjd - 0.5) + 0.5 - J2000)/36525.0;
328 x = 24110.54841 + (8640184.812866 + (0.093104 - 6.2e-6 * T) * T) * T;
330 gst = (1.0/SIDRATE)*hr + x;
332 SG_LOG( SG_EVENT, SG_DEBUG, " gst => " << gst );
338 #if defined( HAVE_TIMEGM )
339 // ignore this function
340 #elif defined( MK_TIME_IS_GMT )
341 // ignore this function
342 #else // ! defined ( MK_TIME_IS_GMT )
344 // Fix up timezone if using ftime()
345 static long int fix_up_timezone( long int timezone_orig ) {
346 # if !defined( HAVE_GETTIMEOFDAY ) && defined( HAVE_FTIME )
347 // ftime() needs a little extra help finding the current timezone
348 struct timeb current;
350 return( current.timezone * 60 );
352 return( timezone_orig );
358 /******************************************************************
359 * The following are some functions that were included as SGTime
360 * members, although they currently don't make use of any of the
361 * class's variables. Maybe this'll change in the future
362 *****************************************************************/
364 // Return time_t for Sat Mar 21 12:00:00 GMT
366 // On many systems it is ambiguous if mktime() assumes the input is in
367 // GMT, or local timezone. To address this, a new function called
368 // timegm() is appearing. It works exactly like mktime() but
369 // explicitely interprets the input as GMT.
371 // timegm() is available and documented under FreeBSD. It is
372 // available, but completely undocumented on my current Debian 2.1
375 // In the absence of timegm() we have to guess what mktime() might do.
377 // Many older BSD style systems have a mktime() that assumes the input
378 // time in GMT. But FreeBSD explicitly states that mktime() assumes
381 // The mktime() on many SYSV style systems (such as Linux) usually
382 // returns its result assuming you have specified the input time in
383 // your local timezone. Therefore, in the absence if timegm() you
384 // have to go to extra trouble to convert back to GMT.
386 // If you are having problems with incorrectly positioned astronomical
387 // bodies, this is a really good place to start looking.
389 time_t sgTimeGetGMT(int year, int month, int day, int hour, int min, int sec)
399 mt.tm_isdst = -1; // let the system determine the proper time zone
401 // For now we assume that if daylight is not defined in
402 // /usr/include/time.h that we have a machine with a mktime() that
403 // assumes input is in GMT ... this only matters if we are
404 // building on a system that does not have timegm()
405 #if !defined(HAVE_DAYLIGHT)
406 # define MK_TIME_IS_GMT 1
409 #if defined( HAVE_TIMEGM )
410 return ( timegm(&mt) );
411 #elif defined( MK_TIME_IS_GMT )
412 time_t ret = mktime(&mt);
418 // This is necessary as some mktime() calls may
419 // try to access the system timezone files
420 // if this open fails errno is set to 2
421 // CYGWIN for one does this
423 // perror( "sgTimeGetGMT()" );
427 // reset errno in any event.
431 #else // ! defined ( MK_TIME_IS_GMT )
433 // timezone seems to work as a proper offset for Linux & Solaris
434 # if defined( __linux__ ) || defined( __sun__ ) ||defined(__CYGWIN__)
435 # define TIMEZONE_OFFSET_WORKS 1
438 #if defined(__CYGWIN__)
439 #define TIMEZONE _timezone
441 #define TIMEZONE timezone
444 time_t start = mktime(&mt);
446 SG_LOG( SG_EVENT, SG_DEBUG, "start1 = " << start );
447 // the ctime() call can screw up time progression on some versions
449 // fgPrintf( SG_EVENT, SG_DEBUG, "start2 = %s", ctime(&start));
450 SG_LOG( SG_EVENT, SG_DEBUG, "(tm_isdst = " << mt.tm_isdst << ")" );
452 TIMEZONE = fix_up_timezone( TIMEZONE );
454 # if defined( TIMEZONE_OFFSET_WORKS )
455 SG_LOG( SG_EVENT, SG_DEBUG,
456 "start = " << start << ", timezone = " << TIMEZONE );
457 return( start - TIMEZONE );
458 # else // ! defined( TIMEZONE_OFFSET_WORKS )
460 daylight = mt.tm_isdst;
461 if ( daylight > 0 ) {
463 } else if ( daylight < 0 ) {
464 SG_LOG( SG_EVENT, FG_WARN,
465 "OOOPS, problem in sg_time.cxx, no daylight savings info." );
468 long int offset = -(TIMEZONE / 3600 - daylight);
470 SG_LOG( SG_EVENT, SG_DEBUG, " Raw time zone offset = " << TIMEZONE );
471 SG_LOG( SG_EVENT, SG_DEBUG, " Daylight Savings = " << daylight );
472 SG_LOG( SG_EVENT, SG_DEBUG, " Local hours from GMT = " << offset );
474 long int start_gmt = start - TIMEZONE + (daylight * 3600);
476 SG_LOG( SG_EVENT, SG_DEBUG, " March 21 noon (CST) = " << start );
478 return ( start_gmt );
479 # endif // ! defined( TIMEZONE_OFFSET_WORKS )
480 #endif // ! defined ( MK_TIME_IS_GMT )
485 char* sgTimeFormatTime( const struct tm* p, char* buf )
487 sprintf( buf, "%d/%d/%2d %d:%02d:%02d",
488 p->tm_mon, p->tm_mday, p->tm_year,
489 p->tm_hour, p->tm_min, p->tm_sec);