xref: /netbsd-src/external/bsd/ntp/dist/ntpd/refclock_arbiter.c (revision 7788a0781fe6ff2cce37368b4578a7ade0850cb1)
1 /*	$NetBSD: refclock_arbiter.c,v 1.1.1.2 2012/01/31 21:26:42 kardel Exp $	*/
2 
3 /*
4  * refclock_arbiter - clock driver for Arbiter 1088A/B Satellite
5  *	Controlled Clock
6  */
7 
8 #ifdef HAVE_CONFIG_H
9 #include <config.h>
10 #endif
11 
12 #if defined(REFCLOCK) && defined(CLOCK_ARBITER)
13 
14 #include "ntpd.h"
15 #include "ntp_io.h"
16 #include "ntp_refclock.h"
17 #include "ntp_stdlib.h"
18 
19 #include <stdio.h>
20 #include <ctype.h>
21 
22 #ifdef SYS_WINNT
23 extern int async_write(int, const void *, unsigned int);
24 #undef write
25 #define write(fd, data, octets)	async_write(fd, data, octets)
26 #endif
27 
28 /*
29  * This driver supports the Arbiter 1088A/B Satellite Controlled Clock.
30  * The claimed accuracy of this clock is 100 ns relative to the PPS
31  * output when receiving four or more satellites.
32  *
33  * The receiver should be configured before starting the NTP daemon, in
34  * order to establish reliable position and operating conditions. It
35  * does not initiate surveying or hold mode. For use with NTP, the
36  * daylight savings time feature should be disables (D0 command) and the
37  * broadcast mode set to operate in UTC (BU command).
38  *
39  * The timecode format supported by this driver is selected by the poll
40  * sequence "B5", which initiates a line in the following format to be
41  * repeated once per second until turned off by the "B0" poll sequence.
42  *
43  * Format B5 (24 ASCII printing characters):
44  *
45  * <cr><lf>i yy ddd hh:mm:ss.000bbb
46  *
47  *	on-time = <cr>
48  *	i = synchronization flag (' ' = locked, '?' = unlocked)
49  *	yy = year of century
50  *	ddd = day of year
51  *	hh:mm:ss = hours, minutes, seconds
52  *	.000 = fraction of second (not used)
53  *	bbb = tailing spaces for fill
54  *
55  * The alarm condition is indicated by a '?' at i, which indicates the
56  * receiver is not synchronized. In normal operation, a line consisting
57  * of the timecode followed by the time quality character (TQ) followed
58  * by the receiver status string (SR) is written to the clockstats file.
59  * The time quality character is encoded in IEEE P1344 standard:
60  *
61  * Format TQ (IEEE P1344 estimated worst-case time quality)
62  *
63  *	0	clock locked, maximum accuracy
64  *	F	clock failure, time not reliable
65  *	4	clock unlocked, accuracy < 1 us
66  *	5	clock unlocked, accuracy < 10 us
67  *	6	clock unlocked, accuracy < 100 us
68  *	7	clock unlocked, accuracy < 1 ms
69  *	8	clock unlocked, accuracy < 10 ms
70  *	9	clock unlocked, accuracy < 100 ms
71  *	A	clock unlocked, accuracy < 1 s
72  *	B	clock unlocked, accuracy < 10 s
73  *
74  * The status string is encoded as follows:
75  *
76  * Format SR (25 ASCII printing characters)
77  *
78  *	V=vv S=ss T=t P=pdop E=ee
79  *
80  *	vv = satellites visible
81  *	ss = relative signal strength
82  *	t = satellites tracked
83  *	pdop = position dilution of precision (meters)
84  *	ee = hardware errors
85  *
86  * If flag4 is set, an additional line consisting of the receiver
87  * latitude (LA), longitude (LO), elevation (LH) (meters), and data
88  * buffer (DB) is written to this file. If channel B is enabled for
89  * deviation mode and connected to a 1-PPS signal, the last two numbers
90  * on the line are the deviation and standard deviation averaged over
91  * the last 15 seconds.
92  *
93  * PPS calibration fudge time1 .001240
94  */
95 
96 /*
97  * Interface definitions
98  */
99 #define	DEVICE		"/dev/gps%d" /* device name and unit */
100 #define	SPEED232	B9600	/* uart speed (9600 baud) */
101 #define	PRECISION	(-20)	/* precision assumed (about 1 us) */
102 #define	REFID		"GPS "	/* reference ID */
103 #define	DESCRIPTION	"Arbiter 1088A/B GPS Receiver" /* WRU */
104 #define	LENARB		24	/* format B5 timecode length */
105 #define MAXSTA		40	/* max length of status string */
106 #define MAXPOS		80	/* max length of position string */
107 
108 #ifdef PRE_NTP420
109 #define MODE ttlmax
110 #else
111 #define MODE ttl
112 #endif
113 
114 #define COMMAND_HALT_BCAST ( (peer->MODE % 2) ? "O0" : "B0" )
115 #define COMMAND_START_BCAST ( (peer->MODE % 2) ? "O5" : "B5" )
116 
117 /*
118  * ARB unit control structure
119  */
120 struct arbunit {
121 	l_fp	laststamp;	/* last receive timestamp */
122 	int	tcswitch;	/* timecode switch/counter */
123 	char	qualchar;	/* IEEE P1344 quality (TQ command) */
124 	char	status[MAXSTA];	/* receiver status (SR command) */
125 	char	latlon[MAXPOS];	/* receiver position (lat/lon/alt) */
126 };
127 
128 /*
129  * Function prototypes
130  */
131 static	int	arb_start	(int, struct peer *);
132 static	void	arb_shutdown	(int, struct peer *);
133 static	void	arb_receive	(struct recvbuf *);
134 static	void	arb_poll	(int, struct peer *);
135 
136 /*
137  * Transfer vector
138  */
139 struct	refclock refclock_arbiter = {
140 	arb_start,		/* start up driver */
141 	arb_shutdown,		/* shut down driver */
142 	arb_poll,		/* transmit poll message */
143 	noentry,		/* not used (old arb_control) */
144 	noentry,		/* initialize driver (not used) */
145 	noentry,		/* not used (old arb_buginfo) */
146 	NOFLAGS			/* not used */
147 };
148 
149 
150 /*
151  * arb_start - open the devices and initialize data for processing
152  */
153 static int
154 arb_start(
155 	int unit,
156 	struct peer *peer
157 	)
158 {
159 	register struct arbunit *up;
160 	struct refclockproc *pp;
161 	int fd;
162 	char device[20];
163 
164 	/*
165 	 * Open serial port. Use CLK line discipline, if available.
166 	 */
167 	snprintf(device, sizeof(device), DEVICE, unit);
168 	if (!(fd = refclock_open(device, SPEED232, LDISC_CLK)))
169 		return (0);
170 
171 	/*
172 	 * Allocate and initialize unit structure
173 	 */
174 	up = emalloc(sizeof(*up));
175 	memset(up, 0, sizeof(*up));
176 	pp = peer->procptr;
177 	pp->io.clock_recv = arb_receive;
178 	pp->io.srcclock = (caddr_t)peer;
179 	pp->io.datalen = 0;
180 	pp->io.fd = fd;
181 	if (!io_addclock(&pp->io)) {
182 		close(fd);
183 		pp->io.fd = -1;
184 		free(up);
185 		return (0);
186 	}
187 	pp->unitptr = (caddr_t)up;
188 
189 	/*
190 	 * Initialize miscellaneous variables
191 	 */
192 	peer->precision = PRECISION;
193 	pp->clockdesc = DESCRIPTION;
194 	memcpy((char *)&pp->refid, REFID, 4);
195 	if (peer->MODE > 1) {
196 		msyslog(LOG_NOTICE, "ARBITER: Invalid mode %d", peer->MODE);
197 		close(fd);
198 		pp->io.fd = -1;
199 		free(up);
200 		return (0);
201 	}
202 #ifdef DEBUG
203 	if(debug) { printf("arbiter: mode = %d.\n", peer->MODE); }
204 #endif
205 	write(pp->io.fd, COMMAND_HALT_BCAST, 2);
206 	return (1);
207 }
208 
209 
210 /*
211  * arb_shutdown - shut down the clock
212  */
213 static void
214 arb_shutdown(
215 	int unit,
216 	struct peer *peer
217 	)
218 {
219 	register struct arbunit *up;
220 	struct refclockproc *pp;
221 
222 	pp = peer->procptr;
223 	up = (struct arbunit *)pp->unitptr;
224 	if (-1 != pp->io.fd)
225 		io_closeclock(&pp->io);
226 	if (NULL != up)
227 		free(up);
228 }
229 
230 
231 /*
232  * arb_receive - receive data from the serial interface
233  */
234 static void
235 arb_receive(
236 	struct recvbuf *rbufp
237 	)
238 {
239 	register struct arbunit *up;
240 	struct refclockproc *pp;
241 	struct peer *peer;
242 	l_fp trtmp;
243 	int temp;
244 	u_char	syncchar;		/* synch indicator */
245 	char	tbuf[BMAX];		/* temp buffer */
246 
247 	/*
248 	 * Initialize pointers and read the timecode and timestamp
249 	 */
250 	peer = (struct peer *)rbufp->recv_srcclock;
251 	pp = peer->procptr;
252 	up = (struct arbunit *)pp->unitptr;
253 	temp = refclock_gtlin(rbufp, tbuf, BMAX, &trtmp);
254 
255 	/*
256 	 * Note we get a buffer and timestamp for both a <cr> and <lf>,
257 	 * but only the <cr> timestamp is retained. The program first
258 	 * sends a TQ and expects the echo followed by the time quality
259 	 * character. It then sends a B5 starting the timecode broadcast
260 	 * and expects the echo followed some time later by the on-time
261 	 * character <cr> and then the <lf> beginning the timecode
262 	 * itself. Finally, at the <cr> beginning the next timecode at
263 	 * the next second, the program sends a B0 shutting down the
264 	 * timecode broadcast.
265 	 *
266 	 * If flag4 is set, the program snatches the latitude, longitude
267 	 * and elevation and writes it to the clockstats file.
268 	 */
269 	if (temp == 0)
270 		return;
271 
272 	pp->lastrec = up->laststamp;
273 	up->laststamp = trtmp;
274 	if (temp < 3)
275 		return;
276 
277 	if (up->tcswitch == 0) {
278 
279 		/*
280 		 * Collect statistics. If nothing is recogized, just
281 		 * ignore; sometimes the clock doesn't stop spewing
282 		 * timecodes for awhile after the B0 command.
283 		 *
284 		 * If flag4 is not set, send TQ, SR, B5. If flag4 is
285 		 * sset, send TQ, SR, LA, LO, LH, DB, B5. When the
286 		 * median filter is full, send B0.
287 		 */
288 		if (!strncmp(tbuf, "TQ", 2)) {
289 			up->qualchar = tbuf[2];
290 			write(pp->io.fd, "SR", 2);
291 			return;
292 
293 		} else if (!strncmp(tbuf, "SR", 2)) {
294 			strcpy(up->status, tbuf + 2);
295 			if (pp->sloppyclockflag & CLK_FLAG4)
296 				write(pp->io.fd, "LA", 2);
297 			else
298 				write(pp->io.fd, COMMAND_START_BCAST, 2);
299 			return;
300 
301 		} else if (!strncmp(tbuf, "LA", 2)) {
302 			strcpy(up->latlon, tbuf + 2);
303 			write(pp->io.fd, "LO", 2);
304 			return;
305 
306 		} else if (!strncmp(tbuf, "LO", 2)) {
307 			strcat(up->latlon, " ");
308 			strcat(up->latlon, tbuf + 2);
309 			write(pp->io.fd, "LH", 2);
310 			return;
311 
312 		} else if (!strncmp(tbuf, "LH", 2)) {
313 			strcat(up->latlon, " ");
314 			strcat(up->latlon, tbuf + 2);
315 			write(pp->io.fd, "DB", 2);
316 			return;
317 
318 		} else if (!strncmp(tbuf, "DB", 2)) {
319 			strcat(up->latlon, " ");
320 			strcat(up->latlon, tbuf + 2);
321 			record_clock_stats(&peer->srcadr, up->latlon);
322 #ifdef DEBUG
323 			if (debug)
324 				printf("arbiter: %s\n", up->latlon);
325 #endif
326 			write(pp->io.fd, COMMAND_START_BCAST, 2);
327 		}
328 	}
329 
330 	/*
331 	 * We get down to business, check the timecode format and decode
332 	 * its contents. If the timecode has valid length, but not in
333 	 * proper format, we declare bad format and exit. If the
334 	 * timecode has invalid length, which sometimes occurs when the
335 	 * B0 amputates the broadcast, we just quietly steal away. Note
336 	 * that the time quality character and receiver status string is
337 	 * tacked on the end for clockstats display.
338 	 */
339 	up->tcswitch++;
340 	if (up->tcswitch <= 1 || temp < LENARB)
341 		return;
342 
343 	/*
344 	 * Timecode format B5: "i yy ddd hh:mm:ss.000   "
345 	 */
346 	strncpy(pp->a_lastcode, tbuf, BMAX);
347 	pp->a_lastcode[LENARB - 2] = up->qualchar;
348 	strcat(pp->a_lastcode, up->status);
349 	pp->lencode = strlen(pp->a_lastcode);
350 	syncchar = ' ';
351 	if (sscanf(pp->a_lastcode, "%c%2d %3d %2d:%2d:%2d",
352 	    &syncchar, &pp->year, &pp->day, &pp->hour,
353 	    &pp->minute, &pp->second) != 6) {
354 		refclock_report(peer, CEVNT_BADREPLY);
355 		write(pp->io.fd, COMMAND_HALT_BCAST, 2);
356 		return;
357 	}
358 
359 	/*
360 	 * We decode the clock dispersion from the time quality
361 	 * character.
362 	 */
363 	switch (up->qualchar) {
364 
365 	    case '0':		/* locked, max accuracy */
366 		pp->disp = 1e-7;
367 		pp->lastref = pp->lastrec;
368 		break;
369 
370 	    case '4':		/* unlock accuracy < 1 us */
371 		pp->disp = 1e-6;
372 		break;
373 
374 	    case '5':		/* unlock accuracy < 10 us */
375 		pp->disp = 1e-5;
376 		break;
377 
378 	    case '6':		/* unlock accuracy < 100 us */
379 		pp->disp = 1e-4;
380 		break;
381 
382 	    case '7':		/* unlock accuracy < 1 ms */
383 		pp->disp = .001;
384 		break;
385 
386 	    case '8':		/* unlock accuracy < 10 ms */
387 		pp->disp = .01;
388 		break;
389 
390 	    case '9':		/* unlock accuracy < 100 ms */
391 		pp->disp = .1;
392 		break;
393 
394 	    case 'A':		/* unlock accuracy < 1 s */
395 		pp->disp = 1;
396 		break;
397 
398 	    case 'B':		/* unlock accuracy < 10 s */
399 		pp->disp = 10;
400 		break;
401 
402 	    case 'F':		/* clock failure */
403 		pp->disp = MAXDISPERSE;
404 		refclock_report(peer, CEVNT_FAULT);
405 		write(pp->io.fd, COMMAND_HALT_BCAST, 2);
406 		return;
407 
408 	    default:
409 		pp->disp = MAXDISPERSE;
410 		refclock_report(peer, CEVNT_BADREPLY);
411 		write(pp->io.fd, COMMAND_HALT_BCAST, 2);
412 		return;
413 	}
414 	if (syncchar != ' ')
415 		pp->leap = LEAP_NOTINSYNC;
416 	else
417 		pp->leap = LEAP_NOWARNING;
418 
419 	/*
420 	 * Process the new sample in the median filter and determine the
421 	 * timecode timestamp.
422 	 */
423 	if (!refclock_process(pp))
424 		refclock_report(peer, CEVNT_BADTIME);
425 	else if (peer->disp > MAXDISTANCE)
426 		refclock_receive(peer);
427 
428 	/* if (up->tcswitch >= MAXSTAGE) { */
429 	write(pp->io.fd, COMMAND_HALT_BCAST, 2);
430 	/* } */
431 }
432 
433 
434 /*
435  * arb_poll - called by the transmit procedure
436  */
437 static void
438 arb_poll(
439 	int unit,
440 	struct peer *peer
441 	)
442 {
443 	register struct arbunit *up;
444 	struct refclockproc *pp;
445 
446 	/*
447 	 * Time to poll the clock. The Arbiter clock responds to a "B5"
448 	 * by returning a timecode in the format specified above.
449 	 * Transmission occurs once per second, unless turned off by a
450 	 * "B0". Note there is no checking on state, since this may not
451 	 * be the only customer reading the clock. Only one customer
452 	 * need poll the clock; all others just listen in.
453 	 */
454 	pp = peer->procptr;
455 	up = (struct arbunit *)pp->unitptr;
456 	pp->polls++;
457 	up->tcswitch = 0;
458 	if (write(pp->io.fd, "TQ", 2) != 2)
459 		refclock_report(peer, CEVNT_FAULT);
460 
461 	/*
462 	 * Process median filter samples. If none received, declare a
463 	 * timeout and keep going.
464 	 */
465 	if (pp->coderecv == pp->codeproc) {
466 		refclock_report(peer, CEVNT_TIMEOUT);
467 		return;
468 	}
469 	refclock_receive(peer);
470 	record_clock_stats(&peer->srcadr, pp->a_lastcode);
471 #ifdef DEBUG
472 	if (debug)
473 		printf("arbiter: timecode %d %s\n",
474 		   pp->lencode, pp->a_lastcode);
475 #endif
476 }
477 
478 #else
479 int refclock_arbiter_bs;
480 #endif /* REFCLOCK */
481