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.
29 #include <simgear/compiler.h>
31 #include <errno.h> // for errno
33 #ifdef SG_HAVE_STD_INCLUDES
45 #ifdef HAVE_SYS_TIMEB_H
46 # include <sys/timeb.h> // for ftime() and struct timeb
49 # include <unistd.h> // for gettimeofday()
51 #ifdef HAVE_SYS_TIME_H
52 # include <sys/time.h> // for get/setitimer, gettimeofday, struct timeval
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 ) {
123 if ( zonename != NULL ) {
129 // given Julian Date and Longitude (decimal degrees West) compute
130 // Local Sidereal Time, in decimal hours.
132 // Provided courtesy of ecdowney@noao.edu (Elwood Downey)
133 static double sidereal_precise( double mjd, double lng )
135 /* printf ("Current Lst on JD %13.5f at %8.4f degrees West: ",
138 // convert to required internal units
139 lng *= SGD_DEGREES_TO_RADIANS;
141 // compute LST and print
142 double gst = sgTimeCalcGST( mjd );
143 double lst = gst - RADHR( lng );
144 lst -= 24.0 * floor( lst / 24.0 );
145 // printf ("%7.4f\n", lstTmp);
151 // return a courser but cheaper estimate of sidereal time
152 static double sidereal_course( time_t cur_time, struct tm *gmt, double lng )
154 time_t start_gmt, now;
155 double diff, part, days, hours, lstTmp;
159 start_gmt = sgTimeGetGMT(gmt->tm_year, 2, 21, 12, 0, 0);
161 SG_LOG( SG_EVENT, SG_DEBUG, " COURSE: GMT = "
162 << sgTimeFormatTime(gmt, tbuf) );
163 SG_LOG( SG_EVENT, SG_DEBUG, " March 21 noon (GMT) = " << start_gmt );
165 diff = (now - start_gmt) / (3600.0 * 24.0);
167 SG_LOG( SG_EVENT, SG_DEBUG,
168 " Time since 3/21/" << gmt->tm_year << " GMT = " << diff );
170 part = fmod(diff, 1.0);
172 hours = gmt->tm_hour + gmt->tm_min/60.0 + gmt->tm_sec/3600.0;
174 lstTmp = (days - lng)/15.0 + hours - 12;
176 while ( lstTmp < 0.0 ) {
180 SG_LOG( SG_EVENT, SG_DEBUG,
181 " days = " << days << " hours = " << hours << " lon = "
182 << lng << " lst = " << lstTmp );
188 // Update the time related variables
189 void SGTime::update( double lon, double lat, long int warp ) {
190 double gst_precise, gst_course;
192 SG_LOG( SG_EVENT, SG_DEBUG, "Updating time" );
194 // get current Unix calendar time (in seconds)
195 // warp += warp_delta;
196 cur_time = time(NULL) + warp;
197 SG_LOG( SG_EVENT, SG_DEBUG,
198 " Current Unix calendar time = " << cur_time
199 << " warp = " << warp );
201 // get GMT break down for current time
202 gmt = gmtime(&cur_time);
203 SG_LOG( SG_EVENT, SG_DEBUG,
204 " Current GMT = " << gmt->tm_mon+1 << "/"
205 << gmt->tm_mday << "/" << gmt->tm_year << " "
206 << gmt->tm_hour << ":" << gmt->tm_min << ":"
209 // calculate modified Julian date
210 // t->mjd = cal_mjd ((int)(t->gmt->tm_mon+1), (double)t->gmt->tm_mday,
211 // (int)(t->gmt->tm_year + 1900));
212 mjd = sgTimeCalcMJD( (int)(gmt->tm_mon+1), (double)gmt->tm_mday,
213 (int)(gmt->tm_year + 1900) );
215 // add in partial day
216 mjd += (gmt->tm_hour / 24.0) + (gmt->tm_min / (24.0 * 60.0)) +
217 (gmt->tm_sec / (24.0 * 60.0 * 60.0));
219 // convert "back" to Julian date + partial day (as a fraction of one)
221 SG_LOG( SG_EVENT, SG_DEBUG, " Current Julian Date = " << jd );
223 // printf(" Current Longitude = %.3f\n", FG_Longitude * SGD_RADIANS_TO_DEGREES);
225 // Calculate local side real time
226 if ( gst_diff < -100.0 ) {
227 // first time through do the expensive calculation & cheap
228 // calculation to get the difference.
229 SG_LOG( SG_EVENT, SG_INFO, " First time, doing precise gst" );
230 gst_precise = gst = sidereal_precise( mjd, 0.00 );
231 gst_course = sidereal_course( cur_time, gmt, 0.00 );
233 gst_diff = gst_precise - gst_course;
235 lst = sidereal_course( cur_time, gmt, -(lon * SGD_RADIANS_TO_DEGREES) ) + gst_diff;
237 // course + difference should drift off very slowly
238 gst = sidereal_course( cur_time, gmt, 0.00 ) + gst_diff;
239 lst = sidereal_course( cur_time, gmt, -(lon * SGD_RADIANS_TO_DEGREES) ) + gst_diff;
242 SG_LOG( SG_EVENT, SG_DEBUG,
243 " Current lon=0.00 Sidereal Time = " << gst );
244 SG_LOG( SG_EVENT, SG_DEBUG,
245 " Current LOCAL Sidereal Time = " << lst << " ("
246 << sidereal_precise( mjd, -(lon * SGD_RADIANS_TO_DEGREES) )
247 << ") (diff = " << gst_diff << ")" );
251 // Given lon/lat, update timezone information and local_offset
252 void SGTime::updateLocal( double lon, double lat, const string& root )
255 time_t aircraftLocalTime;
256 GeoCoord location( SGD_RADIANS_TO_DEGREES * lat, SGD_RADIANS_TO_DEGREES * lon );
257 GeoCoord* nearestTz = tzContainer->getNearest(location);
259 zone.append ( nearestTz->getDescription() );
263 zonename = strdup( zone.c_str() );
264 currGMT = sgTimeGetGMT( gmtime(&cur_time) );
265 aircraftLocalTime = sgTimeGetGMT( (fgLocaltime(&cur_time, zone.c_str())) );
266 local_offset = aircraftLocalTime - currGMT;
267 // cout << "Using " << local_offset << " as local time offset Timezone is "
268 // << zonename << endl;
272 // given a date in months, mn, days, dy, years, yr, return the
273 // modified Julian date (number of days elapsed since 1900 jan 0.5),
274 // mjd. Adapted from Xephem.
275 double sgTimeCalcMJD(int mn, double dy, int yr) {
278 // internal book keeping data
279 static double last_mjd, last_dy;
280 static int last_mn, last_yr;
285 if (mn == last_mn && yr == last_yr && dy == last_dy) {
290 y = (yr < 0) ? yr + 1 : yr;
296 if (yr < 1582 || (yr == 1582 && (mn < 10 || (mn == 10 && dy < 15)))) {
305 c = (long)((365.25*y) - 0.75) - 694025L;
307 c = (long)(365.25*y) - 694025L;
310 d = (int)(30.6001*(m+1));
312 mjd = b + c + d + dy - 0.5;
323 // given an mjd, calculate greenwich mean sidereal time, gst
324 double sgTimeCalcGST( double mjd ) {
327 double day = floor(mjd-0.5)+0.5;
328 double hr = (mjd-day)*24.0;
331 T = ((int)(mjd - 0.5) + 0.5 - J2000)/36525.0;
332 x = 24110.54841 + (8640184.812866 + (0.093104 - 6.2e-6 * T) * T) * T;
334 gst = (1.0/SIDRATE)*hr + x;
336 SG_LOG( SG_EVENT, SG_DEBUG, " gst => " << gst );
342 #if defined( HAVE_TIMEGM )
343 // ignore this function
344 #elif defined( MK_TIME_IS_GMT )
345 // ignore this function
346 #else // ! defined ( MK_TIME_IS_GMT )
348 // Fix up timezone if using ftime()
349 static long int fix_up_timezone( long int timezone_orig ) {
350 # if !defined( HAVE_GETTIMEOFDAY ) && defined( HAVE_FTIME )
351 // ftime() needs a little extra help finding the current timezone
352 struct timeb current;
354 return( current.timezone * 60 );
356 return( timezone_orig );
362 /******************************************************************
363 * The following are some functions that were included as SGTime
364 * members, although they currently don't make use of any of the
365 * class's variables. Maybe this'll change in the future
366 *****************************************************************/
368 // Return time_t for Sat Mar 21 12:00:00 GMT
370 // On many systems it is ambiguous if mktime() assumes the input is in
371 // GMT, or local timezone. To address this, a new function called
372 // timegm() is appearing. It works exactly like mktime() but
373 // explicitely interprets the input as GMT.
375 // timegm() is available and documented under FreeBSD. It is
376 // available, but completely undocumented on my current Debian 2.1
379 // In the absence of timegm() we have to guess what mktime() might do.
381 // Many older BSD style systems have a mktime() that assumes the input
382 // time in GMT. But FreeBSD explicitly states that mktime() assumes
385 // The mktime() on many SYSV style systems (such as Linux) usually
386 // returns its result assuming you have specified the input time in
387 // your local timezone. Therefore, in the absence if timegm() you
388 // have to go to extra trouble to convert back to GMT.
390 // If you are having problems with incorrectly positioned astronomical
391 // bodies, this is a really good place to start looking.
393 time_t sgTimeGetGMT(int year, int month, int day, int hour, int min, int sec)
403 mt.tm_isdst = -1; // let the system determine the proper time zone
405 // For now we assume that if daylight is not defined in
406 // /usr/include/time.h that we have a machine with a mktime() that
407 // assumes input is in GMT ... this only matters if we are
408 // building on a system that does not have timegm()
409 #if !defined(HAVE_DAYLIGHT)
410 # define MK_TIME_IS_GMT 1
413 #if defined( HAVE_TIMEGM )
414 return ( timegm(&mt) );
415 #elif defined( MK_TIME_IS_GMT )
416 time_t ret = mktime(&mt);
422 // This is necessary as some mktime() calls may
423 // try to access the system timezone files
424 // if this open fails errno is set to 2
425 // CYGWIN for one does this
427 // perror( "sgTimeGetGMT()" );
431 // reset errno in any event.
435 #else // ! defined ( MK_TIME_IS_GMT )
437 // timezone seems to work as a proper offset for Linux & Solaris
438 # if defined( __linux__ ) || defined( __sun__ ) ||defined(__CYGWIN__)
439 # define TIMEZONE_OFFSET_WORKS 1
442 #if defined(__CYGWIN__)
443 #define TIMEZONE _timezone
445 #define TIMEZONE timezone
448 time_t start = mktime(&mt);
450 SG_LOG( SG_EVENT, SG_DEBUG, "start1 = " << start );
451 // the ctime() call can screw up time progression on some versions
453 // fgPrintf( SG_EVENT, SG_DEBUG, "start2 = %s", ctime(&start));
454 SG_LOG( SG_EVENT, SG_DEBUG, "(tm_isdst = " << mt.tm_isdst << ")" );
456 TIMEZONE = fix_up_timezone( TIMEZONE );
458 # if defined( TIMEZONE_OFFSET_WORKS )
459 SG_LOG( SG_EVENT, SG_DEBUG,
460 "start = " << start << ", timezone = " << TIMEZONE );
461 return( start - TIMEZONE );
462 # else // ! defined( TIMEZONE_OFFSET_WORKS )
464 daylight = mt.tm_isdst;
465 if ( daylight > 0 ) {
467 } else if ( daylight < 0 ) {
468 SG_LOG( SG_EVENT, FG_WARN,
469 "OOOPS, problem in sg_time.cxx, no daylight savings info." );
472 long int offset = -(TIMEZONE / 3600 - daylight);
474 SG_LOG( SG_EVENT, SG_DEBUG, " Raw time zone offset = " << TIMEZONE );
475 SG_LOG( SG_EVENT, SG_DEBUG, " Daylight Savings = " << daylight );
476 SG_LOG( SG_EVENT, SG_DEBUG, " Local hours from GMT = " << offset );
478 long int start_gmt = start - TIMEZONE + (daylight * 3600);
480 SG_LOG( SG_EVENT, SG_DEBUG, " March 21 noon (CST) = " << start );
482 return ( start_gmt );
483 # endif // ! defined( TIMEZONE_OFFSET_WORKS )
484 #endif // ! defined ( MK_TIME_IS_GMT )
489 char* sgTimeFormatTime( const struct tm* p, char* buf )
491 sprintf( buf, "%d/%d/%2d %d:%02d:%02d",
492 p->tm_mon, p->tm_mday, p->tm_year,
493 p->tm_hour, p->tm_min, p->tm_sec);