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.
26 # include <simgear_config.h>
29 #include <simgear/compiler.h>
31 #include <errno.h> // for errno
33 #ifdef SG_HAVE_STD_INCLUDES
43 #ifdef HAVE_SYS_TIMEB_H
44 # include <sys/timeb.h> // for ftime() and struct timeb
47 # include <unistd.h> // for gettimeofday()
49 #ifdef HAVE_SYS_TIME_H
50 # include <sys/time.h> // for get/setitimer, gettimeofday, struct timeval
53 #include <math.h> // for NAN
55 #include <simgear/constants.h>
56 #include <simgear/debug/logstream.hxx>
57 #include <simgear/misc/sg_path.hxx>
59 #include "sg_time.hxx"
61 #include "lowleveltime.h"
64 #define DEGHR(x) ((x)/15.)
65 #define RADHR(x) DEGHR(x*SGD_RADIANS_TO_DEGREES)
68 static const double MJD0 = 2415020.0;
69 static const double J2000 = 2451545.0 - MJD0;
70 static const double SIDRATE = 0.9972695677;
73 SGTime::SGTime( double lon, double lat, const string& root )
75 SG_LOG( SG_EVENT, SG_INFO, "Initializing Time" );
79 cur_time = time(NULL);
80 cout << "Current greenwich mean time = " << asctime(gmtime(&cur_time))
82 cout << "Current local time = "
83 << asctime(localtime(&cur_time)) << endl;
85 if ( root != (string)"" ) {
87 zone.append( "zone.tab" );
88 SG_LOG( SG_EVENT, SG_INFO, "Reading timezone info from: "
90 tzContainer = new TimezoneContainer( zone.c_str() );
92 GeoCoord location( SGD_RADIANS_TO_DEGREES * lat, SGD_RADIANS_TO_DEGREES * lon );
93 GeoCoord* nearestTz = tzContainer->getNearest(location);
96 name.append( nearestTz->getDescription() );
97 zonename = strdup( name.c_str() );
98 SG_LOG( SG_EVENT, SG_INFO, "Using zonename = " << zonename );
100 SG_LOG( SG_EVENT, SG_INFO, "*** NO TIME ZONE NAME ***" );
107 SGTime::SGTime( const string& root ) {
108 SGTime( 0.0, 0.0, root );
113 SGTime( 0.0, 0.0, "" );
119 if ( tzContainer != NULL ) {
120 TimezoneContainer *tmp = tzContainer;
125 if ( zonename != NULL ) {
126 char *tmp = zonename;
133 // given Julian Date and Longitude (decimal degrees West) compute
134 // Local Sidereal Time, in decimal hours.
136 // Provided courtesy of ecdowney@noao.edu (Elwood Downey)
137 static double sidereal_precise( double mjd, double lng )
139 /* printf ("Current Lst on JD %13.5f at %8.4f degrees West: ",
142 // convert to required internal units
143 lng *= SGD_DEGREES_TO_RADIANS;
145 // compute LST and print
146 double gst = sgTimeCalcGST( mjd );
147 double lst = gst - RADHR( lng );
148 lst -= 24.0 * floor( lst / 24.0 );
149 // printf ("%7.4f\n", lstTmp);
155 // return a courser but cheaper estimate of sidereal time
156 static double sidereal_course( time_t cur_time, struct tm *gmt, double lng )
158 time_t start_gmt, now;
159 double diff, part, days, hours, lstTmp;
163 start_gmt = sgTimeGetGMT(gmt->tm_year, 2, 21, 12, 0, 0);
165 SG_LOG( SG_EVENT, SG_DEBUG, " COURSE: GMT = "
166 << sgTimeFormatTime(gmt, tbuf) );
167 SG_LOG( SG_EVENT, SG_DEBUG, " March 21 noon (GMT) = " << start_gmt );
169 diff = (now - start_gmt) / (3600.0 * 24.0);
171 SG_LOG( SG_EVENT, SG_DEBUG,
172 " Time since 3/21/" << gmt->tm_year << " GMT = " << diff );
174 part = fmod(diff, 1.0);
176 hours = gmt->tm_hour + gmt->tm_min/60.0 + gmt->tm_sec/3600.0;
178 lstTmp = (days - lng)/15.0 + hours - 12;
180 while ( lstTmp < 0.0 ) {
184 SG_LOG( SG_EVENT, SG_DEBUG,
185 " days = " << days << " hours = " << hours << " lon = "
186 << lng << " lst = " << lstTmp );
192 // Update the time related variables
193 void SGTime::update( double lon, double lat, long int warp ) {
194 double gst_precise, gst_course;
196 #if defined(_MSC_VER) || defined(__MINGW32__)
200 SG_LOG( SG_EVENT, SG_DEBUG, "Updating time" );
202 // get current Unix calendar time (in seconds)
203 // warp += warp_delta;
204 cur_time = time(NULL) + warp;
205 SG_LOG( SG_EVENT, SG_DEBUG,
206 " Current Unix calendar time = " << cur_time
207 << " warp = " << warp );
209 // get GMT break down for current time
210 #if defined(_MSC_VER) || defined(__MINGW32__)
211 memcpy( gmt, gmtime(&cur_time), sizeof(tm) );
213 gmt = gmtime(&cur_time);
215 SG_LOG( SG_EVENT, SG_DEBUG,
216 " Current GMT = " << gmt->tm_mon+1 << "/"
217 << gmt->tm_mday << "/" << (1900 + gmt->tm_year) << " "
218 << gmt->tm_hour << ":" << gmt->tm_min << ":"
221 // calculate modified Julian date starting with current
222 mjd = sgTimeCurrentMJD( warp );
224 // add in partial day
225 mjd += (gmt->tm_hour / 24.0) + (gmt->tm_min / (24.0 * 60.0)) +
226 (gmt->tm_sec / (24.0 * 60.0 * 60.0));
228 // convert "back" to Julian date + partial day (as a fraction of one)
230 SG_LOG( SG_EVENT, SG_DEBUG, " Current Julian Date = " << jd );
232 // printf(" Current Longitude = %.3f\n", FG_Longitude * SGD_RADIANS_TO_DEGREES);
234 // Calculate local side real time
235 if ( gst_diff < -100.0 ) {
236 // first time through do the expensive calculation & cheap
237 // calculation to get the difference.
238 SG_LOG( SG_EVENT, SG_INFO, " First time, doing precise gst" );
239 gst_precise = gst = sidereal_precise( mjd, 0.00 );
240 gst_course = sidereal_course( cur_time, gmt, 0.00 );
242 gst_diff = gst_precise - gst_course;
244 lst = sidereal_course( cur_time, gmt, -(lon * SGD_RADIANS_TO_DEGREES) ) + gst_diff;
246 // course + difference should drift off very slowly
247 gst = sidereal_course( cur_time, gmt, 0.00 ) + gst_diff;
248 lst = sidereal_course( cur_time, gmt, -(lon * SGD_RADIANS_TO_DEGREES) ) + gst_diff;
251 SG_LOG( SG_EVENT, SG_DEBUG,
252 " Current lon=0.00 Sidereal Time = " << gst );
253 SG_LOG( SG_EVENT, SG_DEBUG,
254 " Current LOCAL Sidereal Time = " << lst << " ("
255 << sidereal_precise( mjd, -(lon * SGD_RADIANS_TO_DEGREES) )
256 << ") (diff = " << gst_diff << ")" );
260 // Given lon/lat, update timezone information and local_offset
261 void SGTime::updateLocal( double lon, double lat, const string& root ) {
263 if ( lon < -SGD_PI || lon > SGD_PI ) {
264 // not within -180 ... 180
267 if ( lat < -SGD_PI * 0.5 || lat > SGD_PI * 0.5 ) {
268 // not within -90 ... 90
272 // only true if lon == nan
273 SG_LOG( SG_EVENT, SG_ALERT, " Detected lon == nan, resetting to 0.0" );
277 // only true if lat == nan
278 SG_LOG( SG_EVENT, SG_ALERT, " Detected lat == nan, resetting to 0.0" );
282 time_t aircraftLocalTime;
283 GeoCoord location( SGD_RADIANS_TO_DEGREES * lat, SGD_RADIANS_TO_DEGREES * lon );
284 GeoCoord* nearestTz = tzContainer->getNearest(location);
286 zone.append ( nearestTz->getDescription() );
288 char *ptr = zonename;
292 zonename = strdup( zone.c_str() );
294 //Avoid troubles when zone.tab hasn't got the right line endings
295 if (zonename[strlen(zonename)-1] == '\r')
297 zonename[strlen(zonename)-1]=0;
298 zone.set( zonename );
301 currGMT = sgTimeGetGMT( gmtime(&cur_time) );
302 aircraftLocalTime = sgTimeGetGMT( (fgLocaltime(&cur_time, zone.c_str())) );
303 local_offset = aircraftLocalTime - currGMT;
304 // cout << "Using " << local_offset << " as local time offset Timezone is "
305 // << zonename << endl;
309 // given a date in months, mn, days, dy, years, yr, return the
310 // modified Julian date (number of days elapsed since 1900 jan 0.5),
311 // mjd. Adapted from Xephem.
312 double sgTimeCalcMJD(int mn, double dy, int yr) {
315 // internal book keeping data
316 static double last_mjd, last_dy;
317 static int last_mn, last_yr;
322 if (mn == last_mn && yr == last_yr && dy == last_dy) {
327 y = (yr < 0) ? yr + 1 : yr;
333 if (yr < 1582 || (yr == 1582 && (mn < 10 || (mn == 10 && dy < 15)))) {
342 c = (long)((365.25*y) - 0.75) - 694025L;
344 c = (long)(365.25*y) - 694025L;
347 d = (int)(30.6001*(m+1));
349 mjd = b + c + d + dy - 0.5;
360 // return the current modified Julian date (number of days elapsed
361 // since 1900 jan 0.5), mjd.
362 double sgTimeCurrentMJD( long int warp ) {
364 #if defined(_MSC_VER) || defined(__MINGW32__)
365 struct tm m_gmt; // copy of system gmtime(&time_t) structure
370 #if defined(_MSC_VER) || defined(__MINGW32__)
374 // get current Unix calendar time (in seconds)
375 // warp += warp_delta;
376 time_t cur_time = time(NULL) + warp;
377 SG_LOG( SG_EVENT, SG_DEBUG,
378 " Current Unix calendar time = " << cur_time
379 << " warp = " << warp );
381 // get GMT break down for current time
382 #if defined(_MSC_VER) || defined(__MINGW32__)
383 memcpy( gmt, gmtime(&cur_time), sizeof(tm) );
385 gmt = gmtime(&cur_time);
387 SG_LOG( SG_EVENT, SG_DEBUG,
388 " Current GMT = " << gmt->tm_mon+1 << "/"
389 << gmt->tm_mday << "/" << (1900 + gmt->tm_year) << " "
390 << gmt->tm_hour << ":" << gmt->tm_min << ":"
393 // calculate modified Julian date
394 // t->mjd = cal_mjd ((int)(t->gmt->tm_mon+1), (double)t->gmt->tm_mday,
395 // (int)(t->gmt->tm_year + 1900));
396 double mjd = sgTimeCalcMJD( (int)(gmt->tm_mon+1), (double)gmt->tm_mday,
397 (int)(gmt->tm_year + 1900) );
403 // given an mjd, calculate greenwich mean sidereal time, gst
404 double sgTimeCalcGST( double mjd ) {
407 double day = floor(mjd-0.5)+0.5;
408 double hr = (mjd-day)*24.0;
411 T = ((int)(mjd - 0.5) + 0.5 - J2000)/36525.0;
412 x = 24110.54841 + (8640184.812866 + (0.093104 - 6.2e-6 * T) * T) * T;
414 gst = (1.0/SIDRATE)*hr + x;
416 SG_LOG( SG_EVENT, SG_DEBUG, " gst => " << gst );
422 #if defined( HAVE_TIMEGM )
423 // ignore this function
424 #elif defined( MK_TIME_IS_GMT )
425 // ignore this function
426 #else // ! defined ( MK_TIME_IS_GMT )
428 // Fix up timezone if using ftime()
429 static long int fix_up_timezone( long int timezone_orig ) {
430 # if !defined( HAVE_GETTIMEOFDAY ) && defined( HAVE_FTIME )
431 // ftime() needs a little extra help finding the current timezone
432 struct timeb current;
434 return( current.timezone * 60 );
436 return( timezone_orig );
442 /******************************************************************
443 * The following are some functions that were included as SGTime
444 * members, although they currently don't make use of any of the
445 * class's variables. Maybe this'll change in the future
446 *****************************************************************/
448 // Return time_t for Sat Mar 21 12:00:00 GMT
450 // On many systems it is ambiguous if mktime() assumes the input is in
451 // GMT, or local timezone. To address this, a new function called
452 // timegm() is appearing. It works exactly like mktime() but
453 // explicitely interprets the input as GMT.
455 // timegm() is available and documented under FreeBSD. It is
456 // available, but completely undocumented on my current Debian 2.1
459 // In the absence of timegm() we have to guess what mktime() might do.
461 // Many older BSD style systems have a mktime() that assumes the input
462 // time in GMT. But FreeBSD explicitly states that mktime() assumes
465 // The mktime() on many SYSV style systems (such as Linux) usually
466 // returns its result assuming you have specified the input time in
467 // your local timezone. Therefore, in the absence if timegm() you
468 // have to go to extra trouble to convert back to GMT.
470 // If you are having problems with incorrectly positioned astronomical
471 // bodies, this is a really good place to start looking.
473 time_t sgTimeGetGMT(int year, int month, int day, int hour, int min, int sec)
483 mt.tm_isdst = -1; // let the system determine the proper time zone
485 // For now we assume that if daylight is not defined in
486 // /usr/include/time.h that we have a machine with a mktime() that
487 // assumes input is in GMT ... this only matters if we are
488 // building on a system that does not have timegm()
489 #if !defined(HAVE_DAYLIGHT)
490 # define MK_TIME_IS_GMT 1
493 #if defined( HAVE_TIMEGM )
494 return ( timegm(&mt) );
495 #elif defined( MK_TIME_IS_GMT )
496 time_t ret = mktime(&mt);
502 // This is necessary as some mktime() calls may
503 // try to access the system timezone files
504 // if this open fails errno is set to 2
505 // CYGWIN for one does this
507 // perror( "sgTimeGetGMT()" );
511 // reset errno in any event.
515 #else // ! defined ( MK_TIME_IS_GMT )
517 // timezone seems to work as a proper offset for Linux & Solaris
518 # if defined( __linux__ ) || defined( __sun__ ) ||defined(__CYGWIN__)
519 # define TIMEZONE_OFFSET_WORKS 1
522 #if defined(__CYGWIN__)
523 #define TIMEZONE _timezone
525 #define TIMEZONE timezone
528 time_t start = mktime(&mt);
530 SG_LOG( SG_EVENT, SG_DEBUG, "start1 = " << start );
531 // the ctime() call can screw up time progression on some versions
533 // fgPrintf( SG_EVENT, SG_DEBUG, "start2 = %s", ctime(&start));
534 SG_LOG( SG_EVENT, SG_DEBUG, "(tm_isdst = " << mt.tm_isdst << ")" );
536 TIMEZONE = fix_up_timezone( TIMEZONE );
538 # if defined( TIMEZONE_OFFSET_WORKS )
539 SG_LOG( SG_EVENT, SG_DEBUG,
540 "start = " << start << ", timezone = " << TIMEZONE );
541 return( start - TIMEZONE );
542 # else // ! defined( TIMEZONE_OFFSET_WORKS )
544 daylight = mt.tm_isdst;
545 if ( daylight > 0 ) {
547 } else if ( daylight < 0 ) {
548 SG_LOG( SG_EVENT, FG_WARN,
549 "OOOPS, problem in sg_time.cxx, no daylight savings info." );
552 long int offset = -(TIMEZONE / 3600 - daylight);
554 SG_LOG( SG_EVENT, SG_DEBUG, " Raw time zone offset = " << TIMEZONE );
555 SG_LOG( SG_EVENT, SG_DEBUG, " Daylight Savings = " << daylight );
556 SG_LOG( SG_EVENT, SG_DEBUG, " Local hours from GMT = " << offset );
558 long int start_gmt = start - TIMEZONE + (daylight * 3600);
560 SG_LOG( SG_EVENT, SG_DEBUG, " March 21 noon (CST) = " << start );
562 return ( start_gmt );
563 # endif // ! defined( TIMEZONE_OFFSET_WORKS )
564 #endif // ! defined ( MK_TIME_IS_GMT )
569 char* sgTimeFormatTime( const struct tm* p, char* buf )
571 sprintf( buf, "%d/%d/%2d %d:%02d:%02d",
572 p->tm_mon, p->tm_mday, p->tm_year,
573 p->tm_hour, p->tm_min, p->tm_sec);