2 * /src/NTP/REPOSITORY/ntp4-dev/libparse/clk_rawdcf.c,v 4.18 2006/06/22 18:40:01 kardel RELEASE_20060622_A
4 * clk_rawdcf.c,v 4.18 2006/06/22 18:40:01 kardel RELEASE_20060622_A
6 * Raw DCF77 pulse clock support
8 * Copyright (c) 1995-2015 by Frank Kardel <kardel <AT> ntp.org>
9 * Copyright (c) 1989-1994 by Frank Kardel, Friedrich-Alexander Universitaet Erlangen-Nuernberg, Germany
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of the author nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
41 #if defined(REFCLOCK) && defined(CLOCK_PARSE) && defined(CLOCK_RAWDCF)
44 #include "timevalops.h"
45 #include "ntp_unixtime.h"
46 #include "ntp_calendar.h"
50 # include <sys/parsestreams.h>
54 # include "ntp_stdlib.h"
60 * From "Zur Zeit", Physikalisch-Technische Bundesanstalt (PTB), Braunschweig
61 * und Berlin, Maerz 1989
63 * Timecode transmission:
65 * time marks are send every second except for the second before the
67 * time marks consist of a reduction of transmitter power to 25%
68 * of the nominal level
69 * the falling edge is the time indication (on time)
70 * time marks of a 100ms duration constitute a logical 0
71 * time marks of a 200ms duration constitute a logical 1
73 * see the spec. (basically a (non-)inverted psuedo random phase shift)
77 * 0 - 10 AM: free, FM: 0
79 * 15 R - "call bit" used to signalize irregularities in the control facilities
80 * (until 2003 indicated transmission via alternate antenna)
81 * 16 A1 - expect zone change (1 hour before)
82 * 17 - 18 Z1,Z2 - time zone
85 * 1 0 MESZ (MED, MET DST)
87 * 19 A2 - expect leap insertion/deletion (1 hour before)
88 * 20 S - start of time code (1)
89 * 21 - 24 M1 - BCD (lsb first) Minutes
90 * 25 - 27 M10 - BCD (lsb first) 10 Minutes
91 * 28 P1 - Minute Parity (even)
92 * 29 - 32 H1 - BCD (lsb first) Hours
93 * 33 - 34 H10 - BCD (lsb first) 10 Hours
94 * 35 P2 - Hour Parity (even)
95 * 36 - 39 D1 - BCD (lsb first) Days
96 * 40 - 41 D10 - BCD (lsb first) 10 Days
97 * 42 - 44 DW - BCD (lsb first) day of week (1: Monday -> 7: Sunday)
98 * 45 - 49 MO - BCD (lsb first) Month
100 * 51 - 53 Y1 - BCD (lsb first) Years
101 * 54 - 57 Y10 - BCD (lsb first) 10 Years
102 * 58 P3 - Date Parity (even)
103 * 59 - usually missing (minute indication), except for leap insertion
106 static parse_pps_fnc_t pps_rawdcf;
107 static parse_cvt_fnc_t cvt_rawdcf;
108 static parse_inp_fnc_t inp_rawdcf;
110 typedef struct last_tcode {
111 time_t tcode; /* last converted time code */
112 timestamp_t tminute; /* sample time for minute start */
113 timestamp_t timeout; /* last timeout timestamp */
116 #define BUFFER_MAX 61
118 clockformat_t clock_rawdcf =
120 inp_rawdcf, /* DCF77 input handling */
121 cvt_rawdcf, /* raw dcf input conversion */
122 pps_rawdcf, /* examining PPS information */
123 0, /* no private configuration data */
124 "RAW DCF77 Timecode", /* direct decoding / time synthesis */
126 BUFFER_MAX, /* bit buffer */
130 static struct dcfparam
132 const unsigned char *onebits;
133 const unsigned char *zerobits;
136 (const unsigned char *)"###############RADMLS1248124P124812P1248121241248112481248P??", /* 'ONE' representation */
137 (const unsigned char *)"--------------------s-------p------p----------------------p__" /* 'ZERO' representation */
140 static struct rawdcfcode
142 char offset; /* start bit */
145 { 0 }, { 15 }, { 16 }, { 17 }, { 19 }, { 20 }, { 21 }, { 25 }, { 28 }, { 29 },
146 { 33 }, { 35 }, { 36 }, { 40 }, { 42 }, { 45 }, { 49 }, { 50 }, { 54 }, { 58 }, { 59 }
172 char offset; /* start bit of parity field */
175 { 21 }, { 29 }, { 36 }, { 59 }
182 #define DCF_Z_MET 0x2
183 #define DCF_Z_MED 0x1
189 const unsigned char *zero
195 first = rawdcfcode[idx].offset;
197 for (i = rawdcfcode[idx+1].offset - 1; i >= first; i--)
200 sum |= (buf[i] != zero[i]);
209 const unsigned char *zero
215 last = partab[idx+1].offset;
217 for (i = partab[idx].offset; i < last; i++)
218 psum ^= (buf[i] != zero[i]);
225 clocktime_t *clock_time,
229 unsigned int y = (unsigned int)clock_time->year;
230 unsigned int m = (unsigned int)clock_time->month - 1u;
231 unsigned int d = (unsigned int)clock_time->day - 1u;
234 /* Check basic constraints first. */
235 if ((y >= 100u) || (m >= 12u) || (d >= 31u) || (--wd >= 7u))
238 /* Get weekday of date in 1st century by a variation on Zeller's
239 * congruence. All operands are non-negative, and the month
240 * formula is adjusted to use a divider of 32, so we can do a
241 * shift instead of a 'true' division:
243 if ((m += 10u) >= 12u) /* shift base to 0000-03-01 */
245 else if (--y >= 100u)
247 d += y + (y >> 2) + 2u; /* year-related share */
248 d += (m * 83u + 16u) >> 5; /* month-related share */
250 /* The next step combines the exact division by modular inverse
251 * with the (mod 7) step in such way that no true division and
252 * only one multiplication is needed. The multiplier is
253 * M <- ceil((3*8)/7 * 2**29)
254 * and combines multiplication by invmod(5, 7) -> 3 and modulus
255 * by 7 transformation to (mod 8) in one step.
256 * Note that 252 == 0 (mod 7) and that 'd' is less than 185,
257 * so the number to invert and reduce is strictly positive. In
258 * the end, 'c' is number of centuries since start of a great
259 * cycle and must be in [0..3] or we had bad input.
261 c = (((252u + wd - d) * 0x6db6db6eU) >> 29) & 7u;
264 /* undo calendar base shift now */
265 if ((m > 9u) && (++y >= 100u)) {
269 /* combine year with centuries & map to [1970..2369] */
271 clock_time->year = (int)y + ((y < 370u) ? 2000 : 1600);
277 unsigned char *buffer,
279 struct dcfparam *dcfprm,
280 clocktime_t *clock_time
283 unsigned char *s = buffer;
284 const unsigned char *b = dcfprm->onebits;
285 const unsigned char *c = dcfprm->zerobits;
288 parseprintf(DD_RAWDCF,("parse: convert_rawdcf: \"%.*s\"\n", size, buffer));
293 msyslog(LOG_ERR, "parse: convert_rawdcf: INCOMPLETE DATA - time code only has %d bits", size);
295 return CVT_FAIL|CVT_BADFMT;
298 for (i = 0; i < size; i++)
300 if ((*s != *b) && (*s != *c))
303 * we only have two types of bytes (ones and zeros)
306 msyslog(LOG_ERR, "parse: convert_rawdcf: BAD DATA - no conversion");
308 return CVT_FAIL|CVT_BADFMT;
316 * check Start and Parity bits
318 if ((ext_bf(buffer, DCF_S, dcfprm->zerobits) == 1) &&
319 pcheck(buffer, DCF_P_P1, dcfprm->zerobits) &&
320 pcheck(buffer, DCF_P_P2, dcfprm->zerobits) &&
321 pcheck(buffer, DCF_P_P3, dcfprm->zerobits))
326 parseprintf(DD_RAWDCF,("parse: convert_rawdcf: parity check passed\n"));
328 clock_time->flags = PARSEB_S_CALLBIT|PARSEB_S_LEAP;
329 clock_time->utctime= 0;
330 clock_time->usecond= 0;
331 clock_time->second = 0;
332 clock_time->minute = ext_bf(buffer, DCF_M10, dcfprm->zerobits);
333 clock_time->minute = TIMES10(clock_time->minute) + ext_bf(buffer, DCF_M1, dcfprm->zerobits);
334 clock_time->hour = ext_bf(buffer, DCF_H10, dcfprm->zerobits);
335 clock_time->hour = TIMES10(clock_time->hour) + ext_bf(buffer, DCF_H1, dcfprm->zerobits);
336 clock_time->day = ext_bf(buffer, DCF_D10, dcfprm->zerobits);
337 clock_time->day = TIMES10(clock_time->day) + ext_bf(buffer, DCF_D1, dcfprm->zerobits);
338 clock_time->month = ext_bf(buffer, DCF_MO0, dcfprm->zerobits);
339 clock_time->month = TIMES10(clock_time->month) + ext_bf(buffer, DCF_MO, dcfprm->zerobits);
340 clock_time->year = ext_bf(buffer, DCF_Y10, dcfprm->zerobits);
341 clock_time->year = TIMES10(clock_time->year) + ext_bf(buffer, DCF_Y1, dcfprm->zerobits);
343 if (!zeller_expand(clock_time, ext_bf(buffer, DCF_DW, dcfprm->zerobits)))
344 return CVT_FAIL|CVT_BADFMT;
346 switch (ext_bf(buffer, DCF_Z, dcfprm->zerobits))
349 clock_time->utcoffset = -1*60*60;
353 clock_time->flags |= PARSEB_DST;
354 clock_time->utcoffset = -2*60*60;
358 parseprintf(DD_RAWDCF,("parse: convert_rawdcf: BAD TIME ZONE\n"));
359 return CVT_FAIL|CVT_BADFMT;
362 if (ext_bf(buffer, DCF_A1, dcfprm->zerobits))
363 clock_time->flags |= PARSEB_ANNOUNCE;
365 if (ext_bf(buffer, DCF_A2, dcfprm->zerobits))
366 clock_time->flags |= PARSEB_LEAPADD; /* default: DCF77 data format deficiency */
368 if (ext_bf(buffer, DCF_R, dcfprm->zerobits))
369 clock_time->flags |= PARSEB_CALLBIT;
371 parseprintf(DD_RAWDCF,("parse: convert_rawdcf: TIME CODE OK: %02d:%02d, %02d.%02d.%02d, flags 0x%lx\n",
372 (int)clock_time->hour, (int)clock_time->minute, (int)clock_time->day, (int)clock_time->month,(int) clock_time->year,
373 (u_long)clock_time->flags));
379 * bad format - not for us
382 msyslog(LOG_ERR, "parse: convert_rawdcf: start bit / parity check FAILED for \"%.*s\"", size, buffer);
384 return CVT_FAIL|CVT_BADFMT;
389 * parse_cvt_fnc_t cvt_rawdcf
390 * raw dcf input routine - needs to fix up 50 baud
391 * characters for 1/0 decision
395 unsigned char *buffer,
397 struct format *param,
398 clocktime_t *clock_time,
402 last_tcode_t *t = (last_tcode_t *)local;
403 unsigned char *s = (unsigned char *)buffer;
404 unsigned char *e = s + size;
405 const unsigned char *b = dcfparameter.onebits;
406 const unsigned char *c = dcfparameter.zerobits;
407 u_long rtc = CVT_NONE;
408 unsigned int i, lowmax, highmax, cutoff, span;
410 unsigned char histbuf[BITS];
412 * the input buffer contains characters with runs of consecutive
413 * bits set. These set bits are an indication of the DCF77 pulse
414 * length. We assume that we receive the pulse at 50 Baud. Thus
415 * a 100ms pulse would generate a 4 bit train (20ms per bit and
417 * a 200ms pulse would create all zeroes (and probably a frame error)
420 for (i = 0; i < BITS; i++)
430 unsigned int ch = *s ^ 0xFF;
432 * these lines are left as an excercise to the reader 8-)
434 if (!((ch+1) & ch) || !*s)
442 *s = (unsigned char) i;
449 parseprintf(DD_RAWDCF,("parse: cvt_rawdcf: character check for 0x%x@%d FAILED\n", *s, (int)(s - (unsigned char *)buffer)));
450 *s = (unsigned char)~0;
451 rtc = CVT_FAIL|CVT_BADFMT;
462 cutoff = 4; /* doesn't really matter - it'll fail anyway, but gives error output */
465 parseprintf(DD_RAWDCF,("parse: cvt_rawdcf: average bit count: %d\n", cutoff));
470 parseprintf(DD_RAWDCF,("parse: cvt_rawdcf: histogram:"));
471 for (i = 0; i <= cutoff; i++)
473 lowmax+=histbuf[i] * i;
474 highmax += histbuf[i];
475 parseprintf(DD_RAWDCF,(" %d", histbuf[i]));
477 parseprintf(DD_RAWDCF, (" <M>"));
479 lowmax += highmax / 2;
493 for (; i < BITS; i++)
495 highmax+=histbuf[i] * i;
497 parseprintf(DD_RAWDCF,(" %d", histbuf[i]));
499 parseprintf(DD_RAWDCF,("\n"));
510 span = cutoff = lowmax;
511 for (i = lowmax; i <= highmax; i++)
513 if (histbuf[cutoff] > histbuf[i])
519 if (histbuf[cutoff] == histbuf[i])
525 cutoff = (cutoff + span) / 2;
527 parseprintf(DD_RAWDCF,("parse: cvt_rawdcf: lower maximum %d, higher maximum %d, cutoff %d\n", lowmax, highmax, cutoff));
529 s = (unsigned char *)buffer;
532 if (*s == (unsigned char)~0)
538 *s = (*s >= cutoff) ? *b : *c;
549 rtc = convert_rawdcf(buffer, size, &dcfparameter, clock_time);
554 newtime = parse_to_unixtime(clock_time, &rtc);
555 if ((rtc == CVT_OK) && t)
557 if ((newtime - t->tcode) <= 600) /* require a successful telegram within last 10 minutes */
559 parseprintf(DD_RAWDCF,("parse: cvt_rawdcf: recent timestamp check OK\n"));
560 clock_time->utctime = newtime;
564 parseprintf(DD_RAWDCF,("parse: cvt_rawdcf: recent timestamp check FAIL - ignore timestamp\n"));
576 * parse_pps_fnc_t pps_rawdcf
578 * currently a very stupid version - should be extended to decode
579 * also ones and zeros (which is easy)
589 if (!status) /* negative edge for simpler wiring (Rx->DCD) */
591 parseio->parse_dtime.parse_ptime = *ptime;
592 parseio->parse_dtime.parse_state |= PARSEB_PPS|PARSEB_S_PPS;
605 struct timeval delta;
609 delta.tv_sec = ref->tv.tv_sec - offset - base->tv.tv_sec;
610 delta.tv_usec = ref->tv.tv_usec - base->tv.tv_usec;
611 if (delta.tv_usec < 0)
614 delta.tv_usec += 1000000;
621 L_SUB(&delt, &base->fp);
622 TSTOTV(&delt, &delta);
625 delta_usec = 1000000 * (int32_t)delta.tv_sec + delta.tv_usec;
636 * only synthesize if all of following conditions are met:
637 * - CVT_OK parse_status (we have a time stamp base)
638 * - ABS(ptime - tminute - (parse_index - 1) sec) < 500ms (spaced by 1 sec +- 500ms)
639 * - minute marker is available (confirms minute raster as base)
641 last_tcode_t *t = (last_tcode_t *)parseio->parse_pdata;
642 long delta_usec = -1;
644 if (t != NULL && t->tminute.tv.tv_sec != 0) {
645 delta_usec = calc_usecdiff(ptime, &t->tminute, parseio->parse_index - 1);
647 delta_usec = -delta_usec;
650 parseprintf(DD_RAWDCF,("parse: snt_rawdcf: synth for offset %d seconds - absolute usec error %ld\n",
651 parseio->parse_index - 1, delta_usec));
653 if (((parseio->parse_dtime.parse_status & CVT_MASK) == CVT_OK) &&
654 (delta_usec < 500000 && delta_usec >= 0)) /* only if minute marker is available */
656 parseio->parse_dtime.parse_stime = *ptime;
659 parseio->parse_dtime.parse_time.tv.tv_sec++;
661 parseio->parse_dtime.parse_time.fp.l_ui++;
664 parseprintf(DD_RAWDCF,("parse: snt_rawdcf: time stamp synthesized offset %d seconds\n", parseio->parse_index - 1));
666 return updatetimeinfo(parseio, parseio->parse_lstate);
672 * parse_inp_fnc_t inp_rawdcf
674 * grab DCF77 data from input stream
683 static struct timeval timeout = { 1, 500000 }; /* 1.5 secongs denote second #60 */
685 parseprintf(DD_PARSE, ("inp_rawdcf(0x%p, 0x%x, ...)\n", (void*)parseio, ch));
687 parseio->parse_dtime.parse_stime = *tstamp; /* collect timestamp */
689 if (parse_timedout(parseio, tstamp, &timeout))
691 last_tcode_t *t = (last_tcode_t *)parseio->parse_pdata;
694 parseprintf(DD_RAWDCF, ("inp_rawdcf: time out seen\n"));
695 /* finish collection */
696 (void) parse_end(parseio);
700 /* remember minute start sample time if timeouts occur in minute raster */
701 if (t->timeout.tv.tv_sec != 0)
703 delta_usec = calc_usecdiff(tstamp, &t->timeout, 60);
705 delta_usec = -delta_usec;
712 if (delta_usec < 500000 && delta_usec >= 0)
714 parseprintf(DD_RAWDCF, ("inp_rawdcf: timeout time difference %ld usec - minute marker set\n", delta_usec));
715 /* collect minute markers only if spaced by 60 seconds */
716 t->tminute = *tstamp;
720 parseprintf(DD_RAWDCF, ("inp_rawdcf: timeout time difference %ld usec - minute marker cleared\n", delta_usec));
721 memset((char *)&t->tminute, 0, sizeof(t->tminute));
723 t->timeout = *tstamp;
725 (void) parse_addchar(parseio, ch);
727 /* pass up to higher layers */
728 return PARSE_INP_TIME;
734 rtc = parse_addchar(parseio, ch);
735 if (rtc == PARSE_INP_SKIP)
737 if (snt_rawdcf(parseio, tstamp) == CVT_OK)
738 return PARSE_INP_SYNTH;
744 #else /* not (REFCLOCK && CLOCK_PARSE && CLOCK_RAWDCF) */
746 #endif /* not (REFCLOCK && CLOCK_PARSE && CLOCK_RAWDCF) */
752 * Revision 4.18 2006/06/22 18:40:01 kardel
753 * clean up signedness (gcc 4)
755 * Revision 4.17 2006/01/22 16:01:55 kardel
756 * update version information
758 * Revision 4.16 2006/01/22 15:51:22 kardel
759 * generate reasonable timecode output on invalid input
761 * Revision 4.15 2005/08/06 19:17:06 kardel
764 * Revision 4.14 2005/08/06 17:39:40 kardel
765 * cleanup size handling wrt/ to buffer boundaries
767 * Revision 4.13 2005/04/16 17:32:10 kardel
770 * Revision 4.12 2004/11/14 15:29:41 kardel
771 * support PPSAPI, upgrade Copyright to Berkeley style
773 * Revision 4.9 1999/12/06 13:42:23 kardel
774 * transfer correctly converted time codes always into tcode
776 * Revision 4.8 1999/11/28 09:13:50 kardel
779 * Revision 4.7 1999/04/01 20:07:20 kardel
780 * added checking for minutie increment of timestamps in clk_rawdcf.c
782 * Revision 4.6 1998/06/14 21:09:37 kardel
785 * Revision 4.5 1998/06/13 12:04:16 kardel
786 * fix SYSV clock name clash
788 * Revision 4.4 1998/06/12 15:22:28 kardel
791 * Revision 4.3 1998/06/06 18:33:36 kardel
792 * simplified condidional compile expression
794 * Revision 4.2 1998/05/24 11:04:18 kardel
795 * triggering PPS on negative edge for simpler wiring (Rx->DCD)
797 * Revision 4.1 1998/05/24 09:39:53 kardel
798 * implementation of the new IO handling model
800 * Revision 4.0 1998/04/10 19:45:30 kardel
801 * Start 4.0 release version numbering
803 * from V3 3.24 log info deleted 1998/04/11 kardel