154359Sroberto/*
2182007Sroberto * /src/NTP/REPOSITORY/ntp4-dev/libparse/clk_rawdcf.c,v 4.18 2006/06/22 18:40:01 kardel RELEASE_20060622_A
3282408Scy *
4182007Sroberto * clk_rawdcf.c,v 4.18 2006/06/22 18:40:01 kardel RELEASE_20060622_A
554359Sroberto *
654359Sroberto * Raw DCF77 pulse clock support
754359Sroberto *
8285169Scy * Copyright (c) 1995-2015 by Frank Kardel <kardel <AT> ntp.org>
9282408Scy * Copyright (c) 1989-1994 by Frank Kardel, Friedrich-Alexander Universitaet Erlangen-Nuernberg, Germany
1054359Sroberto *
11182007Sroberto * Redistribution and use in source and binary forms, with or without
12182007Sroberto * modification, are permitted provided that the following conditions
13182007Sroberto * are met:
14182007Sroberto * 1. Redistributions of source code must retain the above copyright
15182007Sroberto *    notice, this list of conditions and the following disclaimer.
16182007Sroberto * 2. Redistributions in binary form must reproduce the above copyright
17182007Sroberto *    notice, this list of conditions and the following disclaimer in the
18182007Sroberto *    documentation and/or other materials provided with the distribution.
19182007Sroberto * 3. Neither the name of the author nor the names of its contributors
20182007Sroberto *    may be used to endorse or promote products derived from this software
21182007Sroberto *    without specific prior written permission.
22182007Sroberto *
23182007Sroberto * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
24182007Sroberto * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25182007Sroberto * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26182007Sroberto * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
27182007Sroberto * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28182007Sroberto * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29182007Sroberto * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30182007Sroberto * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31182007Sroberto * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32182007Sroberto * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33182007Sroberto * SUCH DAMAGE.
34182007Sroberto *
3554359Sroberto */
3654359Sroberto
3754359Sroberto#ifdef HAVE_CONFIG_H
3854359Sroberto# include <config.h>
3954359Sroberto#endif
4054359Sroberto
4154359Sroberto#if defined(REFCLOCK) && defined(CLOCK_PARSE) && defined(CLOCK_RAWDCF)
4254359Sroberto
4354359Sroberto#include "ntp_fp.h"
44285169Scy#include "timevalops.h"
4554359Sroberto#include "ntp_unixtime.h"
4654359Sroberto#include "ntp_calendar.h"
4754359Sroberto
4854359Sroberto#include "parse.h"
4954359Sroberto#ifdef PARSESTREAM
5054359Sroberto# include <sys/parsestreams.h>
5154359Sroberto#endif
5254359Sroberto
5354359Sroberto#ifndef PARSEKERNEL
5454359Sroberto# include "ntp_stdlib.h"
5554359Sroberto#endif
5654359Sroberto
5754359Sroberto/*
5854359Sroberto * DCF77 raw time code
5954359Sroberto *
6054359Sroberto * From "Zur Zeit", Physikalisch-Technische Bundesanstalt (PTB), Braunschweig
6154359Sroberto * und Berlin, Maerz 1989
6254359Sroberto *
6354359Sroberto * Timecode transmission:
6454359Sroberto * AM:
6554359Sroberto *	time marks are send every second except for the second before the
6654359Sroberto *	next minute mark
6754359Sroberto *	time marks consist of a reduction of transmitter power to 25%
6854359Sroberto *	of the nominal level
6954359Sroberto *	the falling edge is the time indication (on time)
7054359Sroberto *	time marks of a 100ms duration constitute a logical 0
7154359Sroberto *	time marks of a 200ms duration constitute a logical 1
7254359Sroberto * FM:
7354359Sroberto *	see the spec. (basically a (non-)inverted psuedo random phase shift)
7454359Sroberto *
7554359Sroberto * Encoding:
7654359Sroberto * Second	Contents
7754359Sroberto * 0  - 10	AM: free, FM: 0
7854359Sroberto * 11 - 14	free
79282408Scy * 15		R     - "call bit" used to signalize irregularities in the control facilities
80282408Scy *		        (until 2003 indicated transmission via alternate antenna)
8154359Sroberto * 16		A1    - expect zone change (1 hour before)
8254359Sroberto * 17 - 18	Z1,Z2 - time zone
8354359Sroberto *		 0  0 illegal
8454359Sroberto *		 0  1 MEZ  (MET)
8554359Sroberto *		 1  0 MESZ (MED, MET DST)
8654359Sroberto *		 1  1 illegal
8754359Sroberto * 19		A2    - expect leap insertion/deletion (1 hour before)
8854359Sroberto * 20		S     - start of time code (1)
8954359Sroberto * 21 - 24	M1    - BCD (lsb first) Minutes
9054359Sroberto * 25 - 27	M10   - BCD (lsb first) 10 Minutes
9154359Sroberto * 28		P1    - Minute Parity (even)
9254359Sroberto * 29 - 32	H1    - BCD (lsb first) Hours
9354359Sroberto * 33 - 34      H10   - BCD (lsb first) 10 Hours
9454359Sroberto * 35		P2    - Hour Parity (even)
9554359Sroberto * 36 - 39	D1    - BCD (lsb first) Days
9654359Sroberto * 40 - 41	D10   - BCD (lsb first) 10 Days
9754359Sroberto * 42 - 44	DW    - BCD (lsb first) day of week (1: Monday -> 7: Sunday)
9854359Sroberto * 45 - 49	MO    - BCD (lsb first) Month
9954359Sroberto * 50           MO0   - 10 Months
10054359Sroberto * 51 - 53	Y1    - BCD (lsb first) Years
10154359Sroberto * 54 - 57	Y10   - BCD (lsb first) 10 Years
10254359Sroberto * 58 		P3    - Date Parity (even)
10354359Sroberto * 59		      - usually missing (minute indication), except for leap insertion
10454359Sroberto */
10554359Sroberto
106282408Scystatic parse_pps_fnc_t pps_rawdcf;
107282408Scystatic parse_cvt_fnc_t cvt_rawdcf;
108282408Scystatic parse_inp_fnc_t inp_rawdcf;
10954359Sroberto
11056746Srobertotypedef struct last_tcode {
111285169Scy	time_t      tcode;	/* last converted time code */
112285169Scy        timestamp_t tminute;	/* sample time for minute start */
113285169Scy        timestamp_t timeout;	/* last timeout timestamp */
11456746Sroberto} last_tcode_t;
11556746Sroberto
116182007Sroberto#define BUFFER_MAX	61
117182007Sroberto
11854359Srobertoclockformat_t clock_rawdcf =
11954359Sroberto{
12054359Sroberto  inp_rawdcf,			/* DCF77 input handling */
12154359Sroberto  cvt_rawdcf,			/* raw dcf input conversion */
12254359Sroberto  pps_rawdcf,			/* examining PPS information */
12354359Sroberto  0,				/* no private configuration data */
12454359Sroberto  "RAW DCF77 Timecode",		/* direct decoding / time synthesis */
12554359Sroberto
126182007Sroberto  BUFFER_MAX,			/* bit buffer */
12756746Sroberto  sizeof(last_tcode_t)
12854359Sroberto};
12954359Sroberto
13054359Srobertostatic struct dcfparam
13154359Sroberto{
132280849Scy	const unsigned char *onebits;
133280849Scy	const unsigned char *zerobits;
134282408Scy} dcfparameter =
13554359Sroberto{
136280849Scy	(const unsigned char *)"###############RADMLS1248124P124812P1248121241248112481248P??", /* 'ONE' representation */
137280849Scy	(const unsigned char *)"--------------------s-------p------p----------------------p__"  /* 'ZERO' representation */
13854359Sroberto};
13954359Sroberto
140282408Scystatic struct rawdcfcode
14154359Sroberto{
14254359Sroberto	char offset;			/* start bit */
14354359Sroberto} rawdcfcode[] =
14454359Sroberto{
14554359Sroberto	{  0 }, { 15 }, { 16 }, { 17 }, { 19 }, { 20 }, { 21 }, { 25 }, { 28 }, { 29 },
14654359Sroberto	{ 33 }, { 35 }, { 36 }, { 40 }, { 42 }, { 45 }, { 49 }, { 50 }, { 54 }, { 58 }, { 59 }
14754359Sroberto};
14854359Sroberto
14954359Sroberto#define DCF_M	0
15054359Sroberto#define DCF_R	1
15154359Sroberto#define DCF_A1	2
15254359Sroberto#define DCF_Z	3
15354359Sroberto#define DCF_A2	4
15454359Sroberto#define DCF_S	5
15554359Sroberto#define DCF_M1	6
15654359Sroberto#define DCF_M10	7
15754359Sroberto#define DCF_P1	8
15854359Sroberto#define DCF_H1	9
15954359Sroberto#define DCF_H10	10
16054359Sroberto#define DCF_P2	11
16154359Sroberto#define DCF_D1	12
16254359Sroberto#define DCF_D10	13
16354359Sroberto#define DCF_DW	14
16454359Sroberto#define DCF_MO	15
16554359Sroberto#define DCF_MO0	16
16654359Sroberto#define DCF_Y1	17
16754359Sroberto#define DCF_Y10	18
16854359Sroberto#define DCF_P3	19
16954359Sroberto
17054359Srobertostatic struct partab
17154359Sroberto{
17254359Sroberto	char offset;			/* start bit of parity field */
17354359Sroberto} partab[] =
17454359Sroberto{
17554359Sroberto	{ 21 }, { 29 }, { 36 }, { 59 }
17654359Sroberto};
17754359Sroberto
17854359Sroberto#define DCF_P_P1	0
17954359Sroberto#define DCF_P_P2	1
18054359Sroberto#define DCF_P_P3	2
18154359Sroberto
18254359Sroberto#define DCF_Z_MET 0x2
18354359Sroberto#define DCF_Z_MED 0x1
18454359Sroberto
18554359Srobertostatic u_long
18654359Srobertoext_bf(
187182007Sroberto	unsigned char *buf,
188182007Sroberto	int   idx,
189280849Scy	const unsigned char *zero
19054359Sroberto	)
19154359Sroberto{
192182007Sroberto	u_long sum = 0;
193182007Sroberto	int i, first;
19454359Sroberto
19554359Sroberto	first = rawdcfcode[idx].offset;
196282408Scy
19754359Sroberto	for (i = rawdcfcode[idx+1].offset - 1; i >= first; i--)
19854359Sroberto	{
19954359Sroberto		sum <<= 1;
20054359Sroberto		sum |= (buf[i] != zero[i]);
20154359Sroberto	}
20254359Sroberto	return sum;
20354359Sroberto}
20454359Sroberto
20554359Srobertostatic unsigned
20654359Srobertopcheck(
20754359Sroberto       unsigned char *buf,
20854359Sroberto       int   idx,
209280849Scy       const unsigned char *zero
21054359Sroberto       )
21154359Sroberto{
21254359Sroberto	int i,last;
21354359Sroberto	unsigned psum = 1;
21454359Sroberto
21554359Sroberto	last = partab[idx+1].offset;
21654359Sroberto
21754359Sroberto	for (i = partab[idx].offset; i < last; i++)
21854359Sroberto	    psum ^= (buf[i] != zero[i]);
21954359Sroberto
22054359Sroberto	return psum;
22154359Sroberto}
22254359Sroberto
223358659Scystatic int/*BOOL*/
224358659Scyzeller_expand(
225358659Scy	clocktime_t     *clock_time,
226358659Scy	unsigned int	wd
227358659Scy	)
228358659Scy{
229358659Scy        unsigned int  y = (unsigned int)clock_time->year;
230358659Scy        unsigned int  m = (unsigned int)clock_time->month - 1u;
231358659Scy        unsigned int  d = (unsigned int)clock_time->day - 1u;
232358659Scy	unsigned int  c;
233358659Scy
234358659Scy	/* Check basic constraints first. */
235358659Scy        if ((y >= 100u) || (m >= 12u) || (d >= 31u) || (--wd >= 7u))
236358659Scy		return FALSE;
237358659Scy
238358659Scy	/* Get weekday of date in 1st century by a variation on Zeller's
239358659Scy	 * congruence. All operands are non-negative, and the month
240358659Scy	 * formula is adjusted to use a divider of 32, so we can do a
241358659Scy	 * shift instead of a 'true' division:
242358659Scy	 */
243358659Scy	if ((m += 10u) >= 12u)		/* shift base to 0000-03-01 */
244358659Scy		m -= 12u;
245358659Scy	else if (--y >= 100u)
246358659Scy		y += 100;
247358659Scy	d += y + (y >> 2) + 2u;		/* year-related share */
248358659Scy	d += (m * 83u + 16u) >> 5;	/* month-related share */
249358659Scy
250358659Scy	/* The next step combines the exact division by modular inverse
251358659Scy	 * with the (mod 7) step in such way that no true division and
252358659Scy	 * only one multiplication is needed. The multiplier is
253358659Scy	 *      M <- ceil((3*8)/7 * 2**29)
254358659Scy	 * and combines multiplication by invmod(5, 7) -> 3 and modulus
255358659Scy	 * by 7 transformation to (mod 8) in one step.
256358659Scy	 *   Note that 252 == 0 (mod 7) and that 'd' is less than 185,
257358659Scy	 * so the number to invert and reduce is strictly positive. In
258358659Scy	 * the end, 'c' is number of centuries since start of a great
259358659Scy	 * cycle and must be in [0..3] or we had bad input.
260358659Scy	 */
261358659Scy	c = (((252u + wd - d) * 0x6db6db6eU) >> 29) & 7u;
262358659Scy	if (c >= 4)
263358659Scy		return FALSE;
264358659Scy	/* undo calendar base shift now */
265358659Scy	if ((m > 9u) && (++y >= 100u)) {
266358659Scy		y -= 100u;
267358659Scy		c = (c + 1u) & 3u;
268358659Scy	}
269358659Scy	/* combine year with centuries & map to [1970..2369] */
270358659Scy	y += (c * 100u);
271358659Scy	clock_time->year = (int)y + ((y < 370u) ? 2000 : 1600);
272358659Scy	return TRUE;
273358659Scy}
274358659Scy
27554359Srobertostatic u_long
27654359Srobertoconvert_rawdcf(
27754359Sroberto	       unsigned char   *buffer,
27854359Sroberto	       int              size,
27954359Sroberto	       struct dcfparam *dcfprm,
28054359Sroberto	       clocktime_t     *clock_time
28154359Sroberto	       )
28254359Sroberto{
283182007Sroberto	unsigned char *s = buffer;
284280849Scy	const unsigned char *b = dcfprm->onebits;
285280849Scy	const unsigned char *c = dcfprm->zerobits;
286182007Sroberto	int i;
28754359Sroberto
288285169Scy	parseprintf(DD_RAWDCF,("parse: convert_rawdcf: \"%.*s\"\n", size, buffer));
28954359Sroberto
29054359Sroberto	if (size < 57)
29154359Sroberto	{
29254359Sroberto#ifndef PARSEKERNEL
293280849Scy		msyslog(LOG_ERR, "parse: convert_rawdcf: INCOMPLETE DATA - time code only has %d bits", size);
29454359Sroberto#endif
295285169Scy		return CVT_FAIL|CVT_BADFMT;
29654359Sroberto	}
297282408Scy
298182007Sroberto	for (i = 0; i < size; i++)
29954359Sroberto	{
30054359Sroberto		if ((*s != *b) && (*s != *c))
30154359Sroberto		{
30254359Sroberto			/*
30354359Sroberto			 * we only have two types of bytes (ones and zeros)
30454359Sroberto			 */
30554359Sroberto#ifndef PARSEKERNEL
306182007Sroberto			msyslog(LOG_ERR, "parse: convert_rawdcf: BAD DATA - no conversion");
30754359Sroberto#endif
308285169Scy			return CVT_FAIL|CVT_BADFMT;
30954359Sroberto		}
310182007Sroberto		if (*b) b++;
311182007Sroberto		if (*c) c++;
31254359Sroberto		s++;
31354359Sroberto	}
314182007Sroberto
31554359Sroberto	/*
31654359Sroberto	 * check Start and Parity bits
31754359Sroberto	 */
31854359Sroberto	if ((ext_bf(buffer, DCF_S, dcfprm->zerobits) == 1) &&
31954359Sroberto	    pcheck(buffer, DCF_P_P1, dcfprm->zerobits) &&
32054359Sroberto	    pcheck(buffer, DCF_P_P2, dcfprm->zerobits) &&
32154359Sroberto	    pcheck(buffer, DCF_P_P3, dcfprm->zerobits))
32254359Sroberto	{
32354359Sroberto		/*
32454359Sroberto		 * buffer OK
32554359Sroberto		 */
32654359Sroberto		parseprintf(DD_RAWDCF,("parse: convert_rawdcf: parity check passed\n"));
32754359Sroberto
328285169Scy		clock_time->flags  = PARSEB_S_CALLBIT|PARSEB_S_LEAP;
32954359Sroberto		clock_time->utctime= 0;
33054359Sroberto		clock_time->usecond= 0;
33154359Sroberto		clock_time->second = 0;
33254359Sroberto		clock_time->minute = ext_bf(buffer, DCF_M10, dcfprm->zerobits);
33354359Sroberto		clock_time->minute = TIMES10(clock_time->minute) + ext_bf(buffer, DCF_M1, dcfprm->zerobits);
33454359Sroberto		clock_time->hour   = ext_bf(buffer, DCF_H10, dcfprm->zerobits);
33554359Sroberto		clock_time->hour   = TIMES10(clock_time->hour) + ext_bf(buffer, DCF_H1, dcfprm->zerobits);
33654359Sroberto		clock_time->day    = ext_bf(buffer, DCF_D10, dcfprm->zerobits);
33754359Sroberto		clock_time->day    = TIMES10(clock_time->day) + ext_bf(buffer, DCF_D1, dcfprm->zerobits);
33854359Sroberto		clock_time->month  = ext_bf(buffer, DCF_MO0, dcfprm->zerobits);
33954359Sroberto		clock_time->month  = TIMES10(clock_time->month) + ext_bf(buffer, DCF_MO, dcfprm->zerobits);
34054359Sroberto		clock_time->year   = ext_bf(buffer, DCF_Y10, dcfprm->zerobits);
34154359Sroberto		clock_time->year   = TIMES10(clock_time->year) + ext_bf(buffer, DCF_Y1, dcfprm->zerobits);
34254359Sroberto
343358659Scy		if (!zeller_expand(clock_time, ext_bf(buffer, DCF_DW, dcfprm->zerobits)))
344358659Scy		    return CVT_FAIL|CVT_BADFMT;
345358659Scy
34654359Sroberto		switch (ext_bf(buffer, DCF_Z, dcfprm->zerobits))
34754359Sroberto		{
34854359Sroberto		    case DCF_Z_MET:
34954359Sroberto			clock_time->utcoffset = -1*60*60;
35054359Sroberto			break;
35154359Sroberto
35254359Sroberto		    case DCF_Z_MED:
35354359Sroberto			clock_time->flags     |= PARSEB_DST;
35454359Sroberto			clock_time->utcoffset  = -2*60*60;
35554359Sroberto			break;
35654359Sroberto
35754359Sroberto		    default:
35854359Sroberto			parseprintf(DD_RAWDCF,("parse: convert_rawdcf: BAD TIME ZONE\n"));
35954359Sroberto			return CVT_FAIL|CVT_BADFMT;
36054359Sroberto		}
36154359Sroberto
36254359Sroberto		if (ext_bf(buffer, DCF_A1, dcfprm->zerobits))
36354359Sroberto		    clock_time->flags |= PARSEB_ANNOUNCE;
36454359Sroberto
36554359Sroberto		if (ext_bf(buffer, DCF_A2, dcfprm->zerobits))
36654359Sroberto		    clock_time->flags |= PARSEB_LEAPADD; /* default: DCF77 data format deficiency */
36754359Sroberto
36854359Sroberto		if (ext_bf(buffer, DCF_R, dcfprm->zerobits))
369282408Scy		    clock_time->flags |= PARSEB_CALLBIT;
37054359Sroberto
371285169Scy		parseprintf(DD_RAWDCF,("parse: convert_rawdcf: TIME CODE OK: %02d:%02d, %02d.%02d.%02d, flags 0x%lx\n",
37254359Sroberto				       (int)clock_time->hour, (int)clock_time->minute, (int)clock_time->day, (int)clock_time->month,(int) clock_time->year,
37354359Sroberto				       (u_long)clock_time->flags));
37454359Sroberto		return CVT_OK;
37554359Sroberto	}
37654359Sroberto	else
37754359Sroberto	{
37854359Sroberto		/*
37954359Sroberto		 * bad format - not for us
38054359Sroberto		 */
38154359Sroberto#ifndef PARSEKERNEL
382285169Scy		msyslog(LOG_ERR, "parse: convert_rawdcf: start bit / parity check FAILED for \"%.*s\"", size, buffer);
38354359Sroberto#endif
38454359Sroberto		return CVT_FAIL|CVT_BADFMT;
38554359Sroberto	}
38654359Sroberto}
38754359Sroberto
38854359Sroberto/*
389282408Scy * parse_cvt_fnc_t cvt_rawdcf
39054359Sroberto * raw dcf input routine - needs to fix up 50 baud
39154359Sroberto * characters for 1/0 decision
39254359Sroberto */
39354359Srobertostatic u_long
39454359Srobertocvt_rawdcf(
39554359Sroberto	   unsigned char   *buffer,
39654359Sroberto	   int              size,
39754359Sroberto	   struct format   *param,
39854359Sroberto	   clocktime_t     *clock_time,
39954359Sroberto	   void            *local
40054359Sroberto	   )
40154359Sroberto{
402182007Sroberto	last_tcode_t  *t = (last_tcode_t *)local;
403182007Sroberto	unsigned char *s = (unsigned char *)buffer;
404182007Sroberto	unsigned char *e = s + size;
405280849Scy	const unsigned char *b = dcfparameter.onebits;
406280849Scy	const unsigned char *c = dcfparameter.zerobits;
407182007Sroberto	u_long       rtc = CVT_NONE;
408182007Sroberto	unsigned int i, lowmax, highmax, cutoff, span;
40954359Sroberto#define BITS 9
41054359Sroberto	unsigned char     histbuf[BITS];
41154359Sroberto	/*
41254359Sroberto	 * the input buffer contains characters with runs of consecutive
41354359Sroberto	 * bits set. These set bits are an indication of the DCF77 pulse
41454359Sroberto	 * length. We assume that we receive the pulse at 50 Baud. Thus
41554359Sroberto	 * a 100ms pulse would generate a 4 bit train (20ms per bit and
41654359Sroberto	 * start bit)
41754359Sroberto	 * a 200ms pulse would create all zeroes (and probably a frame error)
41854359Sroberto	 */
41954359Sroberto
42054359Sroberto	for (i = 0; i < BITS; i++)
42154359Sroberto	{
42254359Sroberto		histbuf[i] = 0;
42354359Sroberto	}
42454359Sroberto
42554359Sroberto	cutoff = 0;
42654359Sroberto	lowmax = 0;
42754359Sroberto
42854359Sroberto	while (s < e)
42954359Sroberto	{
430182007Sroberto		unsigned int ch = *s ^ 0xFF;
43154359Sroberto		/*
43254359Sroberto		 * these lines are left as an excercise to the reader 8-)
43354359Sroberto		 */
43454359Sroberto		if (!((ch+1) & ch) || !*s)
43554359Sroberto		{
43654359Sroberto
43754359Sroberto			for (i = 0; ch; i++)
43854359Sroberto			{
43954359Sroberto				ch >>= 1;
44054359Sroberto			}
44154359Sroberto
442282408Scy			*s = (unsigned char) i;
44354359Sroberto			histbuf[i]++;
44454359Sroberto			cutoff += i;
44554359Sroberto			lowmax++;
44654359Sroberto		}
44754359Sroberto		else
44854359Sroberto		{
44954359Sroberto			parseprintf(DD_RAWDCF,("parse: cvt_rawdcf: character check for 0x%x@%d FAILED\n", *s, (int)(s - (unsigned char *)buffer)));
45054359Sroberto			*s = (unsigned char)~0;
45154359Sroberto			rtc = CVT_FAIL|CVT_BADFMT;
45254359Sroberto		}
45354359Sroberto		s++;
45454359Sroberto	}
45554359Sroberto
45654359Sroberto	if (lowmax)
45754359Sroberto	{
45854359Sroberto		cutoff /= lowmax;
45954359Sroberto	}
46054359Sroberto	else
46154359Sroberto	{
46254359Sroberto		cutoff = 4;	/* doesn't really matter - it'll fail anyway, but gives error output */
46354359Sroberto	}
46454359Sroberto
46554359Sroberto	parseprintf(DD_RAWDCF,("parse: cvt_rawdcf: average bit count: %d\n", cutoff));
46654359Sroberto
46754359Sroberto	lowmax = 0;
46854359Sroberto	highmax = 0;
46954359Sroberto
47054359Sroberto	parseprintf(DD_RAWDCF,("parse: cvt_rawdcf: histogram:"));
47154359Sroberto	for (i = 0; i <= cutoff; i++)
47254359Sroberto	{
47354359Sroberto		lowmax+=histbuf[i] * i;
47454359Sroberto		highmax += histbuf[i];
47554359Sroberto		parseprintf(DD_RAWDCF,(" %d", histbuf[i]));
47654359Sroberto	}
47754359Sroberto	parseprintf(DD_RAWDCF, (" <M>"));
47854359Sroberto
47954359Sroberto	lowmax += highmax / 2;
48054359Sroberto
48154359Sroberto	if (highmax)
48254359Sroberto	{
48354359Sroberto		lowmax /= highmax;
48454359Sroberto	}
48554359Sroberto	else
48654359Sroberto	{
48754359Sroberto		lowmax = 0;
48854359Sroberto	}
48954359Sroberto
49054359Sroberto	highmax = 0;
49154359Sroberto	cutoff = 0;
49254359Sroberto
49354359Sroberto	for (; i < BITS; i++)
49454359Sroberto	{
49554359Sroberto		highmax+=histbuf[i] * i;
49654359Sroberto		cutoff +=histbuf[i];
49754359Sroberto		parseprintf(DD_RAWDCF,(" %d", histbuf[i]));
49854359Sroberto	}
49954359Sroberto	parseprintf(DD_RAWDCF,("\n"));
50054359Sroberto
50154359Sroberto	if (cutoff)
50254359Sroberto	{
50354359Sroberto		highmax /= cutoff;
50454359Sroberto	}
50554359Sroberto	else
50654359Sroberto	{
50754359Sroberto		highmax = BITS-1;
50854359Sroberto	}
50954359Sroberto
51054359Sroberto	span = cutoff = lowmax;
51154359Sroberto	for (i = lowmax; i <= highmax; i++)
51254359Sroberto	{
51354359Sroberto		if (histbuf[cutoff] > histbuf[i])
51454359Sroberto		{
51554359Sroberto			cutoff = i;
51654359Sroberto			span = i;
51754359Sroberto		}
51854359Sroberto		else
51954359Sroberto		    if (histbuf[cutoff] == histbuf[i])
52054359Sroberto		    {
52154359Sroberto			    span = i;
52254359Sroberto		    }
52354359Sroberto	}
52454359Sroberto
52554359Sroberto	cutoff = (cutoff + span) / 2;
52654359Sroberto
52754359Sroberto	parseprintf(DD_RAWDCF,("parse: cvt_rawdcf: lower maximum %d, higher maximum %d, cutoff %d\n", lowmax, highmax, cutoff));
52854359Sroberto
52954359Sroberto	s = (unsigned char *)buffer;
530182007Sroberto	while (s < e)
53154359Sroberto	{
53254359Sroberto		if (*s == (unsigned char)~0)
53354359Sroberto		{
53454359Sroberto			*s = '?';
53554359Sroberto		}
53654359Sroberto		else
53754359Sroberto		{
53854359Sroberto			*s = (*s >= cutoff) ? *b : *c;
53954359Sroberto		}
54054359Sroberto		s++;
541182007Sroberto		if (*b) b++;
542182007Sroberto		if (*c) c++;
54354359Sroberto	}
54454359Sroberto
545285169Scy	*s = '\0';
546285169Scy
54756746Sroberto        if (rtc == CVT_NONE)
54856746Sroberto        {
54956746Sroberto	       rtc = convert_rawdcf(buffer, size, &dcfparameter, clock_time);
55056746Sroberto	       if (rtc == CVT_OK)
55156746Sroberto	       {
55256746Sroberto			time_t newtime;
55356746Sroberto
55456746Sroberto			newtime = parse_to_unixtime(clock_time, &rtc);
55556746Sroberto			if ((rtc == CVT_OK) && t)
55656746Sroberto			{
557285169Scy				if ((newtime - t->tcode) <= 600) /* require a successful telegram within last 10 minutes */
55856746Sroberto				{
559285169Scy				        parseprintf(DD_RAWDCF,("parse: cvt_rawdcf: recent timestamp check OK\n"));
56056746Sroberto					clock_time->utctime = newtime;
56156746Sroberto				}
56256746Sroberto				else
56356746Sroberto				{
564285169Scy					parseprintf(DD_RAWDCF,("parse: cvt_rawdcf: recent timestamp check FAIL - ignore timestamp\n"));
565285169Scy					rtc = CVT_SKIP;
56656746Sroberto				}
56756746Sroberto				t->tcode            = newtime;
56856746Sroberto			}
56956746Sroberto	       }
57056746Sroberto        }
571282408Scy
57256746Sroberto    	return rtc;
57354359Sroberto}
57454359Sroberto
57554359Sroberto/*
576282408Scy * parse_pps_fnc_t pps_rawdcf
57754359Sroberto *
57854359Sroberto * currently a very stupid version - should be extended to decode
57954359Sroberto * also ones and zeros (which is easy)
58054359Sroberto */
58154359Sroberto/*ARGSUSED*/
58254359Srobertostatic u_long
58354359Srobertopps_rawdcf(
584182007Sroberto	parse_t *parseio,
585182007Sroberto	int status,
586182007Sroberto	timestamp_t *ptime
58754359Sroberto	)
58854359Sroberto{
58954359Sroberto	if (!status)		/* negative edge for simpler wiring (Rx->DCD) */
59054359Sroberto	{
59154359Sroberto		parseio->parse_dtime.parse_ptime  = *ptime;
59254359Sroberto		parseio->parse_dtime.parse_state |= PARSEB_PPS|PARSEB_S_PPS;
59354359Sroberto	}
59454359Sroberto
59554359Sroberto	return CVT_NONE;
59654359Sroberto}
59754359Sroberto
598285169Scystatic long
599285169Scycalc_usecdiff(
600285169Scy	timestamp_t *ref,
601285169Scy	timestamp_t *base,
602285169Scy	long         offset
603285169Scy	)
604285169Scy{
605285169Scy	struct timeval delta;
606285169Scy	long delta_usec = 0;
607285169Scy
608285169Scy#ifdef PARSEKERNEL
609285169Scy	delta.tv_sec = ref->tv.tv_sec - offset - base->tv.tv_sec;
610285169Scy	delta.tv_usec = ref->tv.tv_usec - base->tv.tv_usec;
611285169Scy	if (delta.tv_usec < 0)
612285169Scy	{
613285169Scy		delta.tv_sec  -= 1;
614285169Scy		delta.tv_usec += 1000000;
615285169Scy	}
616285169Scy#else
617285169Scy	l_fp delt;
618285169Scy
619285169Scy	delt = ref->fp;
620285169Scy	delt.l_i -= offset;
621285169Scy	L_SUB(&delt, &base->fp);
622285169Scy	TSTOTV(&delt, &delta);
623285169Scy#endif
624285169Scy
625285169Scy	delta_usec = 1000000 * (int32_t)delta.tv_sec + delta.tv_usec;
626285169Scy	return delta_usec;
627285169Scy}
628285169Scy
62954359Srobertostatic u_long
63054359Srobertosnt_rawdcf(
631182007Sroberto	parse_t *parseio,
632182007Sroberto	timestamp_t *ptime
63354359Sroberto	)
63454359Sroberto{
635285169Scy	/*
636285169Scy	 * only synthesize if all of following conditions are met:
637285169Scy	 * - CVT_OK parse_status (we have a time stamp base)
638285169Scy	 * - ABS(ptime - tminute - (parse_index - 1) sec) < 500ms (spaced by 1 sec +- 500ms)
639285169Scy	 * - minute marker is available (confirms minute raster as base)
640285169Scy	 */
641285169Scy	last_tcode_t  *t = (last_tcode_t *)parseio->parse_pdata;
642285169Scy	long delta_usec = -1;
643285169Scy
644285169Scy	if (t != NULL && t->tminute.tv.tv_sec != 0) {
645285169Scy		delta_usec = calc_usecdiff(ptime, &t->tminute, parseio->parse_index - 1);
646285169Scy		if (delta_usec < 0)
647285169Scy			delta_usec = -delta_usec;
648285169Scy	}
649285169Scy
650285169Scy	parseprintf(DD_RAWDCF,("parse: snt_rawdcf: synth for offset %d seconds - absolute usec error %ld\n",
651285169Scy			       parseio->parse_index - 1, delta_usec));
652285169Scy
653285169Scy	if (((parseio->parse_dtime.parse_status & CVT_MASK) == CVT_OK) &&
654285169Scy	    (delta_usec < 500000 && delta_usec >= 0)) /* only if minute marker is available */
65554359Sroberto	{
65654359Sroberto		parseio->parse_dtime.parse_stime = *ptime;
65754359Sroberto
65854359Sroberto#ifdef PARSEKERNEL
65954359Sroberto		parseio->parse_dtime.parse_time.tv.tv_sec++;
66054359Sroberto#else
66154359Sroberto		parseio->parse_dtime.parse_time.fp.l_ui++;
66254359Sroberto#endif
663282408Scy
66454359Sroberto		parseprintf(DD_RAWDCF,("parse: snt_rawdcf: time stamp synthesized offset %d seconds\n", parseio->parse_index - 1));
665282408Scy
66654359Sroberto		return updatetimeinfo(parseio, parseio->parse_lstate);
66754359Sroberto	}
66854359Sroberto	return CVT_NONE;
66954359Sroberto}
67054359Sroberto
67154359Sroberto/*
672282408Scy * parse_inp_fnc_t inp_rawdcf
67354359Sroberto *
674182007Sroberto * grab DCF77 data from input stream
67554359Sroberto */
67654359Srobertostatic u_long
67754359Srobertoinp_rawdcf(
67854359Sroberto	  parse_t      *parseio,
679282408Scy	  char         ch,
68054359Sroberto	  timestamp_t  *tstamp
68154359Sroberto	  )
68254359Sroberto{
68354359Sroberto	static struct timeval timeout = { 1, 500000 }; /* 1.5 secongs denote second #60 */
684282408Scy
685293423Sdelphij	parseprintf(DD_PARSE, ("inp_rawdcf(0x%p, 0x%x, ...)\n", (void*)parseio, ch));
686282408Scy
68754359Sroberto	parseio->parse_dtime.parse_stime = *tstamp; /* collect timestamp */
68854359Sroberto
68954359Sroberto	if (parse_timedout(parseio, tstamp, &timeout))
69054359Sroberto	{
691285169Scy		last_tcode_t *t = (last_tcode_t *)parseio->parse_pdata;
692285169Scy		long delta_usec;
693285169Scy
694285169Scy		parseprintf(DD_RAWDCF, ("inp_rawdcf: time out seen\n"));
695285169Scy		/* finish collection */
696285169Scy		(void) parse_end(parseio);
69754359Sroberto
698285169Scy		if (t != NULL)
699285169Scy		{
700285169Scy			/* remember minute start sample time if timeouts occur in minute raster */
701285169Scy			if (t->timeout.tv.tv_sec != 0)
702285169Scy			{
703285169Scy				delta_usec = calc_usecdiff(tstamp, &t->timeout, 60);
704285169Scy				if (delta_usec < 0)
705285169Scy					delta_usec = -delta_usec;
706285169Scy			}
707285169Scy			else
708285169Scy			{
709285169Scy				delta_usec = -1;
710285169Scy			}
711285169Scy
712285169Scy			if (delta_usec < 500000 && delta_usec >= 0)
713285169Scy			{
714285169Scy				parseprintf(DD_RAWDCF, ("inp_rawdcf: timeout time difference %ld usec - minute marker set\n", delta_usec));
715285169Scy				/* collect minute markers only if spaced by 60 seconds */
716285169Scy				t->tminute = *tstamp;
717285169Scy			}
718285169Scy			else
719285169Scy			{
720285169Scy				parseprintf(DD_RAWDCF, ("inp_rawdcf: timeout time difference %ld usec - minute marker cleared\n", delta_usec));
721285169Scy				memset((char *)&t->tminute, 0, sizeof(t->tminute));
722285169Scy			}
723285169Scy			t->timeout = *tstamp;
724285169Scy		}
72554359Sroberto		(void) parse_addchar(parseio, ch);
726285169Scy
727285169Scy		/* pass up to higher layers */
72854359Sroberto		return PARSE_INP_TIME;
72954359Sroberto	}
73054359Sroberto	else
73154359Sroberto	{
73254359Sroberto		unsigned int rtc;
733282408Scy
73454359Sroberto		rtc = parse_addchar(parseio, ch);
73554359Sroberto		if (rtc == PARSE_INP_SKIP)
73654359Sroberto		{
73754359Sroberto			if (snt_rawdcf(parseio, tstamp) == CVT_OK)
73854359Sroberto				return PARSE_INP_SYNTH;
73954359Sroberto		}
74054359Sroberto		return rtc;
74154359Sroberto	}
74254359Sroberto}
74354359Sroberto
74454359Sroberto#else /* not (REFCLOCK && CLOCK_PARSE && CLOCK_RAWDCF) */
74554359Srobertoint clk_rawdcf_bs;
74654359Sroberto#endif /* not (REFCLOCK && CLOCK_PARSE && CLOCK_RAWDCF) */
74754359Sroberto
74854359Sroberto/*
74954359Sroberto * History:
75054359Sroberto *
75154359Sroberto * clk_rawdcf.c,v
752182007Sroberto * Revision 4.18  2006/06/22 18:40:01  kardel
753182007Sroberto * clean up signedness (gcc 4)
754182007Sroberto *
755182007Sroberto * Revision 4.17  2006/01/22 16:01:55  kardel
756182007Sroberto * update version information
757182007Sroberto *
758182007Sroberto * Revision 4.16  2006/01/22 15:51:22  kardel
759182007Sroberto * generate reasonable timecode output on invalid input
760182007Sroberto *
761182007Sroberto * Revision 4.15  2005/08/06 19:17:06  kardel
762182007Sroberto * clean log output
763182007Sroberto *
764182007Sroberto * Revision 4.14  2005/08/06 17:39:40  kardel
765182007Sroberto * cleanup size handling wrt/ to buffer boundaries
766182007Sroberto *
767182007Sroberto * Revision 4.13  2005/04/16 17:32:10  kardel
768182007Sroberto * update copyright
769182007Sroberto *
770182007Sroberto * Revision 4.12  2004/11/14 15:29:41  kardel
771182007Sroberto * support PPSAPI, upgrade Copyright to Berkeley style
772182007Sroberto *
77356746Sroberto * Revision 4.9  1999/12/06 13:42:23  kardel
77456746Sroberto * transfer correctly converted time codes always into tcode
77556746Sroberto *
77656746Sroberto * Revision 4.8  1999/11/28 09:13:50  kardel
77756746Sroberto * RECON_4_0_98F
77856746Sroberto *
77956746Sroberto * Revision 4.7  1999/04/01 20:07:20  kardel
78056746Sroberto * added checking for minutie increment of timestamps in clk_rawdcf.c
78156746Sroberto *
78254359Sroberto * Revision 4.6  1998/06/14 21:09:37  kardel
78354359Sroberto * Sun acc cleanup
78454359Sroberto *
78554359Sroberto * Revision 4.5  1998/06/13 12:04:16  kardel
78654359Sroberto * fix SYSV clock name clash
78754359Sroberto *
78854359Sroberto * Revision 4.4  1998/06/12 15:22:28  kardel
78954359Sroberto * fix prototypes
79054359Sroberto *
79154359Sroberto * Revision 4.3  1998/06/06 18:33:36  kardel
79254359Sroberto * simplified condidional compile expression
79354359Sroberto *
79454359Sroberto * Revision 4.2  1998/05/24 11:04:18  kardel
79554359Sroberto * triggering PPS on negative edge for simpler wiring (Rx->DCD)
79654359Sroberto *
79754359Sroberto * Revision 4.1  1998/05/24 09:39:53  kardel
79854359Sroberto * implementation of the new IO handling model
79954359Sroberto *
80054359Sroberto * Revision 4.0  1998/04/10 19:45:30  kardel
80154359Sroberto * Start 4.0 release version numbering
80254359Sroberto *
80354359Sroberto * from V3 3.24 log info deleted 1998/04/11 kardel
80454359Sroberto *
80554359Sroberto */
806