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