2 * /src/NTP/ntp-4/parseutil/dcfd.c,v 4.9 1999/02/28 13:06:27 kardel RELEASE_19990228_A
4 * dcfd.c,v 4.9 1999/02/28 13:06:27 kardel RELEASE_19990228_A
6 * DCF77 100/200ms pulse synchronisation daemon program (via 50Baud serial line)
10 * simple NTP loopfilter logic for local clock
11 * interactive display for debugging
14 * Leap second handling (at that level you should switch to NTP Version 4 - really!)
16 * Copyright (C) 1995-1999 by Frank Kardel <kardel@acm.org>
17 * Copyright (C) 1993-1994 by Frank Kardel
18 * Friedrich-Alexander Universität Erlangen-Nürnberg, Germany
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
24 * This program may not be sold or used for profit without prior
25 * written consent of the author.
35 #include <sys/types.h>
42 * NTP compilation environment
44 #include "ntp_stdlib.h"
45 #include "ntpd.h" /* indirectly include ntp.h to get YEAR_PIVOT Y2KFixes */
48 * select which terminal handling to use (currently only SysV variants)
50 #if defined(HAVE_TERMIOS_H) || defined(STREAM)
52 #define TTY_GETATTR(_FD_, _ARG_) tcgetattr((_FD_), (_ARG_))
53 #define TTY_SETATTR(_FD_, _ARG_) tcsetattr((_FD_), TCSANOW, (_ARG_))
54 #else /* not HAVE_TERMIOS_H || STREAM */
55 # if defined(HAVE_TERMIO_H) || defined(HAVE_SYSV_TTYS)
57 # define TTY_GETATTR(_FD_, _ARG_) ioctl((_FD_), TCGETA, (_ARG_))
58 # define TTY_SETATTR(_FD_, _ARG_) ioctl((_FD_), TCSETAW, (_ARG_))
59 # endif/* HAVE_TERMIO_H || HAVE_SYSV_TTYS */
60 #endif /* not HAVE_TERMIOS_H || STREAM */
64 #include "Bletch: MUST DEFINE ONE OF 'HAVE_TERMIOS_H' or 'HAVE_TERMIO_H'"
68 #define days_per_year(_x_) (((_x_) % 4) ? 365 : (((_x_) % 400) ? 365 : 366))
71 #define timernormalize(_a_) \
72 if ((_a_)->tv_usec >= 1000000) \
74 (_a_)->tv_sec += (_a_)->tv_usec / 1000000; \
75 (_a_)->tv_usec = (_a_)->tv_usec % 1000000; \
77 if ((_a_)->tv_usec < 0) \
79 (_a_)->tv_sec -= 1 + (-(_a_)->tv_usec / 1000000); \
80 (_a_)->tv_usec = 999999 - (-(_a_)->tv_usec - 1); \
86 #define timeradd(_a_, _b_) \
87 (_a_)->tv_sec += (_b_)->tv_sec; \
88 (_a_)->tv_usec += (_b_)->tv_usec; \
94 #define timersub(_a_, _b_) \
95 (_a_)->tv_sec -= (_b_)->tv_sec; \
96 (_a_)->tv_usec -= (_b_)->tv_usec; \
102 #define PRINTF if (interactive) printf
103 #define LPRINTF if (interactive && loop_filter_debug) printf
106 #define dprintf(_x_) LPRINTF _x_
114 * display received data (avoids also detaching from tty)
116 static int interactive = 0;
119 * display loopfilter (clock control) variables
121 static int loop_filter_debug = 0;
124 * do not set/adjust system time
126 static int no_set = 0;
129 * time that passes between start of DCF impulse and time stamping (fine
130 * adjustment) in microseconds (receiver/OS dependent)
132 #define DEFAULT_DELAY 230000 /* rough estimate */
135 * The two states we can be in - eithe we receive nothing
136 * usable or we have the correct time
141 static int sync_state = NO_SYNC;
142 static time_t last_sync;
144 static unsigned long ticks = 0;
146 static char pat[] = "-\\|/";
148 #define LINES (24-2) /* error lines after which the two headlines are repeated */
150 #define MAX_UNSYNC (10*60) /* allow synchronisation loss for 10 minutes */
151 #define NOTICE_INTERVAL (20*60) /* mention missing synchronisation every 20 minutes */
154 * clock adjustment PLL - see NTP protocol spec (RFC1305) for details
158 #define TIMECONSTANT 2
159 #define ADJINTERVAL 0
160 #define FREQ_WEIGHT 18
161 #define PHASE_WEIGHT 7
162 #define MAX_DRIFT 0x3FFFFFFF
164 #define R_SHIFT(_X_, _Y_) (((_X_) < 0) ? -(-(_X_) >> (_Y_)) : ((_X_) >> (_Y_)))
166 static struct timeval max_adj_offset = { 0, 128000 };
168 static long clock_adjust = 0; /* current adjustment value (usec * 2^USECSCALE) */
169 static long accum_drift = 0; /* accumulated drift value (usec / ADJINTERVAL) */
170 static long adjustments = 0;
171 static char skip_adjust = 1; /* discard first adjustment (bad samples) */
176 #define DCFB_ANNOUNCE 0x0001 /* switch time zone warning (DST switch) */
177 #define DCFB_DST 0x0002 /* DST in effect */
178 #define DCFB_LEAP 0x0004 /* LEAP warning (1 hour prior to occurence) */
179 #define DCFB_ALTERNATE 0x0008 /* alternate antenna used */
181 struct clocktime /* clock time broken up from time code */
183 long wday; /* Day of week: 1: Monday - 7: Sunday */
191 long utcoffset; /* in minutes */
192 long flags; /* current clock status (DCF77 state flags) */
195 typedef struct clocktime clocktime_t;
198 * (usually) quick constant multiplications
200 #define TIMES10(_X_) (((_X_) << 3) + ((_X_) << 1)) /* *8 + *2 */
201 #define TIMES24(_X_) (((_X_) << 4) + ((_X_) << 3)) /* *16 + *8 */
202 #define TIMES60(_X_) ((((_X_) << 4) - (_X_)) << 2) /* *(16 - 1) *4 */
204 * generic l_abs() function
206 #define l_abs(_x_) (((_x_) < 0) ? -(_x_) : (_x_))
209 * conversion related return/error codes
211 #define CVT_MASK 0x0000000F /* conversion exit code */
212 #define CVT_NONE 0x00000001 /* format not applicable */
213 #define CVT_FAIL 0x00000002 /* conversion failed - error code returned */
214 #define CVT_OK 0x00000004 /* conversion succeeded */
215 #define CVT_BADFMT 0x00000010 /* general format error - (unparsable) */
216 #define CVT_BADDATE 0x00000020 /* invalid date */
217 #define CVT_BADTIME 0x00000040 /* invalid time */
220 * DCF77 raw time code
222 * From "Zur Zeit", Physikalisch-Technische Bundesanstalt (PTB), Braunschweig
223 * und Berlin, Maerz 1989
225 * Timecode transmission:
227 * time marks are send every second except for the second before the
229 * time marks consist of a reduction of transmitter power to 25%
230 * of the nominal level
231 * the falling edge is the time indication (on time)
232 * time marks of a 100ms duration constitute a logical 0
233 * time marks of a 200ms duration constitute a logical 1
235 * see the spec. (basically a (non-)inverted psuedo random phase shift)
239 * 0 - 10 AM: free, FM: 0
241 * 15 R - alternate antenna
242 * 16 A1 - expect zone change (1 hour before)
243 * 17 - 18 Z1,Z2 - time zone
246 * 1 0 MESZ (MED, MET DST)
248 * 19 A2 - expect leap insertion/deletion (1 hour before)
249 * 20 S - start of time code (1)
250 * 21 - 24 M1 - BCD (lsb first) Minutes
251 * 25 - 27 M10 - BCD (lsb first) 10 Minutes
252 * 28 P1 - Minute Parity (even)
253 * 29 - 32 H1 - BCD (lsb first) Hours
254 * 33 - 34 H10 - BCD (lsb first) 10 Hours
255 * 35 P2 - Hour Parity (even)
256 * 36 - 39 D1 - BCD (lsb first) Days
257 * 40 - 41 D10 - BCD (lsb first) 10 Days
258 * 42 - 44 DW - BCD (lsb first) day of week (1: Monday -> 7: Sunday)
259 * 45 - 49 MO - BCD (lsb first) Month
261 * 51 - 53 Y1 - BCD (lsb first) Years
262 * 54 - 57 Y10 - BCD (lsb first) 10 Years
263 * 58 P3 - Date Parity (even)
264 * 59 - usually missing (minute indication), except for leap insertion
267 /*-----------------------------------------------------------------------
268 * conversion table to map DCF77 bit stream into data fields.
270 * Each field of the DCF77 code is described with two adjacent entries in
271 * this table. The first entry specifies the offset into the DCF77 data stream
272 * while the length is given as the difference between the start index and
273 * the start index of the following field.
275 static struct rawdcfcode
277 char offset; /* start bit */
280 { 0 }, { 15 }, { 16 }, { 17 }, { 19 }, { 20 }, { 21 }, { 25 }, { 28 }, { 29 },
281 { 33 }, { 35 }, { 36 }, { 40 }, { 42 }, { 45 }, { 49 }, { 50 }, { 54 }, { 58 }, { 59 }
284 /*-----------------------------------------------------------------------
285 * symbolic names for the fields of DCF77 describes in "rawdcfcode".
286 * see comment above for the structure of the DCF77 data
309 /*-----------------------------------------------------------------------
310 * parity field table (same encoding as rawdcfcode)
311 * This table describes the sections of the DCF77 code that are
316 char offset; /* start bit of parity field */
319 { 21 }, { 29 }, { 36 }, { 59 }
322 /*-----------------------------------------------------------------------
323 * offsets for parity field descriptions
329 /*-----------------------------------------------------------------------
330 * legal values for time zone information
332 #define DCF_Z_MET 0x2
333 #define DCF_Z_MED 0x1
335 /*-----------------------------------------------------------------------
336 * symbolic representation if the DCF77 data stream
338 static struct dcfparam
340 unsigned char onebits[60];
341 unsigned char zerobits[60];
344 "###############RADMLS1248124P124812P1248121241248112481248P", /* 'ONE' representation */
345 "--------------------s-------p------p----------------------p" /* 'ZERO' representation */
348 /*-----------------------------------------------------------------------
349 * extract a bitfield from DCF77 datastream
350 * All numeric fields are LSB first.
351 * buf holds a pointer to a DCF77 data buffer in symbolic
353 * idx holds the index to the field description in rawdcfcode
357 register unsigned char *buf,
361 register unsigned long sum = 0;
362 register int i, first;
364 first = rawdcfcode[idx].offset;
366 for (i = rawdcfcode[idx+1].offset - 1; i >= first; i--)
369 sum |= (buf[i] != dcfparam.zerobits[i]);
374 /*-----------------------------------------------------------------------
375 * check even parity integrity for a bitfield
377 * buf holds a pointer to a DCF77 data buffer in symbolic
379 * idx holds the index to the field description in partab
383 register unsigned char *buf,
388 register unsigned psum = 1;
390 last = partab[idx+1].offset;
392 for (i = partab[idx].offset; i < last; i++)
393 psum ^= (buf[i] != dcfparam.zerobits[i]);
398 /*-----------------------------------------------------------------------
399 * convert a DCF77 data buffer into wall clock time + flags
401 * buffer holds a pointer to a DCF77 data buffer in symbolic
403 * size describes the length of DCF77 information in bits (represented
404 * as chars in symbolic notation
405 * clock points to a wall clock time description of the DCF77 data (result)
409 unsigned char *buffer,
411 clocktime_t *clock_time
416 PRINTF("%-30s", "*** INCOMPLETE");
421 * check Start and Parity bits
423 if ((ext_bf(buffer, DCF_S) == 1) &&
424 pcheck(buffer, DCF_P_P1) &&
425 pcheck(buffer, DCF_P_P2) &&
426 pcheck(buffer, DCF_P_P3))
429 * buffer OK - extract all fields and build wall clock time from them
432 clock_time->flags = 0;
433 clock_time->usecond= 0;
434 clock_time->second = 0;
435 clock_time->minute = ext_bf(buffer, DCF_M10);
436 clock_time->minute = TIMES10(clock_time->minute) + ext_bf(buffer, DCF_M1);
437 clock_time->hour = ext_bf(buffer, DCF_H10);
438 clock_time->hour = TIMES10(clock_time->hour) + ext_bf(buffer, DCF_H1);
439 clock_time->day = ext_bf(buffer, DCF_D10);
440 clock_time->day = TIMES10(clock_time->day) + ext_bf(buffer, DCF_D1);
441 clock_time->month = ext_bf(buffer, DCF_MO0);
442 clock_time->month = TIMES10(clock_time->month) + ext_bf(buffer, DCF_MO);
443 clock_time->year = ext_bf(buffer, DCF_Y10);
444 clock_time->year = TIMES10(clock_time->year) + ext_bf(buffer, DCF_Y1);
445 clock_time->wday = ext_bf(buffer, DCF_DW);
448 * determine offset to UTC by examining the time zone
450 switch (ext_bf(buffer, DCF_Z))
453 clock_time->utcoffset = -60;
457 clock_time->flags |= DCFB_DST;
458 clock_time->utcoffset = -120;
462 PRINTF("%-30s", "*** BAD TIME ZONE");
463 return CVT_FAIL|CVT_BADFMT;
467 * extract various warnings from DCF77
469 if (ext_bf(buffer, DCF_A1))
470 clock_time->flags |= DCFB_ANNOUNCE;
472 if (ext_bf(buffer, DCF_A2))
473 clock_time->flags |= DCFB_LEAP;
475 if (ext_bf(buffer, DCF_R))
476 clock_time->flags |= DCFB_ALTERNATE;
483 * bad format - not for us
485 PRINTF("%-30s", "*** BAD FORMAT (invalid/parity)");
486 return CVT_FAIL|CVT_BADFMT;
490 /*-----------------------------------------------------------------------
491 * raw dcf input routine - fix up 50 baud
492 * characters for 1/0 decision
496 unsigned char *buffer,
498 clocktime_t *clock_time
501 register unsigned char *s = buffer;
502 register unsigned char *e = buffer + size;
503 register unsigned char *b = dcfparam.onebits;
504 register unsigned char *c = dcfparam.zerobits;
505 register unsigned rtc = CVT_NONE;
506 register unsigned int i, lowmax, highmax, cutoff, span;
508 unsigned char histbuf[BITS];
510 * the input buffer contains characters with runs of consecutive
511 * bits set. These set bits are an indication of the DCF77 pulse
512 * length. We assume that we receive the pulse at 50 Baud. Thus
513 * a 100ms pulse would generate a 4 bit train (20ms per bit and
515 * a 200ms pulse would create all zeroes (and probably a frame error)
517 * The basic idea is that on corret reception we must have two
518 * maxima in the pulse length distribution histogram. (one for
519 * the zero representing pulses and one for the one representing
521 * There will always be ones in the datastream, thus we have to see
523 * The best point to cut for a 1/0 decision is the minimum between those
524 * between the maxima. The following code tries to find this cutoff point.
528 * clear histogram buffer
530 for (i = 0; i < BITS; i++)
539 * convert sequences of set bits into bits counts updating
540 * the histogram alongway
544 register unsigned int ch = *s ^ 0xFF;
546 * check integrity and update histogramm
548 if (!((ch+1) & ch) || !*s)
566 * invalid character (no consecutive bit sequence)
568 dprintf(("parse: cvt_rawdcf: character check for 0x%x@%d FAILED\n", *s, s - buffer));
569 *s = (unsigned char)~0;
570 rtc = CVT_FAIL|CVT_BADFMT;
576 * first cutoff estimate (average bit count - must be between both
585 cutoff = 4; /* doesn't really matter - it'll fail anyway, but gives error output */
588 dprintf(("parse: cvt_rawdcf: average bit count: %d\n", cutoff));
590 lowmax = 0; /* weighted sum */
591 highmax = 0; /* bitcount */
594 * collect weighted sum of lower bits (left of initial guess)
596 dprintf(("parse: cvt_rawdcf: histogram:"));
597 for (i = 0; i <= cutoff; i++)
599 lowmax += histbuf[i] * i;
600 highmax += histbuf[i];
601 dprintf((" %d", histbuf[i]));
608 lowmax += highmax / 2;
611 * calculate lower bit maximum (weighted sum / bit count)
613 * avoid divide by zero
624 highmax = 0; /* weighted sum of upper bits counts */
625 cutoff = 0; /* bitcount */
628 * collect weighted sum of lower bits (right of initial guess)
630 for (; i < BITS; i++)
632 highmax+=histbuf[i] * i;
634 dprintf((" %d", histbuf[i]));
639 * determine upper maximum (weighted sum / bit count)
651 * following now holds:
652 * lowmax <= cutoff(initial guess) <= highmax
653 * best cutoff is the minimum nearest to higher bits
657 * find the minimum between lowmax and highmax (detecting
658 * possibly a minimum span)
660 span = cutoff = lowmax;
661 for (i = lowmax; i <= highmax; i++)
663 if (histbuf[cutoff] > histbuf[i])
666 * got a new minimum move beginning of minimum (cutoff) and
667 * end of minimum (span) there
672 if (histbuf[cutoff] == histbuf[i])
675 * minimum not better yet - but it spans more than
676 * one bit value - follow it
683 * cutoff point for 1/0 decision is the middle of the minimum section
686 cutoff = (cutoff + span) / 2;
688 dprintf(("parse: cvt_rawdcf: lower maximum %d, higher maximum %d, cutoff %d\n", lowmax, highmax, cutoff));
691 * convert the bit counts to symbolic 1/0 information for data conversion
694 while ((s < e) && *c && *b)
696 if (*s == (unsigned char)~0)
706 * symbolic 1/0 representation
708 *s = (*s >= cutoff) ? *b : *c;
716 * if everything went well so far return the result of the symbolic
717 * conversion routine else just the accumulated errors
721 PRINTF("%-30s", "*** BAD DATA");
724 return (rtc == CVT_NONE) ? convert_rawdcf(buffer, size, clock_time) : rtc;
727 /*-----------------------------------------------------------------------
728 * convert a wall clock time description of DCF77 to a Unix time (seconds
729 * since 1.1. 1970 UTC)
733 clocktime_t *clock_time,
737 #define SETRTC(_X_) { if (cvtrtc) *cvtrtc = (_X_); }
738 static int days_of_month[] =
740 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
746 * map 2 digit years to 19xx (DCF77 is a 20th century item)
748 if ( clock_time->year < YEAR_PIVOT ) /* in case of Y2KFixes [ */
749 clock_time->year += 100; /* *year%100, make tm_year */
750 /* *(do we need this?) */
751 if ( clock_time->year < YEAR_BREAK ) /* (failsafe if) */
752 clock_time->year += 1900; /* Y2KFixes ] */
755 * must have been a really bad year code - drop it
757 if (clock_time->year < (YEAR_PIVOT + 1900) ) /* Y2KFixes */
759 SETRTC(CVT_FAIL|CVT_BADDATE);
763 * sorry, slow section here - but it's not time critical anyway
767 * calculate days since 1970 (watching leap years)
769 t = julian0( clock_time->year ) - julian0( 1970 );
772 if (clock_time->month <= 0 || clock_time->month > 12)
774 SETRTC(CVT_FAIL|CVT_BADDATE);
775 return -1; /* bad month */
777 /* adjust current leap year */
779 if (clock_time->month < 3 && days_per_year(clock_time->year) == 366)
784 * collect days from months excluding the current one
786 for (i = 1; i < clock_time->month; i++)
788 t += days_of_month[i];
791 if (clock_time->day < 1 || ((clock_time->month == 2 && days_per_year(clock_time->year) == 366) ?
792 clock_time->day > 29 : clock_time->day > days_of_month[clock_time->month]))
794 SETRTC(CVT_FAIL|CVT_BADDATE);
795 return -1; /* bad day */
799 * collect days from date excluding the current one
801 t += clock_time->day - 1;
804 if (clock_time->hour < 0 || clock_time->hour >= 24)
806 SETRTC(CVT_FAIL|CVT_BADTIME);
807 return -1; /* bad hour */
811 * calculate hours from 1. 1. 1970
813 t = TIMES24(t) + clock_time->hour;
816 if (clock_time->minute < 0 || clock_time->minute > 59)
818 SETRTC(CVT_FAIL|CVT_BADTIME);
819 return -1; /* bad min */
823 * calculate minutes from 1. 1. 1970
825 t = TIMES60(t) + clock_time->minute;
829 * calculate UTC in minutes
831 t += clock_time->utcoffset;
833 if (clock_time->second < 0 || clock_time->second > 60) /* allow for LEAPs */
835 SETRTC(CVT_FAIL|CVT_BADTIME);
836 return -1; /* bad sec */
840 * calculate UTC in seconds - phew !
842 t = TIMES60(t) + clock_time->second;
847 /*-----------------------------------------------------------------------
848 * cheap half baked 1/0 decision - for interactive operation only
859 /*-----------------------------------------------------------------------
860 * week day representation
862 static const char *wday[8] =
874 /*-----------------------------------------------------------------------
875 * generate a string representation for a timeval
884 if (val->tv_sec == 0)
885 sprintf(buf, "%c0.%06ld", (val->tv_usec < 0) ? '-' : '+', (long int)l_abs(val->tv_usec));
887 sprintf(buf, "%ld.%06ld", (long int)val->tv_sec, (long int)l_abs(val->tv_usec));
891 /*-----------------------------------------------------------------------
892 * correct the current time by an offset by setting the time rigorously
896 struct timeval *offset
899 struct timeval the_time;
904 LPRINTF("set_time: %s ", pr_timeval(offset));
905 syslog(LOG_NOTICE, "setting time (offset %s)", pr_timeval(offset));
907 if (gettimeofday(&the_time, 0L) == -1)
909 perror("gettimeofday()");
913 timeradd(&the_time, offset);
914 if (settimeofday(&the_time, 0L) == -1)
916 perror("settimeofday()");
921 /*-----------------------------------------------------------------------
922 * slew the time by a given offset
929 struct timeval time_offset;
934 time_offset.tv_sec = offset / 1000000;
935 time_offset.tv_usec = offset % 1000000;
937 LPRINTF("adj_time: %ld us ", (long int)offset);
938 if (adjtime(&time_offset, 0L) == -1)
942 /*-----------------------------------------------------------------------
943 * read in a possibly previously written drift value
947 const char *drift_file
952 df = fopen(drift_file, "r");
955 int idrift = 0, fdrift = 0;
957 fscanf(df, "%4d.%03d", &idrift, &fdrift);
959 LPRINTF("read_drift: %d.%03d ppm ", idrift, fdrift);
961 accum_drift = idrift << USECSCALE;
962 fdrift = (fdrift << USECSCALE) / 1000;
963 accum_drift += fdrift & (1<<USECSCALE);
964 LPRINTF("read_drift: drift_comp %ld ", (long int)accum_drift);
968 /*-----------------------------------------------------------------------
969 * write out the current drift value
973 const char *drift_file,
980 df = fopen(drift_file, "w");
983 int idrift = R_SHIFT(accum_drift, USECSCALE);
984 int fdrift = accum_drift & ((1<<USECSCALE)-1);
986 LPRINTF("update_drift: drift_comp %ld ", (long int)accum_drift);
987 fdrift = (fdrift * 1000) / (1<<USECSCALE);
988 fprintf(df, "%4d.%03d %c%ld.%06ld %.24s\n", idrift, fdrift,
989 (offset < 0) ? '-' : '+', (long int)(l_abs(offset) / 1000000),
990 (long int)(l_abs(offset) % 1000000), asctime(localtime(&reftime)));
992 LPRINTF("update_drift: %d.%03d ppm ", idrift, fdrift);
996 /*-----------------------------------------------------------------------
997 * process adjustments derived from the DCF77 observation
998 * (controls clock PLL)
1002 struct timeval *offset,
1003 const char *drift_file,
1007 struct timeval toffset;
1008 register long usecoffset;
1021 toffset.tv_sec = l_abs(toffset.tv_sec);
1022 toffset.tv_usec = l_abs(toffset.tv_usec);
1023 if (timercmp(&toffset, &max_adj_offset, >))
1026 * hopeless - set the clock - and clear the timing
1034 usecoffset = offset->tv_sec * 1000000 + offset->tv_usec;
1036 clock_adjust = R_SHIFT(usecoffset, TIMECONSTANT); /* adjustment to make for next period */
1039 while (adjustments > (1 << tmp))
1042 if (tmp > FREQ_WEIGHT)
1045 accum_drift += R_SHIFT(usecoffset << USECSCALE, TIMECONSTANT+TIMECONSTANT+FREQ_WEIGHT-tmp);
1047 if (accum_drift > MAX_DRIFT) /* clamp into interval */
1048 accum_drift = MAX_DRIFT;
1050 if (accum_drift < -MAX_DRIFT)
1051 accum_drift = -MAX_DRIFT;
1053 update_drift(drift_file, usecoffset, reftime);
1054 LPRINTF("clock_adjust: %s, clock_adjust %ld, drift_comp %ld(%ld) ",
1055 pr_timeval(offset),(long int) R_SHIFT(clock_adjust, USECSCALE),
1056 (long int)R_SHIFT(accum_drift, USECSCALE), (long int)accum_drift);
1059 /*-----------------------------------------------------------------------
1060 * adjust the clock by a small mount to simulate frequency correction
1067 register long adjustment;
1071 adjustment = R_SHIFT(clock_adjust, PHASE_WEIGHT);
1073 clock_adjust -= adjustment;
1075 adjustment += R_SHIFT(accum_drift, USECSCALE+ADJINTERVAL);
1077 adj_time(adjustment);
1080 /*-----------------------------------------------------------------------
1081 * control synchronisation status (warnings) and do periodic adjusts
1082 * (frequency control simulation)
1089 static unsigned long last_notice = 0;
1091 #if !defined(HAVE_SIGACTION) && !defined(HAVE_SIGVEC)
1092 (void)signal(SIGALRM, tick);
1097 ticks += 1<<ADJINTERVAL;
1099 if ((ticks - last_sync) > MAX_UNSYNC)
1102 * not getting time for a while
1104 if (sync_state == SYNC)
1107 * completely lost information
1109 sync_state = NO_SYNC;
1110 syslog(LOG_INFO, "DCF77 reception lost (timeout)");
1111 last_notice = ticks;
1115 * in NO_SYNC state - look whether its time to speak up again
1117 if ((ticks - last_notice) > NOTICE_INTERVAL)
1119 syslog(LOG_NOTICE, "still not synchronized to DCF77 - check receiver/signal");
1120 last_notice = ticks;
1125 (void) alarm(1<<ADJINTERVAL);
1129 /*-----------------------------------------------------------------------
1130 * break association from terminal to avoid catching terminal
1131 * or process group related signals (-> daemon operation)
1140 # else /* not HAVE_DAEMON */
1148 #if defined(HAVE_SYSCONF) && defined(_SC_OPEN_MAX)
1149 max_fd = sysconf(_SC_OPEN_MAX);
1150 #else /* HAVE_SYSCONF && _SC_OPEN_MAX */
1151 max_fd = getdtablesize();
1152 #endif /* HAVE_SYSCONF && _SC_OPEN_MAX */
1153 for (s = 0; s < max_fd; s++)
1154 (void) close((int)s);
1155 (void) open("/", 0);
1163 proc2_$who_am_i(&puid);
1164 proc2_$make_server(&puid, &st);
1166 #endif /* SYS_DOMAINOS */
1167 #if defined(HAVE_SETPGID) || defined(HAVE_SETSID)
1169 if (setsid() == (pid_t)-1)
1170 syslog(LOG_ERR, "dcfd: setsid(): %m");
1172 if (setpgid(0, 0) == -1)
1173 syslog(LOG_ERR, "dcfd: setpgid(): %m");
1175 #else /* HAVE_SETPGID || HAVE_SETSID */
1179 fid = open("/dev/tty", 2);
1182 (void) ioctl(fid, (u_long) TIOCNOTTY, (char *) 0);
1185 # ifdef HAVE_SETPGRP_0
1187 # else /* HAVE_SETPGRP_0 */
1188 (void) setpgrp(0, getpid());
1189 # endif /* HAVE_SETPGRP_0 */
1191 #endif /* HAVE_SETPGID || HAVE_SETSID */
1193 #endif /* not HAVE_DAEMON */
1196 /*-----------------------------------------------------------------------
1197 * list possible arguments and options
1204 fprintf(stderr, "usage: %s [-n] [-f] [-l] [-t] [-i] [-o] [-d <drift_file>] [-D <input delay>] <device>\n", program);
1205 fprintf(stderr, "\t-n do not change time\n");
1206 fprintf(stderr, "\t-i interactive\n");
1207 fprintf(stderr, "\t-t trace (print all datagrams)\n");
1208 fprintf(stderr, "\t-f print all databits (includes PTB private data)\n");
1209 fprintf(stderr, "\t-l print loop filter debug information\n");
1210 fprintf(stderr, "\t-o print offet average for current minute\n");
1211 fprintf(stderr, "\t-Y make internal Y2K checks then exit\n"); /* Y2KFixes */
1212 fprintf(stderr, "\t-d <drift_file> specify alternate drift file\n");
1213 fprintf(stderr, "\t-D <input delay>specify delay from input edge to processing in micro seconds\n");
1216 /*-----------------------------------------------------------------------
1217 * check_y2k() - internal check of Y2K logic
1218 * (a lot of this logic lifted from ../ntpd/check_y2k.c)
1223 int year; /* current working year */
1224 int year0 = 1900; /* sarting year for NTP time */
1225 int yearend; /* ending year we test for NTP time.
1226 * 32-bit systems: through 2036, the
1227 **year in which NTP time overflows.
1228 * 64-bit systems: a reasonable upper
1229 **limit (well, maybe somewhat beyond
1230 **reasonable, but well before the
1231 **max time, by which time the earth
1234 struct tm LocalTime;
1236 int Fatals, Warnings;
1237 #define Error(year) if ( (year)>=2036 && LocalTime.tm_year < 110 ) \
1238 Warnings++; else Fatals++
1240 Fatals = Warnings = 0;
1242 Time = time( (time_t *)NULL );
1243 LocalTime = *localtime( &Time );
1245 year = ( sizeof( u_long ) > 4 ) /* save max span using year as temp */
1246 ? ( 400 * 3 ) /* three greater gregorian cycles */
1247 : ((int)(0x7FFFFFFF / 365.242 / 24/60/60)* 2 ); /*32-bit limit*/
1248 /* NOTE: will automacially expand test years on
1249 * 64 bit machines.... this may cause some of the
1250 * existing ntp logic to fail for years beyond
1251 * 2036 (the current 32-bit limit). If all checks
1252 * fail ONLY beyond year 2036 you may ignore such
1253 * errors, at least for a decade or so. */
1254 yearend = year0 + year;
1256 year = 1900+YEAR_PIVOT;
1257 printf( " starting year %04d\n", (int) year );
1258 printf( " ending year %04d\n", (int) yearend );
1260 for ( ; year < yearend; year++ )
1271 ct.hour = ct.minute = ct.second = ct.usecond = 0;
1276 Observed = dcf_to_unixtime( &ct, &Flag );
1277 /* seems to be a clone of parse_to_unixtime() with
1278 * *a minor difference to arg2 type */
1279 if ( ct.year != year )
1282 "%04d: dcf_to_unixtime(,%d) CORRUPTED ct.year: was %d\n",
1283 (int)year, (int)Flag, (int)ct.year );
1287 t = julian0(year) - julian0(1970); /* Julian day from 1970 */
1288 Expected = t * 24 * 60 * 60;
1289 if ( Observed != Expected || Flag )
1290 { /* time difference */
1292 "%04d: dcf_to_unixtime(,%d) FAILURE: was=%lu s/b=%lu (%ld)\n",
1294 (unsigned long)Observed, (unsigned long)Expected,
1295 ((long)Observed - (long)Expected) );
1300 if ( year >= YEAR_PIVOT+1900 )
1302 /* check year % 100 code we put into dcf_to_unixtime() */
1303 ct.year = year % 100;
1306 Observed = dcf_to_unixtime( &ct, &Flag );
1308 if ( Observed != Expected || Flag )
1309 { /* time difference */
1311 "%04d: dcf_to_unixtime(%d,%d) FAILURE: was=%lu s/b=%lu (%ld)\n",
1312 year, (int)ct.year, (int)Flag,
1313 (unsigned long)Observed, (unsigned long)Expected,
1314 ((long)Observed - (long)Expected) );
1319 /* check year - 1900 code we put into dcf_to_unixtime() */
1320 ct.year = year - 1900;
1323 Observed = dcf_to_unixtime( &ct, &Flag );
1325 if ( Observed != Expected || Flag ) { /* time difference */
1327 "%04d: dcf_to_unixtime(%d,%d) FAILURE: was=%lu s/b=%lu (%ld)\n",
1328 year, (int)ct.year, (int)Flag,
1329 (unsigned long)Observed, (unsigned long)Expected,
1330 ((long)Observed - (long)Expected) );
1342 /*--------------------------------------------------
1343 * rawdcf_init - set up modem lines for RAWDCF receivers
1345 #if defined(TIOCMSET) && (defined(TIOCM_DTR) || defined(CIOCM_DTR))
1352 * You can use the RS232 to supply the power for a DCF77 receiver.
1353 * Here a voltage between the DTR and the RTS line is used. Unfortunately
1354 * the name has changed from CIOCM_DTR to TIOCM_DTR recently.
1358 int sl232 = TIOCM_DTR; /* turn on DTR for power supply */
1360 int sl232 = CIOCM_DTR; /* turn on DTR for power supply */
1363 if (ioctl(fd, TIOCMSET, (caddr_t)&sl232) == -1)
1365 syslog(LOG_NOTICE, "rawdcf_init: WARNING: ioctl(fd, TIOCMSET, [C|T]IOCM_DTR): %m");
1374 syslog(LOG_NOTICE, "rawdcf_init: WARNING: OS interface incapable of setting DTR to power DCF modules");
1376 #endif /* DTR initialisation type */
1378 /*-----------------------------------------------------------------------
1379 * main loop - argument interpreter / setup / main loop
1391 const char *drift_file = "/etc/dcfd.drift";
1395 int delay = DEFAULT_DELAY; /* average delay from input edge to time stamping */
1406 while ((c = *++arg))
1420 loop_filter_debug = 1;
1446 fprintf(stderr, "%s: -D requires integer argument\n", argv[0]);
1459 fprintf(stderr, "%s: -d requires file name argument\n", argv[0]);
1466 exit( errs ? 1 : 0 );
1469 fprintf(stderr, "%s: unknown option -%c\n", argv[0], c);
1478 fprintf(stderr, "%s: device specified twice\n", argv[0]);
1491 fprintf(stderr, "%s: device not specified\n", argv[0]);
1499 * get access to DCF77 tty port
1501 fd = open(file, O_RDONLY);
1510 struct timeval t, tt, tlast;
1511 struct timeval timeout;
1512 struct timeval phase;
1513 struct timeval time_offset;
1514 char pbuf[61]; /* printable version */
1515 char buf[61]; /* raw data */
1516 clocktime_t clock_time; /* wall clock time */
1517 time_t utc_time = 0;
1518 time_t last_utc_time = 0;
1521 #if defined(HAVE_TERMIOS_H) || defined(STREAM)
1522 struct termios term;
1523 #else /* not HAVE_TERMIOS_H || STREAM */
1524 # if defined(HAVE_TERMIO_H) || defined(HAVE_SYSV_TTYS)
1526 # endif/* HAVE_TERMIO_H || HAVE_SYSV_TTYS */
1527 #endif /* not HAVE_TERMIOS_H || STREAM */
1528 unsigned int rtc = CVT_NONE;
1533 timeout.tv_usec = 500000;
1536 phase.tv_usec = delay;
1539 * setup TTY (50 Baud, Read, 8Bit, No Hangup, 1 character IO)
1541 if (TTY_GETATTR(fd, &term) == -1)
1543 perror("tcgetattr");
1547 memset(term.c_cc, 0, sizeof(term.c_cc));
1548 term.c_cc[VMIN] = 1;
1549 #ifdef NO_PARENB_IGNPAR
1550 term.c_cflag = B50|CS8|CREAD|CLOCAL;
1552 term.c_cflag = B50|CS8|CREAD|CLOCAL|PARENB;
1554 term.c_iflag = IGNPAR;
1558 if (TTY_SETATTR(fd, &term) == -1)
1560 perror("tcsetattr");
1565 * loose terminal if in daemon operation
1571 * get syslog() initialized
1574 openlog("dcfd", LOG_PID, LOG_DAEMON);
1576 openlog("dcfd", LOG_PID);
1580 * setup periodic operations (state control / frequency control)
1586 vec.sv_handler = tick;
1590 if (sigvec(SIGALRM, &vec, (struct sigvec *)0) == -1)
1592 syslog(LOG_ERR, "sigvec(SIGALRM): %m");
1597 #ifdef HAVE_SIGACTION
1599 struct sigaction act;
1601 act.sa_handler = tick;
1602 # ifdef HAVE_SA_SIGACTION_IN_STRUCT_SIGACTION
1603 act.sa_sigaction = (void (*) P((int, siginfo_t *, void *)))0;
1604 # endif /* HAVE_SA_SIGACTION_IN_STRUCT_SIGACTION */
1605 sigemptyset(&act.sa_mask);
1608 if (sigaction(SIGALRM, &act, (struct sigaction *)0) == -1)
1610 syslog(LOG_ERR, "sigaction(SIGALRM): %m");
1615 (void) signal(SIGALRM, tick);
1621 struct itimerval it;
1623 it.it_interval.tv_sec = 1<<ADJINTERVAL;
1624 it.it_interval.tv_usec = 0;
1625 it.it_value.tv_sec = 1<<ADJINTERVAL;
1626 it.it_value.tv_usec = 0;
1628 if (setitimer(ITIMER_REAL, &it, (struct itimerval *)0) == -1)
1630 syslog(LOG_ERR, "setitimer: %m");
1635 (void) alarm(1<<ADJINTERVAL);
1638 PRINTF(" DCF77 monitor - Copyright (C) 1993-1998 by Frank Kardel\n\n");
1641 for ( i = 0; i < 60; i++)
1644 read_drift(drift_file);
1647 * what time is it now (for interval measurement)
1649 gettimeofday(&tlast, 0L);
1652 * loop until input trouble ...
1659 while ((rrc = read(fd, &c, 1)) == 1)
1661 gettimeofday(&t, 0L);
1663 timersub(&t, &tlast);
1667 PRINTF(" %s", &"PTB private....RADMLSMin....PHour..PMDay..DayMonthYear....P\n"[offset]);
1668 PRINTF(" %s", &"---------------RADMLS1248124P124812P1248121241248112481248P\n"[offset]);
1673 * timeout -> possible minute mark -> interpretation
1675 if (timercmp(&t, &timeout, >))
1677 PRINTF("%c %.*s ", pat[i % (sizeof(pat)-1)], 59 - offset, &pbuf[offset]);
1679 if ((rtc = cvt_rawdcf((unsigned char *)buf, i, &clock_time)) != CVT_OK)
1682 * this data was bad - well - forget synchronisation for now
1685 if (sync_state == SYNC)
1687 sync_state = NO_SYNC;
1688 syslog(LOG_INFO, "DCF77 reception lost (bad data)");
1695 PRINTF("\r %.*s ", 59 - offset, &buf[offset]);
1702 * collect first character
1704 if (((c^0xFF)+1) & (c^0xFF))
1707 pbuf[0] = type(c) ? '#' : '-';
1709 for ( i = 1; i < 60; i++)
1722 * initial guess (usually correct)
1724 if (((c^0xFF)+1) & (c^0xFF))
1727 pbuf[i] = type(c) ? '#' : '-';
1729 PRINTF("%c %.*s ", pat[i % (sizeof(pat)-1)], 59 - offset, &pbuf[offset]);
1732 if (i == 0 && rtc == CVT_OK)
1735 * we got a good time code here - try to convert it to
1738 if ((utc_time = dcf_to_unixtime(&clock_time, &rtc)) == -1)
1740 PRINTF("*** BAD CONVERSION\n");
1743 if (utc_time != (last_utc_time + 60))
1746 * well, two successive sucessful telegrams are not 60 seconds
1749 PRINTF("*** NO MINUTE INC\n");
1750 if (sync_state == SYNC)
1752 sync_state = NO_SYNC;
1753 syslog(LOG_INFO, "DCF77 reception lost (data mismatch)");
1756 rtc = CVT_FAIL|CVT_BADTIME|CVT_BADDATE;
1761 last_utc_time = utc_time;
1769 * valid time code - determine offset and
1770 * note regained reception
1773 if (sync_state == NO_SYNC)
1775 syslog(LOG_INFO, "receiving DCF77");
1780 * we had at least one minute SYNC - thus
1781 * last error is valid
1783 time_offset.tv_sec = lasterror / 1000000;
1784 time_offset.tv_usec = lasterror % 1000000;
1785 adjust_clock(&time_offset, drift_file, utc_time);
1790 time_offset.tv_sec = utc_time + i;
1791 time_offset.tv_usec = 0;
1793 timeradd(&time_offset, &phase);
1795 usecerror += (time_offset.tv_sec - tt.tv_sec) * 1000000 + time_offset.tv_usec
1799 * output interpreted DCF77 data
1801 PRINTF(offsets ? "%s, %2d:%02d:%02d, %d.%02d.%02d, <%s%s%s%s> (%c%d.%06ds)" :
1802 "%s, %2d:%02d:%02d, %d.%02d.%02d, <%s%s%s%s>",
1803 wday[clock_time.wday],
1804 clock_time.hour, clock_time.minute, i, clock_time.day, clock_time.month,
1806 (clock_time.flags & DCFB_ALTERNATE) ? "R" : "_",
1807 (clock_time.flags & DCFB_ANNOUNCE) ? "A" : "_",
1808 (clock_time.flags & DCFB_DST) ? "D" : "_",
1809 (clock_time.flags & DCFB_LEAP) ? "L" : "_",
1810 (lasterror < 0) ? '-' : '+', l_abs(lasterror) / 1000000, l_abs(lasterror) % 1000000
1813 if (trace && (i == 0))
1818 lasterror = usecerror / (i+1);
1822 lasterror = 0; /* we cannot calculate phase errors on bad reception */
1837 } while ((rrc == -1) && (errno == EINTR));
1840 * lost IO - sorry guys
1842 syslog(LOG_ERR, "TERMINATING - cannot read from device %s (%m)", file);