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_TIME_H
44 # include <sys/time.h> // for get/setitimer, gettimeofday, struct timeval
46 #ifdef HAVE_SYS_TIMEB_H
47 # include <sys/timeb.h> // for ftime() and struct timeb
50 # include <unistd.h> // for gettimeofday()
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 void SGTime::init( double lon, double lat,
74 const string& root, time_t init_time )
76 SG_LOG( SG_EVENT, SG_INFO, "Initializing Time" );
83 cur_time = time(NULL);
86 cout << "Current greenwich mean time = " << asctime(gmtime(&cur_time))
88 cout << "Current local time = "
89 << asctime(localtime(&cur_time)) << endl;
91 if ( root != (string)"" ) {
93 zone.append( "zone.tab" );
94 SG_LOG( SG_EVENT, SG_INFO, "Reading timezone info from: "
96 tzContainer = new TimezoneContainer( zone.c_str() );
98 GeoCoord location( SGD_RADIANS_TO_DEGREES * lat, SGD_RADIANS_TO_DEGREES * lon );
99 GeoCoord* nearestTz = tzContainer->getNearest(location);
102 name.append( nearestTz->getDescription() );
103 zonename = strdup( name.c_str() );
104 SG_LOG( SG_EVENT, SG_INFO, "Using zonename = " << zonename );
106 SG_LOG( SG_EVENT, SG_INFO, "*** NO TIME ZONE NAME ***" );
112 SGTime::SGTime( double lon, double lat, const string& root, time_t init_time )
114 init( lon, lat, root, init_time );
118 SGTime::SGTime( const string& root ) {
119 init( 0.0, 0.0, root, 0 );
124 init( 0.0, 0.0, "", 0 );
130 if ( tzContainer != NULL ) {
131 TimezoneContainer *tmp = tzContainer;
136 if ( zonename != NULL ) {
137 char *tmp = zonename;
144 // given Julian Date and Longitude (decimal degrees West) compute
145 // Local Sidereal Time, in decimal hours.
147 // Provided courtesy of ecdowney@noao.edu (Elwood Downey)
148 static double sidereal_precise( double mjd, double lng )
150 /* printf ("Current Lst on JD %13.5f at %8.4f degrees West: ",
153 // convert to required internal units
154 lng *= SGD_DEGREES_TO_RADIANS;
156 // compute LST and print
157 double gst = sgTimeCalcGST( mjd );
158 double lst = gst - RADHR( lng );
159 lst -= 24.0 * floor( lst / 24.0 );
160 // printf ("%7.4f\n", lstTmp);
166 // return a courser but cheaper estimate of sidereal time
167 static double sidereal_course( time_t cur_time, const struct tm *gmt, double lng )
169 time_t start_gmt, now;
170 double diff, part, days, hours, lstTmp;
174 start_gmt = sgTimeGetGMT(gmt->tm_year, 2, 21, 12, 0, 0);
176 SG_LOG( SG_EVENT, SG_DEBUG, " COURSE: GMT = "
177 << sgTimeFormatTime(gmt, tbuf) );
178 SG_LOG( SG_EVENT, SG_DEBUG, " March 21 noon (GMT) = " << start_gmt );
180 diff = (now - start_gmt) / (3600.0 * 24.0);
182 SG_LOG( SG_EVENT, SG_DEBUG,
183 " Time since 3/21/" << gmt->tm_year << " GMT = " << diff );
185 part = fmod(diff, 1.0);
187 hours = gmt->tm_hour + gmt->tm_min/60.0 + gmt->tm_sec/3600.0;
189 lstTmp = (days - lng)/15.0 + hours - 12;
191 while ( lstTmp < 0.0 ) {
195 SG_LOG( SG_EVENT, SG_DEBUG,
196 " days = " << days << " hours = " << hours << " lon = "
197 << lng << " lst = " << lstTmp );
203 // Update the time related variables
204 void SGTime::update( double lon, double lat, time_t ct, long int warp ) {
205 double gst_precise, gst_course;
207 #if defined(_MSC_VER) || defined(__MINGW32__)
211 SG_LOG( SG_EVENT, SG_DEBUG, "Updating time" );
213 // get current Unix calendar time (in seconds)
214 // warp += warp_delta;
216 cur_time = ct + warp;
218 cur_time = time(NULL) + warp;
220 SG_LOG( SG_EVENT, SG_DEBUG,
221 " Current Unix calendar time = " << cur_time
222 << " warp = " << warp );
224 // get GMT break down for current time
225 #if defined(_MSC_VER) || defined(__MINGW32__)
226 memcpy( gmt, gmtime(&cur_time), sizeof(tm) );
228 gmt = gmtime(&cur_time);
230 SG_LOG( SG_EVENT, SG_DEBUG,
231 " Current GMT = " << gmt->tm_mon+1 << "/"
232 << gmt->tm_mday << "/" << (1900 + gmt->tm_year) << " "
233 << gmt->tm_hour << ":" << gmt->tm_min << ":"
236 // calculate modified Julian date starting with current
237 mjd = sgTimeCurrentMJD( ct, warp );
239 // add in partial day
240 mjd += (gmt->tm_hour / 24.0) + (gmt->tm_min / (24.0 * 60.0)) +
241 (gmt->tm_sec / (24.0 * 60.0 * 60.0));
243 // convert "back" to Julian date + partial day (as a fraction of one)
245 SG_LOG( SG_EVENT, SG_DEBUG, " Current Julian Date = " << jd );
247 // printf(" Current Longitude = %.3f\n", FG_Longitude * SGD_RADIANS_TO_DEGREES);
249 // Calculate local side real time
250 if ( gst_diff < -100.0 ) {
251 // first time through do the expensive calculation & cheap
252 // calculation to get the difference.
253 SG_LOG( SG_EVENT, SG_INFO, " First time, doing precise gst" );
254 gst_precise = gst = sidereal_precise( mjd, 0.00 );
255 gst_course = sidereal_course( cur_time, gmt, 0.00 );
257 gst_diff = gst_precise - gst_course;
259 lst = sidereal_course( cur_time, gmt, -(lon * SGD_RADIANS_TO_DEGREES) ) + gst_diff;
261 // course + difference should drift off very slowly
262 gst = sidereal_course( cur_time, gmt, 0.00 ) + gst_diff;
263 lst = sidereal_course( cur_time, gmt, -(lon * SGD_RADIANS_TO_DEGREES) ) + gst_diff;
266 SG_LOG( SG_EVENT, SG_DEBUG,
267 " Current lon=0.00 Sidereal Time = " << gst );
268 SG_LOG( SG_EVENT, SG_DEBUG,
269 " Current LOCAL Sidereal Time = " << lst << " ("
270 << sidereal_precise( mjd, -(lon * SGD_RADIANS_TO_DEGREES) )
271 << ") (diff = " << gst_diff << ")" );
275 // Given lon/lat, update timezone information and local_offset
276 void SGTime::updateLocal( double lon, double lat, const string& root ) {
278 if ( lon < -SGD_PI || lon > SGD_PI ) {
279 // not within -180 ... 180
282 if ( lat < -SGD_PI * 0.5 || lat > SGD_PI * 0.5 ) {
283 // not within -90 ... 90
287 // only true if lon == nan
288 SG_LOG( SG_EVENT, SG_ALERT, " Detected lon == nan, resetting to 0.0" );
292 // only true if lat == nan
293 SG_LOG( SG_EVENT, SG_ALERT, " Detected lat == nan, resetting to 0.0" );
297 time_t aircraftLocalTime;
298 GeoCoord location( SGD_RADIANS_TO_DEGREES * lat, SGD_RADIANS_TO_DEGREES * lon );
299 GeoCoord* nearestTz = tzContainer->getNearest(location);
301 zone.append ( nearestTz->getDescription() );
303 char *ptr = zonename;
307 zonename = strdup( zone.c_str() );
309 //Avoid troubles when zone.tab hasn't got the right line endings
310 if (zonename[strlen(zonename)-1] == '\r')
312 zonename[strlen(zonename)-1]=0;
313 zone.set( zonename );
316 currGMT = sgTimeGetGMT( gmtime(&cur_time) );
317 aircraftLocalTime = sgTimeGetGMT( (fgLocaltime(&cur_time, zone.c_str())) );
318 local_offset = aircraftLocalTime - currGMT;
319 // cout << "Using " << local_offset << " as local time offset Timezone is "
320 // << zonename << endl;
324 // given a date in months, mn, days, dy, years, yr, return the
325 // modified Julian date (number of days elapsed since 1900 jan 0.5),
326 // mjd. Adapted from Xephem.
327 double sgTimeCalcMJD(int mn, double dy, int yr) {
330 // internal book keeping data
331 static double last_mjd, last_dy;
332 static int last_mn, last_yr;
337 if (mn == last_mn && yr == last_yr && dy == last_dy) {
342 y = (yr < 0) ? yr + 1 : yr;
348 if (yr < 1582 || (yr == 1582 && (mn < 10 || (mn == 10 && dy < 15)))) {
357 c = (long)((365.25*y) - 0.75) - 694025L;
359 c = (long)(365.25*y) - 694025L;
362 d = (int)(30.6001*(m+1));
364 mjd = b + c + d + dy - 0.5;
375 // return the current modified Julian date (number of days elapsed
376 // since 1900 jan 0.5), mjd.
377 double sgTimeCurrentMJD( time_t ct, long int warp ) {
379 #if defined(_MSC_VER) || defined(__MINGW32__)
380 struct tm m_gmt; // copy of system gmtime(&time_t) structure
381 struct tm *gmt = &m_gmt;
386 // get current Unix calendar time (in seconds)
387 // warp += warp_delta;
390 cur_time = ct + warp;
392 cur_time = time(NULL) + warp;
394 SG_LOG( SG_EVENT, SG_DEBUG,
395 " Current Unix calendar time = " << cur_time
396 << " warp = " << warp );
398 // get GMT break down for current time
399 #if defined(_MSC_VER) || defined(__MINGW32__)
400 memcpy( gmt, gmtime(&cur_time), sizeof(tm) );
402 gmt = gmtime(&cur_time);
404 SG_LOG( SG_EVENT, SG_DEBUG,
405 " Current GMT = " << gmt->tm_mon+1 << "/"
406 << gmt->tm_mday << "/" << (1900 + gmt->tm_year) << " "
407 << gmt->tm_hour << ":" << gmt->tm_min << ":"
410 // calculate modified Julian date
411 // t->mjd = cal_mjd ((int)(t->gmt->tm_mon+1), (double)t->gmt->tm_mday,
412 // (int)(t->gmt->tm_year + 1900));
413 double mjd = sgTimeCalcMJD( (int)(gmt->tm_mon+1), (double)gmt->tm_mday,
414 (int)(gmt->tm_year + 1900) );
420 // given an mjd, calculate greenwich mean sidereal time, gst
421 double sgTimeCalcGST( double mjd ) {
424 double day = floor(mjd-0.5)+0.5;
425 double hr = (mjd-day)*24.0;
428 T = ((int)(mjd - 0.5) + 0.5 - J2000)/36525.0;
429 x = 24110.54841 + (8640184.812866 + (0.093104 - 6.2e-6 * T) * T) * T;
431 gst = (1.0/SIDRATE)*hr + x;
433 SG_LOG( SG_EVENT, SG_DEBUG, " gst => " << gst );
439 #if defined( HAVE_TIMEGM )
440 // ignore this function
441 #elif defined( MK_TIME_IS_GMT )
442 // ignore this function
443 #else // ! defined ( MK_TIME_IS_GMT )
445 // Fix up timezone if using ftime()
446 static long int fix_up_timezone( long int timezone_orig ) {
447 # if !defined( HAVE_GETTIMEOFDAY ) && defined( HAVE_FTIME )
448 // ftime() needs a little extra help finding the current timezone
449 struct timeb current;
451 return( current.timezone * 60 );
453 return( timezone_orig );
459 /******************************************************************
460 * The following are some functions that were included as SGTime
461 * members, although they currently don't make use of any of the
462 * class's variables. Maybe this'll change in the future
463 *****************************************************************/
465 // Return time_t for Sat Mar 21 12:00:00 GMT
467 // On many systems it is ambiguous if mktime() assumes the input is in
468 // GMT, or local timezone. To address this, a new function called
469 // timegm() is appearing. It works exactly like mktime() but
470 // explicitely interprets the input as GMT.
472 // timegm() is available and documented under FreeBSD. It is
473 // available, but completely undocumented on my current Debian 2.1
476 // In the absence of timegm() we have to guess what mktime() might do.
478 // Many older BSD style systems have a mktime() that assumes the input
479 // time in GMT. But FreeBSD explicitly states that mktime() assumes
482 // The mktime() on many SYSV style systems (such as Linux) usually
483 // returns its result assuming you have specified the input time in
484 // your local timezone. Therefore, in the absence if timegm() you
485 // have to go to extra trouble to convert back to GMT.
487 // If you are having problems with incorrectly positioned astronomical
488 // bodies, this is a really good place to start looking.
490 time_t sgTimeGetGMT(int year, int month, int day, int hour, int min, int sec)
500 mt.tm_isdst = -1; // let the system determine the proper time zone
502 // For now we assume that if daylight is not defined in
503 // /usr/include/time.h that we have a machine with a mktime() that
504 // assumes input is in GMT ... this only matters if we are
505 // building on a system that does not have timegm()
506 #if !defined(HAVE_DAYLIGHT)
507 # define MK_TIME_IS_GMT 1
510 #if defined( HAVE_TIMEGM )
511 return ( timegm(&mt) );
512 #elif defined( MK_TIME_IS_GMT )
513 time_t ret = mktime(&mt);
519 // This is necessary as some mktime() calls may
520 // try to access the system timezone files
521 // if this open fails errno is set to 2
522 // CYGWIN for one does this
524 // perror( "sgTimeGetGMT()" );
528 // reset errno in any event.
532 #else // ! defined ( MK_TIME_IS_GMT )
534 // timezone seems to work as a proper offset for Linux & Solaris
535 # if defined( __linux__ ) || defined( __sun__ ) ||defined(__CYGWIN__)
536 # define TIMEZONE_OFFSET_WORKS 1
539 #if defined(__CYGWIN__)
540 #define TIMEZONE _timezone
542 #define TIMEZONE timezone
545 time_t start = mktime(&mt);
547 SG_LOG( SG_EVENT, SG_DEBUG, "start1 = " << start );
548 // the ctime() call can screw up time progression on some versions
550 // fgPrintf( SG_EVENT, SG_DEBUG, "start2 = %s", ctime(&start));
551 SG_LOG( SG_EVENT, SG_DEBUG, "(tm_isdst = " << mt.tm_isdst << ")" );
553 TIMEZONE = fix_up_timezone( TIMEZONE );
555 # if defined( TIMEZONE_OFFSET_WORKS )
556 SG_LOG( SG_EVENT, SG_DEBUG,
557 "start = " << start << ", timezone = " << TIMEZONE );
558 return( start - TIMEZONE );
559 # else // ! defined( TIMEZONE_OFFSET_WORKS )
561 daylight = mt.tm_isdst;
562 if ( daylight > 0 ) {
564 } else if ( daylight < 0 ) {
565 SG_LOG( SG_EVENT, FG_WARN,
566 "OOOPS, problem in sg_time.cxx, no daylight savings info." );
569 long int offset = -(TIMEZONE / 3600 - daylight);
571 SG_LOG( SG_EVENT, SG_DEBUG, " Raw time zone offset = " << TIMEZONE );
572 SG_LOG( SG_EVENT, SG_DEBUG, " Daylight Savings = " << daylight );
573 SG_LOG( SG_EVENT, SG_DEBUG, " Local hours from GMT = " << offset );
575 long int start_gmt = start - TIMEZONE + (daylight * 3600);
577 SG_LOG( SG_EVENT, SG_DEBUG, " March 21 noon (CST) = " << start );
579 return ( start_gmt );
580 # endif // ! defined( TIMEZONE_OFFSET_WORKS )
581 #endif // ! defined ( MK_TIME_IS_GMT )
586 char* sgTimeFormatTime( const struct tm* p, char* buf )
588 sprintf( buf, "%d/%d/%2d %d:%02d:%02d",
589 p->tm_mon, p->tm_mday, p->tm_year,
590 p->tm_hour, p->tm_min, p->tm_sec);