1/*	$NetBSD: refclock_wwvb.c,v 1.2 2012/02/01 07:46:22 kardel Exp $	*/
2
3/*
4 * refclock_wwvb - clock driver for Spectracom WWVB and GPS receivers
5 */
6
7#ifdef HAVE_CONFIG_H
8#include <config.h>
9#endif
10
11#if defined(REFCLOCK) && defined(CLOCK_SPECTRACOM)
12
13#include "ntpd.h"
14#include "ntp_io.h"
15#include "ntp_refclock.h"
16#include "ntp_calendar.h"
17#include "ntp_stdlib.h"
18
19#include <stdio.h>
20#include <ctype.h>
21
22#ifdef HAVE_PPSAPI
23#include "ppsapi_timepps.h"
24#include "refclock_atom.h"
25#endif /* HAVE_PPSAPI */
26
27/*
28 * This driver supports the Spectracom Model 8170 and Netclock/2 WWVB
29 * Synchronized Clocks and the Netclock/GPS Master Clock. Both the WWVB
30 * and GPS clocks have proven reliable sources of time; however, the
31 * WWVB clocks have proven vulnerable to high ambient conductive RF
32 * interference. The claimed accuracy of the WWVB clocks is 100 us
33 * relative to the broadcast signal, while the claimed accuracy of the
34 * GPS clock is 50 ns; however, in most cases the actual accuracy is
35 * limited by the resolution of the timecode and the latencies of the
36 * serial interface and operating system.
37 *
38 * The WWVB and GPS clocks should be configured for 24-hour display,
39 * AUTO DST off, time zone 0 (UTC), data format 0 or 2 (see below) and
40 * baud rate 9600. If the clock is to used as the source for the IRIG
41 * Audio Decoder (refclock_irig.c in this distribution), it should be
42 * configured for AM IRIG output and IRIG format 1 (IRIG B with
43 * signature control). The GPS clock can be configured either to respond
44 * to a 'T' poll character or left running continuously.
45 *
46 * There are two timecode formats used by these clocks. Format 0, which
47 * is available with both the Netclock/2 and 8170, and format 2, which
48 * is available only with the Netclock/2, specially modified 8170 and
49 * GPS.
50 *
51 * Format 0 (22 ASCII printing characters):
52 *
53 * <cr><lf>i  ddd hh:mm:ss TZ=zz<cr><lf>
54 *
55 *	on-time = first <cr>
56 *	hh:mm:ss = hours, minutes, seconds
57 *	i = synchronization flag (' ' = in synch, '?' = out of synch)
58 *
59 * The alarm condition is indicated by other than ' ' at i, which occurs
60 * during initial synchronization and when received signal is lost for
61 * about ten hours.
62 *
63 * Format 2 (24 ASCII printing characters):
64 *
65 * <cr><lf>iqyy ddd hh:mm:ss.fff ld
66 *
67 *	on-time = <cr>
68 *	i = synchronization flag (' ' = in synch, '?' = out of synch)
69 *	q = quality indicator (' ' = locked, 'A'...'D' = unlocked)
70 *	yy = year (as broadcast)
71 *	ddd = day of year
72 *	hh:mm:ss.fff = hours, minutes, seconds, milliseconds
73 *
74 * The alarm condition is indicated by other than ' ' at i, which occurs
75 * during initial synchronization and when received signal is lost for
76 * about ten hours. The unlock condition is indicated by other than ' '
77 * at q.
78 *
79 * The q is normally ' ' when the time error is less than 1 ms and a
80 * character in the set 'A'...'D' when the time error is less than 10,
81 * 100, 500 and greater than 500 ms respectively. The l is normally ' ',
82 * but is set to 'L' early in the month of an upcoming UTC leap second
83 * and reset to ' ' on the first day of the following month. The d is
84 * set to 'S' for standard time 'I' on the day preceding a switch to
85 * daylight time, 'D' for daylight time and 'O' on the day preceding a
86 * switch to standard time. The start bit of the first <cr> is
87 * synchronized to the indicated time as returned.
88 *
89 * This driver does not need to be told which format is in use - it
90 * figures out which one from the length of the message. The driver
91 * makes no attempt to correct for the intrinsic jitter of the radio
92 * itself, which is a known problem with the older radios.
93 *
94 * PPS Signal Processing
95 *
96 * When PPS signal processing is enabled, and when the system clock has
97 * been set by this or another driver and the PPS signal offset is
98 * within 0.4 s of the system clock offset, the PPS signal replaces the
99 * timecode for as long as the PPS signal is active. If for some reason
100 * the PPS signal fails for one or more poll intervals, the driver
101 * reverts to the timecode. If the timecode fails for one or more poll
102 * intervals, the PPS signal is disconnected.
103 *
104 * Fudge Factors
105 *
106 * This driver can retrieve a table of quality data maintained
107 * internally by the Netclock/2 clock. If flag4 of the fudge
108 * configuration command is set to 1, the driver will retrieve this
109 * table and write it to the clockstats file when the first timecode
110 * message of a new day is received.
111 *
112 * PPS calibration fudge time 1: format 0 .003134, format 2 .004034
113 */
114/*
115 * Interface definitions
116 */
117#define	DEVICE		"/dev/wwvb%d" /* device name and unit */
118#define	SPEED232	B9600	/* uart speed (9600 baud) */
119#define	PRECISION	(-13)	/* precision assumed (about 100 us) */
120#define	PPS_PRECISION	(-13)	/* precision assumed (about 100 us) */
121#define	REFID		"WWVB"	/* reference ID */
122#define	DESCRIPTION	"Spectracom WWVB/GPS Receiver" /* WRU */
123
124#define	LENWWVB0	22	/* format 0 timecode length */
125#define	LENWWVB2	24	/* format 2 timecode length */
126#define LENWWVB3	29	/* format 3 timecode length */
127#define MONLIN		15	/* number of monitoring lines */
128
129/*
130 * WWVB unit control structure
131 */
132struct wwvbunit {
133#ifdef HAVE_PPSAPI
134	struct refclock_atom atom; /* PPSAPI structure */
135	int	ppsapi_tried;	/* attempt PPSAPI once */
136	int	ppsapi_lit;	/* time_pps_create() worked */
137	int	tcount;		/* timecode sample counter */
138	int	pcount;		/* PPS sample counter */
139#endif /* HAVE_PPSAPI */
140	l_fp	laststamp;	/* last <CR> timestamp */
141	int	prev_eol_cr;	/* was last EOL <CR> (not <LF>)? */
142	u_char	lasthour;	/* last hour (for monitor) */
143	u_char	linect;		/* count ignored lines (for monitor */
144};
145
146/*
147 * Function prototypes
148 */
149static	int	wwvb_start	(int, struct peer *);
150static	void	wwvb_shutdown	(int, struct peer *);
151static	void	wwvb_receive	(struct recvbuf *);
152static	void	wwvb_poll	(int, struct peer *);
153static	void	wwvb_timer	(int, struct peer *);
154#ifdef HAVE_PPSAPI
155static	void	wwvb_control	(int, struct refclockstat *,
156				 struct refclockstat *, struct peer *);
157#define		WWVB_CONTROL	wwvb_control
158#else
159#define		WWVB_CONTROL	noentry
160#endif /* HAVE_PPSAPI */
161
162/*
163 * Transfer vector
164 */
165struct	refclock refclock_wwvb = {
166	wwvb_start,		/* start up driver */
167	wwvb_shutdown,		/* shut down driver */
168	wwvb_poll,		/* transmit poll message */
169	WWVB_CONTROL,		/* fudge set/change notification */
170	noentry,		/* initialize driver (not used) */
171	noentry,		/* not used (old wwvb_buginfo) */
172	wwvb_timer		/* called once per second */
173};
174
175
176/*
177 * wwvb_start - open the devices and initialize data for processing
178 */
179static int
180wwvb_start(
181	int unit,
182	struct peer *peer
183	)
184{
185	register struct wwvbunit *up;
186	struct refclockproc *pp;
187	int fd;
188	char device[20];
189
190	/*
191	 * Open serial port. Use CLK line discipline, if available.
192	 */
193	snprintf(device, sizeof(device), DEVICE, unit);
194	fd = refclock_open(device, SPEED232, LDISC_CLK);
195	if (fd <= 0)
196		return (0);
197
198	/*
199	 * Allocate and initialize unit structure
200	 */
201	up = emalloc_zero(sizeof(*up));
202	pp = peer->procptr;
203	pp->io.clock_recv = wwvb_receive;
204	pp->io.srcclock = (void *)peer;
205	pp->io.datalen = 0;
206	pp->io.fd = fd;
207	if (!io_addclock(&pp->io)) {
208		close(fd);
209		pp->io.fd = -1;
210		free(up);
211		return (0);
212	}
213	pp->unitptr = up;
214
215	/*
216	 * Initialize miscellaneous variables
217	 */
218	peer->precision = PRECISION;
219	pp->clockdesc = DESCRIPTION;
220	memcpy(&pp->refid, REFID, 4);
221	return (1);
222}
223
224
225/*
226 * wwvb_shutdown - shut down the clock
227 */
228static void
229wwvb_shutdown(
230	int unit,
231	struct peer *peer
232	)
233{
234	register struct wwvbunit *up;
235	struct refclockproc *pp;
236
237	pp = peer->procptr;
238	up = pp->unitptr;
239	if (-1 != pp->io.fd)
240		io_closeclock(&pp->io);
241	if (NULL != up)
242		free(up);
243}
244
245
246/*
247 * wwvb_receive - receive data from the serial interface
248 */
249static void
250wwvb_receive(
251	struct recvbuf *rbufp
252	)
253{
254	struct wwvbunit *up;
255	struct refclockproc *pp;
256	struct peer *peer;
257
258	l_fp	trtmp;		/* arrival timestamp */
259	int	tz;		/* time zone */
260	int	day, month;	/* ddd conversion */
261	int	temp;		/* int temp */
262	char	syncchar;	/* synchronization indicator */
263	char	qualchar;	/* quality indicator */
264	char	leapchar;	/* leap indicator */
265	char	dstchar;	/* daylight/standard indicator */
266	char	tmpchar;	/* trashbin */
267
268	/*
269	 * Initialize pointers and read the timecode and timestamp
270	 */
271	peer = rbufp->recv_peer;
272	pp = peer->procptr;
273	up = pp->unitptr;
274	temp = refclock_gtlin(rbufp, pp->a_lastcode, BMAX, &trtmp);
275
276	/*
277	 * Note we get a buffer and timestamp for both a <cr> and <lf>,
278	 * but only the <cr> timestamp is retained. Note: in format 0 on
279	 * a Netclock/2 or upgraded 8170 the start bit is delayed 100
280	 * +-50 us relative to the pps; however, on an unmodified 8170
281	 * the start bit can be delayed up to 10 ms. In format 2 the
282	 * reading precision is only to the millisecond. Thus, unless
283	 * you have a PPS gadget and don't have to have the year, format
284	 * 0 provides the lowest jitter.
285	 * Save the timestamp of each <CR> in up->laststamp.  Lines with
286	 * no characters occur for every <LF>, and for some <CR>s when
287	 * format 0 is used. Format 0 starts and ends each cycle with a
288	 * <CR><LF> pair, format 2 starts each cycle with its only pair.
289	 * The preceding <CR> is the on-time character for both formats.
290	 * The timestamp provided with non-empty lines corresponds to
291	 * the <CR> following the timecode, which is ultimately not used
292	 * with format 0 and is used for the following timecode for
293	 * format 2.
294	 */
295	if (temp == 0) {
296		if (up->prev_eol_cr) {
297			DPRINTF(2, ("wwvb: <LF> @ %s\n",
298				    prettydate(&trtmp)));
299		} else {
300			up->laststamp = trtmp;
301			DPRINTF(2, ("wwvb: <CR> @ %s\n",
302				    prettydate(&trtmp)));
303		}
304		up->prev_eol_cr = !up->prev_eol_cr;
305		return;
306	}
307	pp->lencode = temp;
308	pp->lastrec = up->laststamp;
309	up->laststamp = trtmp;
310	up->prev_eol_cr = TRUE;
311	DPRINTF(2, ("wwvb: code @ %s\n"
312		    "       using %s minus one char\n",
313		    prettydate(&trtmp), prettydate(&pp->lastrec)));
314	if (L_ISZERO(&pp->lastrec))
315		return;
316
317	/*
318	 * We get down to business, check the timecode format and decode
319	 * its contents. This code uses the timecode length to determine
320	 * format 0, 2 or 3. If the timecode has invalid length or is
321	 * not in proper format, we declare bad format and exit.
322	 */
323	syncchar = qualchar = leapchar = dstchar = ' ';
324	tz = 0;
325	switch (pp->lencode) {
326
327	case LENWWVB0:
328
329		/*
330		 * Timecode format 0: "I  ddd hh:mm:ss DTZ=nn"
331		 */
332		if (sscanf(pp->a_lastcode,
333		    "%c %3d %2d:%2d:%2d%c%cTZ=%2d",
334		    &syncchar, &pp->day, &pp->hour, &pp->minute,
335		    &pp->second, &tmpchar, &dstchar, &tz) == 8) {
336			pp->nsec = 0;
337			break;
338		}
339		goto bad_format;
340
341	case LENWWVB2:
342
343		/*
344		 * Timecode format 2: "IQyy ddd hh:mm:ss.mmm LD" */
345		if (sscanf(pp->a_lastcode,
346		    "%c%c %2d %3d %2d:%2d:%2d.%3ld %c",
347		    &syncchar, &qualchar, &pp->year, &pp->day,
348		    &pp->hour, &pp->minute, &pp->second, &pp->nsec,
349		    &leapchar) == 9) {
350			pp->nsec *= 1000000;
351			break;
352		}
353		goto bad_format;
354
355	case LENWWVB3:
356
357		/*
358		 * Timecode format 3: "0003I yyyymmdd hhmmss+0000SL#"
359		 * WARNING: Undocumented, and the on-time character # is
360		 * not yet handled correctly by this driver.  It may be
361		 * as simple as compensating for an additional 1/960 s.
362		 */
363		if (sscanf(pp->a_lastcode,
364		    "0003%c %4d%2d%2d %2d%2d%2d+0000%c%c",
365		    &syncchar, &pp->year, &month, &day, &pp->hour,
366		    &pp->minute, &pp->second, &dstchar, &leapchar) == 8)
367		    {
368			pp->day = ymd2yd(pp->year, month, day);
369			pp->nsec = 0;
370			break;
371		}
372		goto bad_format;
373
374	default:
375	bad_format:
376
377		/*
378		 * Unknown format: If dumping internal table, record
379		 * stats; otherwise, declare bad format.
380		 */
381		if (up->linect > 0) {
382			up->linect--;
383			record_clock_stats(&peer->srcadr,
384			    pp->a_lastcode);
385		} else {
386			refclock_report(peer, CEVNT_BADREPLY);
387		}
388		return;
389	}
390
391	/*
392	 * Decode synchronization, quality and leap characters. If
393	 * unsynchronized, set the leap bits accordingly and exit.
394	 * Otherwise, set the leap bits according to the leap character.
395	 * Once synchronized, the dispersion depends only on the
396	 * quality character.
397	 */
398	switch (qualchar) {
399
400	    case ' ':
401		pp->disp = .001;
402		pp->lastref = pp->lastrec;
403		break;
404
405	    case 'A':
406		pp->disp = .01;
407		break;
408
409	    case 'B':
410		pp->disp = .1;
411		break;
412
413	    case 'C':
414		pp->disp = .5;
415		break;
416
417	    case 'D':
418		pp->disp = MAXDISPERSE;
419		break;
420
421	    default:
422		pp->disp = MAXDISPERSE;
423		refclock_report(peer, CEVNT_BADREPLY);
424		break;
425	}
426	if (syncchar != ' ')
427		pp->leap = LEAP_NOTINSYNC;
428	else if (leapchar == 'L')
429		pp->leap = LEAP_ADDSECOND;
430	else
431		pp->leap = LEAP_NOWARNING;
432
433	/*
434	 * Process the new sample in the median filter and determine the
435	 * timecode timestamp, but only if the PPS is not in control.
436	 */
437#ifdef HAVE_PPSAPI
438	up->tcount++;
439	if (peer->flags & FLAG_PPS)
440		return;
441
442#endif /* HAVE_PPSAPI */
443	if (!refclock_process_f(pp, pp->fudgetime2))
444		refclock_report(peer, CEVNT_BADTIME);
445}
446
447
448/*
449 * wwvb_timer - called once per second by the transmit procedure
450 */
451static void
452wwvb_timer(
453	int unit,
454	struct peer *peer
455	)
456{
457	register struct wwvbunit *up;
458	struct refclockproc *pp;
459	char	pollchar;	/* character sent to clock */
460	l_fp	now;
461
462	/*
463	 * Time to poll the clock. The Spectracom clock responds to a
464	 * 'T' by returning a timecode in the format(s) specified above.
465	 * Note there is no checking on state, since this may not be the
466	 * only customer reading the clock. Only one customer need poll
467	 * the clock; all others just listen in.
468	 */
469	pp = peer->procptr;
470	up = pp->unitptr;
471	if (up->linect > 0)
472		pollchar = 'R';
473	else
474		pollchar = 'T';
475	if (write(pp->io.fd, &pollchar, 1) != 1)
476		refclock_report(peer, CEVNT_FAULT);
477#ifdef DEBUG
478	get_systime(&now);
479	if (debug)
480		printf("%c poll at %s\n", pollchar, prettydate(&now));
481#endif
482#ifdef HAVE_PPSAPI
483	if (up->ppsapi_lit &&
484	    refclock_pps(peer, &up->atom, pp->sloppyclockflag) > 0) {
485		up->pcount++,
486		peer->flags |= FLAG_PPS;
487		peer->precision = PPS_PRECISION;
488	}
489#endif /* HAVE_PPSAPI */
490}
491
492
493/*
494 * wwvb_poll - called by the transmit procedure
495 */
496static void
497wwvb_poll(
498	int unit,
499	struct peer *peer
500	)
501{
502	register struct wwvbunit *up;
503	struct refclockproc *pp;
504
505	/*
506	 * Sweep up the samples received since the last poll. If none
507	 * are received, declare a timeout and keep going.
508	 */
509	pp = peer->procptr;
510	up = pp->unitptr;
511	pp->polls++;
512
513	/*
514	 * If the monitor flag is set (flag4), we dump the internal
515	 * quality table at the first timecode beginning the day.
516	 */
517	if (pp->sloppyclockflag & CLK_FLAG4 && pp->hour <
518	    (int)up->lasthour)
519		up->linect = MONLIN;
520	up->lasthour = (u_char)pp->hour;
521
522	/*
523	 * Process median filter samples. If none received, declare a
524	 * timeout and keep going.
525	 */
526#ifdef HAVE_PPSAPI
527	if (up->pcount == 0) {
528		peer->flags &= ~FLAG_PPS;
529		peer->precision = PRECISION;
530	}
531	if (up->tcount == 0) {
532		pp->coderecv = pp->codeproc;
533		refclock_report(peer, CEVNT_TIMEOUT);
534		return;
535	}
536	up->pcount = up->tcount = 0;
537#else /* HAVE_PPSAPI */
538	if (pp->coderecv == pp->codeproc) {
539		refclock_report(peer, CEVNT_TIMEOUT);
540		return;
541	}
542#endif /* HAVE_PPSAPI */
543	refclock_receive(peer);
544	record_clock_stats(&peer->srcadr, pp->a_lastcode);
545#ifdef DEBUG
546	if (debug)
547		printf("wwvb: timecode %d %s\n", pp->lencode,
548		    pp->a_lastcode);
549#endif
550}
551
552
553/*
554 * wwvb_control - fudge parameters have been set or changed
555 */
556#ifdef HAVE_PPSAPI
557static void
558wwvb_control(
559	int unit,
560	struct refclockstat *in_st,
561	struct refclockstat *out_st,
562	struct peer *peer
563	)
564{
565	register struct wwvbunit *up;
566	struct refclockproc *pp;
567
568	pp = peer->procptr;
569	up = pp->unitptr;
570
571	if (!(pp->sloppyclockflag & CLK_FLAG1)) {
572		if (!up->ppsapi_tried)
573			return;
574		up->ppsapi_tried = 0;
575		if (!up->ppsapi_lit)
576			return;
577		peer->flags &= ~FLAG_PPS;
578		peer->precision = PRECISION;
579		time_pps_destroy(up->atom.handle);
580		up->atom.handle = 0;
581		up->ppsapi_lit = 0;
582		return;
583	}
584
585	if (up->ppsapi_tried)
586		return;
587	/*
588	 * Light up the PPSAPI interface.
589	 */
590	up->ppsapi_tried = 1;
591	if (refclock_ppsapi(pp->io.fd, &up->atom)) {
592		up->ppsapi_lit = 1;
593		return;
594	}
595
596	NLOG(NLOG_CLOCKINFO)
597		msyslog(LOG_WARNING, "%s flag1 1 but PPSAPI fails",
598			refnumtoa(&peer->srcadr));
599}
600#endif	/* HAVE_PPSAPI */
601
602#else
603int refclock_wwvb_bs;
604#endif /* REFCLOCK */
605