2 * refclock_nmea.c - clock driver for an NMEA GPS CLOCK
3 * Michael Petry Jun 20, 1994
4 * based on refclock_heathn.c
6 * Updated to add support for Accord GPS Clock
7 * Venu Gopal Dec 05, 2007
8 * neo.venu@gmail.com, venugopal_d@pgad.gov.in
10 * Updated to process 'time1' fudge factor
11 * Venu Gopal May 05, 2008
13 * Converted to common PPSAPI code, separate PPS fudge time1
14 * from serial timecode fudge time2.
15 * Dave Hart July 1, 2009
16 * hart@ntp.org, davehart@davehart.com
23 #include "ntp_types.h"
25 #if defined(REFCLOCK) && defined(CLOCK_NMEA)
27 #define NMEA_WRITE_SUPPORT 0 /* no write support at the moment */
32 #ifdef HAVE_SYS_SOCKET_H
33 #include <sys/socket.h>
38 #include "ntp_unixtime.h"
39 #include "ntp_refclock.h"
40 #include "ntp_stdlib.h"
41 #include "ntp_calendar.h"
42 #include "timespecops.h"
45 # include "ppsapi_timepps.h"
46 # include "refclock_atom.h"
47 #endif /* HAVE_PPSAPI */
51 * This driver supports NMEA-compatible GPS receivers
53 * Prototype was refclock_trak.c, Thanks a lot.
55 * The receiver used spits out the NMEA sentences for boat navigation.
56 * And you thought it was an information superhighway. Try a raging river
57 * filled with rapids and whirlpools that rip away your data and warp time.
59 * If HAVE_PPSAPI is defined code to use the PPSAPI will be compiled in.
60 * On startup if initialization of the PPSAPI fails, it will fall back
61 * to the "normal" timestamps.
63 * The PPSAPI part of the driver understands fudge flag2 and flag3. If
64 * flag2 is set, it will use the clear edge of the pulse. If flag3 is
65 * set, kernel hardpps is enabled.
67 * GPS sentences other than RMC (the default) may be enabled by setting
68 * the relevent bits of 'mode' in the server configuration line
69 * server 127.127.20.x mode X
71 * bit 0 - enables RMC (1)
72 * bit 1 - enables GGA (2)
73 * bit 2 - enables GLL (4)
74 * bit 3 - enables ZDA (8) - Standard Time & Date
75 * bit 3 - enables ZDG (8) - Accord GPS Clock's custom sentence with GPS time
76 * very close to standard ZDA
78 * Multiple sentences may be selected except when ZDG/ZDA is selected.
80 * bit 4/5/6 - selects the baudrate for serial port :
81 * 0 for 4800 (default)
88 #define NMEA_MESSAGE_MASK 0x0000FF0FU
89 #define NMEA_BAUDRATE_MASK 0x00000070U
90 #define NMEA_BAUDRATE_SHIFT 4
92 #define NMEA_DELAYMEAS_MASK 0x80
93 #define NMEA_EXTLOG_MASK 0x00010000U
94 #define NMEA_DATETRUST_MASK 0x02000000U
96 #define NMEA_PROTO_IDLEN 5 /* tag name must be at least 5 chars */
97 #define NMEA_PROTO_MINLEN 6 /* min chars in sentence, excluding CS */
98 #define NMEA_PROTO_MAXLEN 80 /* max chars in sentence, excluding CS */
99 #define NMEA_PROTO_FIELDS 32 /* not official; limit on fields per record */
102 * We check the timecode format and decode its contents. We only care
103 * about a few of them, the most important being the $GPRMC format:
105 * $GPRMC,hhmmss,a,fddmm.xx,n,dddmmm.xx,w,zz.z,yyy.,ddmmyy,dd,v*CC
107 * mode (0,1,2,3) selects sentence ANY/ALL, RMC, GGA, GLL, ZDA
108 * $GPGLL,3513.8385,S,14900.7851,E,232420.594,A*21
109 * $GPGGA,232420.59,3513.8385,S,14900.7851,E,1,05,3.4,00519,M,,,,*3F
110 * $GPRMC,232418.19,A,3513.8386,S,14900.7853,E,00.0,000.0,121199,12.,E*77
112 * Defining GPZDA to support Standard Time & Date
113 * sentence. The sentence has the following format
115 * $--ZDA,HHMMSS.SS,DD,MM,YYYY,TH,TM,*CS<CR><LF>
117 * Apart from the familiar fields,
118 * 'TH' Time zone Hours
119 * 'TM' Time zone Minutes
121 * Defining GPZDG to support Accord GPS Clock's custom NMEA
122 * sentence. The sentence has the following format
124 * $GPZDG,HHMMSS.S,DD,MM,YYYY,AA.BB,V*CS<CR><LF>
126 * It contains the GPS timestamp valid for next PPS pulse.
127 * Apart from the familiar fields,
128 * 'AA.BB' denotes the signal strength( should be < 05.00 )
129 * 'V' denotes the GPS sync status :
130 * '0' indicates INVALID time,
131 * '1' indicates accuracy of +/-20 ms
132 * '2' indicates accuracy of +/-100 ns
134 * Defining PGRMF for Garmin GPS Fix Data
135 * $PGRMF,WN,WS,DATE,TIME,LS,LAT,LAT_DIR,LON,LON_DIR,MODE,FIX,SPD,DIR,PDOP,TDOP
136 * WN -- GPS week number (weeks since 1980-01-06, mod 1024)
137 * WS -- GPS seconds in week
138 * LS -- GPS leap seconds, accumulated ( UTC + LS == GPS )
139 * FIX -- Fix type: 0=nofix, 1=2D, 2=3D
140 * DATE/TIME are standard date/time strings in UTC time scale
142 * The GPS time can be used to get the full century for the truncated
149 #define DEVICE "/dev/gps%d" /* GPS serial device */
150 #define PPSDEV "/dev/gpspps%d" /* PPSAPI device override */
151 #define SPEED232 B4800 /* uart speed (4800 bps) */
152 #define PRECISION (-9) /* precision assumed (about 2 ms) */
153 #define PPS_PRECISION (-20) /* precision assumed (about 1 us) */
154 #define REFID "GPS\0" /* reference id */
155 #define DESCRIPTION "NMEA GPS Clock" /* who we are */
159 #define M_NOCTTY O_NOCTTY
164 #define M_NONBLOCK O_NONBLOCK
166 #define PPSOPENMODE (O_RDWR | M_NOCTTY | M_NONBLOCK)
168 /* NMEA sentence array indexes for those we use */
169 #define NMEA_GPRMC 0 /* recommended min. nav. */
170 #define NMEA_GPGGA 1 /* fix and quality */
171 #define NMEA_GPGLL 2 /* geo. lat/long */
172 #define NMEA_GPZDA 3 /* date/time */
174 * $GPZDG is a proprietary sentence that violates the spec, by not
175 * using $P and an assigned company identifier to prefix the sentence
176 * identifier. When used with this driver, the system needs to be
177 * isolated from other NTP networks, as it operates in GPS time, not
178 * UTC as is much more common. GPS time is >15 seconds different from
179 * UTC due to not respecting leap seconds since 1970 or so. Other
180 * than the different timebase, $GPZDG is similar to $GPZDA.
184 #define NMEA_ARRAY_SIZE (NMEA_PGRMF + 1)
187 * Sentence selection mode bits
189 #define USE_GPRMC 0x00000001u
190 #define USE_GPGGA 0x00000002u
191 #define USE_GPGLL 0x00000004u
192 #define USE_GPZDA 0x00000008u
193 #define USE_PGRMF 0x00000100u
195 /* mapping from sentence index to controlling mode bit */
196 static const u_int32 sentence_mode[NMEA_ARRAY_SIZE] =
206 /* date formats we support */
208 DATE_1_DDMMYY, /* use 1 field with 2-digit year */
209 DATE_3_DDMMYYYY /* use 3 fields with 4-digit year */
212 /* results for 'field_init()'
214 * Note: If a checksum is present, the checksum test must pass OK or the
215 * sentence is tagged invalid.
217 #define CHECK_EMPTY -1 /* no data */
218 #define CHECK_INVALID 0 /* not a valid NMEA sentence */
219 #define CHECK_VALID 1 /* valid but without checksum */
220 #define CHECK_CSVALID 2 /* valid with checksum OK */
223 * Unit control structure
227 struct refclock_atom atom; /* PPSAPI structure */
228 int ppsapi_fd; /* fd used with PPSAPI */
229 u_char ppsapi_tried; /* attempt PPSAPI once */
230 u_char ppsapi_lit; /* time_pps_create() worked */
231 u_char ppsapi_gate; /* system is on PPS */
232 #endif /* HAVE_PPSAPI */
233 u_char gps_time; /* use GPS time, not UTC */
234 u_short century_cache; /* cached current century */
235 l_fp last_reftime; /* last processed reference stamp */
236 short epoch_warp; /* last epoch warp, for logging */
237 /* tally stats, reset each poll cycle */
242 u_int rejected; /* GPS said not enough signal */
243 u_int malformed; /* Bad checksum, invalid date or time */
244 u_int filtered; /* mode bits, not GPZDG, same second */
248 /* per sentence checksum seen flag */
249 u_char cksum_type[NMEA_ARRAY_SIZE];
253 * helper for faster field access
256 char *base; /* buffer base */
257 char *cptr; /* current field ptr */
258 int blen; /* buffer length */
259 int cidx; /* current field index */
263 * NMEA gps week/time information
264 * This record contains the number of weeks since 1980-01-06 modulo
265 * 1024, the seconds elapsed since start of the week, and the number of
266 * leap seconds that are the difference between GPS and UTC time scale.
269 u_int32 wt_time; /* seconds since weekstart */
270 u_short wt_week; /* week number */
271 short wt_leap; /* leap seconds */
275 * The GPS week time scale starts on Sunday, 1980-01-06. We need the
276 * rata die number of this day.
278 #ifndef DAY_GPS_STARTS
279 #define DAY_GPS_STARTS 722820
283 * Function prototypes
285 static void nmea_init (void);
286 static int nmea_start (int, struct peer *);
287 static void nmea_shutdown (int, struct peer *);
288 static void nmea_receive (struct recvbuf *);
289 static void nmea_poll (int, struct peer *);
291 static void nmea_control (int, const struct refclockstat *,
292 struct refclockstat *, struct peer *);
293 #define NMEA_CONTROL nmea_control
295 #define NMEA_CONTROL noentry
296 #endif /* HAVE_PPSAPI */
297 static void nmea_timer (int, struct peer *);
299 /* parsing helpers */
300 static int field_init (nmea_data * data, char * cp, int len);
301 static char * field_parse (nmea_data * data, int fn);
302 static void field_wipe (nmea_data * data, ...);
303 static u_char parse_qual (nmea_data * data, int idx,
305 static int parse_time (struct calendar * jd, long * nsec,
306 nmea_data *, int idx);
307 static int parse_date (struct calendar *jd, nmea_data*,
308 int idx, enum date_fmt fmt);
309 static int parse_weekdata (gps_weektm *, nmea_data *,
310 int weekidx, int timeidx, int leapidx);
311 /* calendar / date helpers */
312 static int unfold_day (struct calendar * jd, u_int32 rec_ui);
313 static int unfold_century (struct calendar * jd, u_int32 rec_ui);
314 static int gpsfix_century (struct calendar * jd, const gps_weektm * wd,
316 static l_fp eval_gps_time (struct peer * peer, const struct calendar * gpst,
317 const struct timespec * gpso, const l_fp * xrecv);
319 static int nmead_open (const char * device);
320 static void save_ltc (struct refclockproc * const, const char * const,
324 * If we want the driver to ouput sentences, too: re-enable the send
325 * support functions by defining NMEA_WRITE_SUPPORT to non-zero...
327 #if NMEA_WRITE_SUPPORT
329 static void gps_send(int, const char *, struct peer *);
331 # undef write /* ports/winnt/include/config.h: #define write _write */
332 extern int async_write(int, const void *, unsigned int);
333 # define write(fd, data, octets) async_write(fd, data, octets)
334 # endif /* SYS_WINNT */
336 #endif /* NMEA_WRITE_SUPPORT */
338 static int32_t g_gpsMinBase;
339 static int32_t g_gpsMinYear;
342 * -------------------------------------------------------------------
344 * -------------------------------------------------------------------
346 struct refclock refclock_nmea = {
347 nmea_start, /* start up driver */
348 nmea_shutdown, /* shut down driver */
349 nmea_poll, /* transmit poll message */
350 NMEA_CONTROL, /* fudge control */
351 nmea_init, /* initialize driver */
352 noentry, /* buginfo */
353 nmea_timer /* called once per second */
357 * -------------------------------------------------------------------
358 * nmea_init - initialise data
360 * calculates a few runtime constants that cannot be made compile time
362 * -------------------------------------------------------------------
367 struct calendar date;
369 /* - calculate min. base value for GPS epoch & century unfolding
370 * This assumes that the build system was roughly in sync with
371 * the world, and that really synchronising to a time before the
372 * program was created would be unsafe or insane. If the build
373 * date cannot be stablished, at least use the start of GPS
374 * (1980-01-06) as minimum, because GPS can surely NOT
375 * synchronise beyond it's own big bang. We add a little safety
376 * margin for the fuzziness of the build date, which is in an
377 * undefined time zone. */
378 if (ntpcal_get_build_date(&date))
379 g_gpsMinBase = ntpcal_date_to_rd(&date) - 2;
383 if (g_gpsMinBase < DAY_GPS_STARTS)
384 g_gpsMinBase = DAY_GPS_STARTS;
386 ntpcal_rd_to_date(&date, g_gpsMinBase);
387 g_gpsMinYear = date.year;
388 g_gpsMinBase -= DAY_NTP_STARTS;
392 * -------------------------------------------------------------------
393 * nmea_start - open the GPS devices and initialize data for processing
395 * return 0 on error, 1 on success. Even on error the peer structures
396 * must be in a state that permits 'nmea_shutdown()' to clean up all
397 * resources, because it will be called immediately to do so.
398 * -------------------------------------------------------------------
406 struct refclockproc * const pp = peer->procptr;
407 nmea_unit * const up = emalloc_zero(sizeof(*up));
412 const char * baudtext;
415 /* Get baudrate choice from mode byte bits 4/5/6 */
416 rate = (peer->ttl & NMEA_BAUDRATE_MASK) >> NMEA_BAUDRATE_SHIFT;
449 baudtext = "4800 (fallback)";
453 /* Allocate and initialize unit structure */
454 pp->unitptr = (caddr_t)up;
456 pp->io.clock_recv = nmea_receive;
457 pp->io.srcclock = peer;
459 /* force change detection on first valid message */
460 memset(&up->last_reftime, 0xFF, sizeof(up->last_reftime));
461 /* force checksum on GPRMC, see below */
462 up->cksum_type[NMEA_GPRMC] = CHECK_CSVALID;
468 /* Initialize miscellaneous variables */
469 peer->precision = PRECISION;
470 pp->clockdesc = DESCRIPTION;
471 memcpy(&pp->refid, REFID, 4);
473 /* Open serial port. Use CLK line discipline, if available. */
474 devlen = snprintf(device, sizeof(device), DEVICE, unit);
475 if (devlen >= sizeof(device)) {
476 msyslog(LOG_ERR, "%s clock device name too long",
477 refnumtoa(&peer->srcadr));
478 return FALSE; /* buffer overflow */
480 pp->io.fd = refclock_open(device, baudrate, LDISC_CLK);
481 if (0 >= pp->io.fd) {
482 pp->io.fd = nmead_open(device);
486 LOGIF(CLOCKINFO, (LOG_NOTICE, "%s serial %s open at %s bps",
487 refnumtoa(&peer->srcadr), device, baudtext));
489 /* succeed if this clock can be added */
490 return io_addclock(&pp->io) != 0;
495 * -------------------------------------------------------------------
496 * nmea_shutdown - shut down a GPS clock
498 * NOTE this routine is called after nmea_start() returns failure,
499 * as well as during a normal shutdown due to ntpq :config unpeer.
500 * -------------------------------------------------------------------
508 struct refclockproc * const pp = peer->procptr;
509 nmea_unit * const up = (nmea_unit *)pp->unitptr;
516 time_pps_destroy(up->atom.handle);
517 if (up->ppsapi_tried && up->ppsapi_fd != pp->io.fd)
518 close(up->ppsapi_fd);
522 pp->unitptr = (caddr_t)NULL;
524 io_closeclock(&pp->io);
529 * -------------------------------------------------------------------
530 * nmea_control - configure fudge params
531 * -------------------------------------------------------------------
537 const struct refclockstat * in_st,
538 struct refclockstat * out_st,
542 struct refclockproc * const pp = peer->procptr;
543 nmea_unit * const up = (nmea_unit *)pp->unitptr;
554 * If /dev/gpspps$UNIT can be opened that will be used for
555 * PPSAPI. Otherwise, the GPS serial device /dev/gps$UNIT
556 * already opened is used for PPSAPI as well. (This might not
557 * work, in which case the PPS API remains unavailable...)
560 /* Light up the PPSAPI interface if not yet attempted. */
561 if ((CLK_FLAG1 & pp->sloppyclockflag) && !up->ppsapi_tried) {
562 up->ppsapi_tried = TRUE;
563 devlen = snprintf(device, sizeof(device), PPSDEV, unit);
564 if (devlen < sizeof(device)) {
565 up->ppsapi_fd = open(device, PPSOPENMODE,
569 msyslog(LOG_ERR, "%s PPS device name too long",
570 refnumtoa(&peer->srcadr));
572 if (-1 == up->ppsapi_fd)
573 up->ppsapi_fd = pp->io.fd;
574 if (refclock_ppsapi(up->ppsapi_fd, &up->atom)) {
575 /* use the PPS API for our own purposes now. */
576 up->ppsapi_lit = refclock_params(
577 pp->sloppyclockflag, &up->atom);
578 if (!up->ppsapi_lit) {
579 /* failed to configure, drop PPS unit */
580 time_pps_destroy(up->atom.handle);
582 "%s set PPSAPI params fails",
583 refnumtoa(&peer->srcadr));
585 /* note: the PPS I/O handle remains valid until
586 * flag1 is cleared or the clock is shut down.
590 "%s flag1 1 but PPSAPI fails",
591 refnumtoa(&peer->srcadr));
595 /* shut down PPS API if activated */
596 if (!(CLK_FLAG1 & pp->sloppyclockflag) && up->ppsapi_tried) {
597 /* shutdown PPS API */
599 time_pps_destroy(up->atom.handle);
601 /* close/drop PPS fd */
602 if (up->ppsapi_fd != pp->io.fd)
603 close(up->ppsapi_fd);
606 /* clear markers and peer items */
607 up->ppsapi_gate = FALSE;
608 up->ppsapi_lit = FALSE;
609 up->ppsapi_tried = FALSE;
611 peer->flags &= ~FLAG_PPS;
612 peer->precision = PRECISION;
615 #endif /* HAVE_PPSAPI */
618 * -------------------------------------------------------------------
619 * nmea_timer - called once per second
620 * this only polls (older?) Oncore devices now
622 * Usually 'nmea_receive()' can get a timestamp every second, but at
623 * least one Motorola unit needs prompting each time. Doing so in
624 * 'nmea_poll()' gives only one sample per poll cycle, which actually
625 * defeats the purpose of the median filter. Polling once per second
626 * seems a much better idea.
627 * -------------------------------------------------------------------
635 #if NMEA_WRITE_SUPPORT
637 struct refclockproc * const pp = peer->procptr;
641 if (-1 != pp->io.fd) /* any mode bits to evaluate here? */
642 gps_send(pp->io.fd, "$PMOTG,RMC,0000*1D\r\n", peer);
648 #endif /* NMEA_WRITE_SUPPORT */
653 * -------------------------------------------------------------------
654 * refclock_ppsrelate(...) -- correlate with PPS edge
656 * This function is used to correlate a receive time stamp and a
657 * reference time with a PPS edge time stamp. It applies the necessary
658 * fudges (fudge1 for PPS, fudge2 for receive time) and then tries to
659 * move the receive time stamp to the corresponding edge. This can warp
660 * into future, if a transmission delay of more than 500ms is not
661 * compensated with a corresponding fudge time2 value, because then the
662 * next PPS edge is nearer than the last. (Similiar to what the PPS ATOM
663 * driver does, but we deal with full time stamps here, not just phase
664 * shift information.) Likewise, a negative fudge time2 value must be
665 * used if the reference time stamp correlates with the *following* PPS
668 * Note that the receive time fudge value only needs to move the receive
669 * stamp near a PPS edge but that close proximity is not required;
670 * +/-100ms precision should be enough. But since the fudge value will
671 * probably also be used to compensate the transmission delay when no
672 * PPS edge can be related to the time stamp, it's best to get it as
675 * It should also be noted that the typical use case is matching to the
676 * preceeding edge, as most units relate their sentences to the current
679 * The function returns PPS_RELATE_NONE (0) if no PPS edge correlation
680 * can be fixed; PPS_RELATE_EDGE (1) when a PPS edge could be fixed, but
681 * the distance to the reference time stamp is too big (exceeds
682 * +/-400ms) and the ATOM driver PLL cannot be used to fix the phase;
683 * and PPS_RELATE_PHASE (2) when the ATOM driver PLL code can be used.
685 * On output, the receive time stamp is replaced with the corresponding
686 * PPS edge time if a fix could be made; the PPS fudge is updated to
687 * reflect the proper fudge time to apply. (This implies that
688 * 'refclock_process_offset()' must be used!)
689 * -------------------------------------------------------------------
691 #define PPS_RELATE_NONE 0 /* no pps correlation possible */
692 #define PPS_RELATE_EDGE 1 /* recv time fixed, no phase lock */
693 #define PPS_RELATE_PHASE 2 /* recv time fixed, phase lock ok */
697 const struct refclockproc * pp , /* for sanity */
698 const struct refclock_atom * ap , /* for PPS io */
699 const l_fp * reftime ,
700 l_fp * rd_stamp, /* i/o read stamp */
701 double pp_fudge, /* pps fudge */
702 double * rd_fudge /* i/o read fudge */
706 struct timespec timeout;
707 l_fp pp_stamp, pp_delta;
708 double delta, idelta;
710 if (pp->leap == LEAP_NOTINSYNC)
711 return PPS_RELATE_NONE; /* clock is insane, no chance */
715 if (time_pps_fetch(ap->handle, PPS_TSFMT_TSPEC,
716 &pps_info, &timeout) < 0)
717 return PPS_RELATE_NONE; /* can't get time stamps */
719 /* get last active PPS edge before receive */
720 if (ap->pps_params.mode & PPS_CAPTUREASSERT)
721 timeout = pps_info.assert_timestamp;
722 else if (ap->pps_params.mode & PPS_CAPTURECLEAR)
723 timeout = pps_info.clear_timestamp;
725 return PPS_RELATE_NONE; /* WHICH edge, please?!? */
727 /* get delta between receive time and PPS time */
728 pp_stamp = tspec_stamp_to_lfp(timeout);
729 pp_delta = *rd_stamp;
730 L_SUB(&pp_delta, &pp_stamp);
731 LFPTOD(&pp_delta, delta);
732 delta += pp_fudge - *rd_fudge;
733 if (fabs(delta) > 1.5)
734 return PPS_RELATE_NONE; /* PPS timeout control */
736 /* eventually warp edges, check phase */
737 idelta = floor(delta + 0.5);
740 if (fabs(delta) > 0.45)
741 return PPS_RELATE_NONE; /* dead band control */
743 /* we actually have a PPS edge to relate with! */
744 *rd_stamp = pp_stamp;
745 *rd_fudge = pp_fudge;
747 /* if whole system out-of-sync, do not try to PLL */
748 if (sys_leap == LEAP_NOTINSYNC)
749 return PPS_RELATE_EDGE; /* cannot PLL with atom code */
751 /* check against reftime if ATOM PLL can be used */
753 L_SUB(&pp_delta, &pp_stamp);
754 LFPTOD(&pp_delta, delta);
756 if (fabs(delta) > 0.45)
757 return PPS_RELATE_EDGE; /* cannot PLL with atom code */
759 /* all checks passed, gets an AAA rating here! */
760 return PPS_RELATE_PHASE; /* can PLL with atom code */
762 #endif /* HAVE_PPSAPI */
765 * -------------------------------------------------------------------
766 * nmea_receive - receive data from the serial interface
768 * This is the workhorse for NMEA data evaluation:
770 * + it checks all NMEA data, and rejects sentences that are not valid
772 * + it checks whether a sentence is known and to be used
773 * + it parses the time and date data from the NMEA data string and
774 * augments the missing bits. (century in dat, whole date, ...)
775 * + it rejects data that is not from the first accepted sentence in a
777 * + it eventually replaces the receive time with the PPS edge time.
778 * + it feeds the data to the internal processing stages.
779 * -------------------------------------------------------------------
783 struct recvbuf * rbufp
786 /* declare & init control structure ptrs */
787 struct peer * const peer = rbufp->recv_peer;
788 struct refclockproc * const pp = peer->procptr;
789 nmea_unit * const up = (nmea_unit*)pp->unitptr;
791 /* Use these variables to hold data until we decide its worth keeping */
793 char rd_lastcode[BMAX];
794 l_fp rd_timestamp, rd_reftime;
799 struct calendar date; /* to keep & convert the time stamp */
800 struct timespec tofs; /* offset to full-second reftime */
801 gps_weektm gpsw; /* week time storage */
802 /* results of sentence/date/time parsing */
803 u_char sentence; /* sentence tag */
809 /* make sure data has defined pristine state */
813 sentence = 0; // Should never be needed.
814 rc_date = 0; // Should never be needed.
815 rc_time = 0; // Should never be needed.
818 * Read the timecode and timestamp, then initialise field
819 * processing. The <CR><LF> at the NMEA line end is translated
820 * to <LF><LF> by the terminal input routines on most systems,
821 * and this gives us one spurious empty read per record which we
822 * better ignore silently.
824 rd_lencode = refclock_gtlin(rbufp, rd_lastcode,
825 sizeof(rd_lastcode), &rd_timestamp);
826 checkres = field_init(&rdata, rd_lastcode, rd_lencode);
830 DPRINTF(1, ("%s invalid data: '%s'\n",
831 refnumtoa(&peer->srcadr), rd_lastcode));
832 refclock_report(peer, CEVNT_BADREPLY);
839 DPRINTF(1, ("%s gpsread: %d '%s'\n",
840 refnumtoa(&peer->srcadr), rd_lencode,
847 * --> below this point we have a valid NMEA sentence <--
849 * Check sentence name. Skip first 2 chars (talker ID) in most
850 * cases, to allow for $GLGGA and $GPGGA etc. Since the name
851 * field has at least 5 chars we can simply shift the field
854 cp = field_parse(&rdata, 0);
855 if (strncmp(cp + 2, "RMC,", 4) == 0)
856 sentence = NMEA_GPRMC;
857 else if (strncmp(cp + 2, "GGA,", 4) == 0)
858 sentence = NMEA_GPGGA;
859 else if (strncmp(cp + 2, "GLL,", 4) == 0)
860 sentence = NMEA_GPGLL;
861 else if (strncmp(cp + 2, "ZDA,", 4) == 0)
862 sentence = NMEA_GPZDA;
863 else if (strncmp(cp + 2, "ZDG,", 4) == 0)
864 sentence = NMEA_GPZDG;
865 else if (strncmp(cp, "PGRMF,", 6) == 0)
866 sentence = NMEA_PGRMF;
868 return; /* not something we know about */
870 /* Eventually output delay measurement now. */
871 if (peer->ttl & NMEA_DELAYMEAS_MASK) {
872 mprintf_clock_stats(&peer->srcadr, "delay %0.6f %.*s",
873 ldexp(rd_timestamp.l_uf, -32),
874 (int)(strchr(rd_lastcode, ',') - rd_lastcode),
878 /* See if I want to process this message type */
879 if ((peer->ttl & NMEA_MESSAGE_MASK) &&
880 !(peer->ttl & sentence_mode[sentence])) {
881 up->tally.filtered++;
886 * make sure it came in clean
888 * Apparently, older NMEA specifications (which are expensive)
889 * did not require the checksum for all sentences. $GPMRC is
890 * the only one so far identified which has always been required
891 * to include a checksum.
893 * Today, most NMEA GPS receivers checksum every sentence. To
894 * preserve its error-detection capabilities with modern GPSes
895 * while allowing operation without checksums on all but $GPMRC,
896 * we keep track of whether we've ever seen a valid checksum on
897 * a given sentence, and if so, reject future instances without
898 * checksum. ('up->cksum_type[NMEA_GPRMC]' is set in
899 * 'nmea_start()' to enforce checksums for $GPRMC right from the
902 if (up->cksum_type[sentence] <= (u_char)checkres) {
903 up->cksum_type[sentence] = (u_char)checkres;
905 DPRINTF(1, ("%s checksum missing: '%s'\n",
906 refnumtoa(&peer->srcadr), rd_lastcode));
907 refclock_report(peer, CEVNT_BADREPLY);
908 up->tally.malformed++;
913 * $GPZDG provides GPS time not UTC, and the two mix poorly.
914 * Once have processed a $GPZDG, do not process any further UTC
915 * sentences (all but $GPZDG currently).
917 if (up->gps_time && NMEA_GPZDG != sentence) {
918 up->tally.filtered++;
922 DPRINTF(1, ("%s processing %d bytes, timecode '%s'\n",
923 refnumtoa(&peer->srcadr), rd_lencode, rd_lastcode));
926 * Grab fields depending on clock string type and possibly wipe
927 * sensitive data from the last timecode.
932 /* Check quality byte, fetch data & time */
933 rc_time = parse_time(&date, &tofs.tv_nsec, &rdata, 1);
934 pp->leap = parse_qual(&rdata, 2, 'A', 0);
935 rc_date = parse_date(&date, &rdata, 9, DATE_1_DDMMYY)
936 && unfold_century(&date, rd_timestamp.l_ui);
937 if (CLK_FLAG4 & pp->sloppyclockflag)
938 field_wipe(&rdata, 3, 4, 5, 6, -1);
942 /* Check quality byte, fetch time only */
943 rc_time = parse_time(&date, &tofs.tv_nsec, &rdata, 1);
944 pp->leap = parse_qual(&rdata, 6, '0', 1);
945 rc_date = unfold_day(&date, rd_timestamp.l_ui);
946 if (CLK_FLAG4 & pp->sloppyclockflag)
947 field_wipe(&rdata, 2, 4, -1);
951 /* Check quality byte, fetch time only */
952 rc_time = parse_time(&date, &tofs.tv_nsec, &rdata, 5);
953 pp->leap = parse_qual(&rdata, 6, 'A', 0);
954 rc_date = unfold_day(&date, rd_timestamp.l_ui);
955 if (CLK_FLAG4 & pp->sloppyclockflag)
956 field_wipe(&rdata, 1, 3, -1);
960 /* No quality. Assume best, fetch time & full date */
961 pp->leap = LEAP_NOWARNING;
962 rc_time = parse_time(&date, &tofs.tv_nsec, &rdata, 1);
963 rc_date = parse_date(&date, &rdata, 2, DATE_3_DDMMYYYY);
967 /* Check quality byte, fetch time & full date */
968 rc_time = parse_time(&date, &tofs.tv_nsec, &rdata, 1);
969 rc_date = parse_date(&date, &rdata, 2, DATE_3_DDMMYYYY);
970 pp->leap = parse_qual(&rdata, 4, '0', 1);
971 tofs.tv_sec = -1; /* GPZDG is following second */
975 /* get date, time, qualifier and GPS weektime. We need
976 * date and time-of-day for the century fix, so we read
979 rc_date = parse_weekdata(&gpsw, &rdata, 1, 2, 5)
980 && parse_date(&date, &rdata, 3, DATE_1_DDMMYY);
981 rc_time = parse_time(&date, &tofs.tv_nsec, &rdata, 4);
982 pp->leap = parse_qual(&rdata, 11, '0', 1);
984 && gpsfix_century(&date, &gpsw, &up->century_cache);
985 if (CLK_FLAG4 & pp->sloppyclockflag)
986 field_wipe(&rdata, 6, 8, -1);
990 INVARIANT(0); /* Coverity 97123 */
994 /* Check sanity of time-of-day. */
995 if (rc_time == 0) { /* no time or conversion error? */
996 checkres = CEVNT_BADTIME;
997 up->tally.malformed++;
999 /* Check sanity of date. */
1000 else if (rc_date == 0) {/* no date or conversion error? */
1001 checkres = CEVNT_BADDATE;
1002 up->tally.malformed++;
1004 /* check clock sanity; [bug 2143] */
1005 else if (pp->leap == LEAP_NOTINSYNC) { /* no good status? */
1006 checkres = CEVNT_BADREPLY;
1007 up->tally.rejected++;
1012 if (checkres != -1) {
1013 save_ltc(pp, rd_lastcode, rd_lencode);
1014 refclock_report(peer, checkres);
1018 DPRINTF(1, ("%s effective timecode: %04u-%02u-%02u %02d:%02d:%02d\n",
1019 refnumtoa(&peer->srcadr),
1020 date.year, date.month, date.monthday,
1021 date.hour, date.minute, date.second));
1023 /* Check if we must enter GPS time mode; log so if we do */
1024 if (!up->gps_time && (sentence == NMEA_GPZDG)) {
1025 msyslog(LOG_INFO, "%s using GPS time as if it were UTC",
1026 refnumtoa(&peer->srcadr));
1031 * Get the reference time stamp from the calendar buffer.
1032 * Process the new sample in the median filter and determine the
1033 * timecode timestamp, but only if the PPS is not in control.
1034 * Discard sentence if reference time did not change.
1036 rd_reftime = eval_gps_time(peer, &date, &tofs, &rd_timestamp);
1037 if (L_ISEQU(&up->last_reftime, &rd_reftime)) {
1038 /* Do not touch pp->a_lastcode on purpose! */
1039 up->tally.filtered++;
1042 up->last_reftime = rd_reftime;
1043 rd_fudge = pp->fudgetime2;
1045 DPRINTF(1, ("%s using '%s'\n",
1046 refnumtoa(&peer->srcadr), rd_lastcode));
1048 /* Data will be accepted. Update stats & log data. */
1049 up->tally.accepted++;
1050 save_ltc(pp, rd_lastcode, rd_lencode);
1051 pp->lastrec = rd_timestamp;
1055 * If we have PPS running, we try to associate the sentence
1056 * with the last active edge of the PPS signal.
1059 switch (refclock_ppsrelate(
1060 pp, &up->atom, &rd_reftime, &rd_timestamp,
1061 pp->fudgetime1, &rd_fudge))
1063 case PPS_RELATE_PHASE:
1064 up->ppsapi_gate = TRUE;
1065 peer->precision = PPS_PRECISION;
1066 peer->flags |= FLAG_PPS;
1067 DPRINTF(2, ("%s PPS_RELATE_PHASE\n",
1068 refnumtoa(&peer->srcadr)));
1069 up->tally.pps_used++;
1072 case PPS_RELATE_EDGE:
1073 up->ppsapi_gate = TRUE;
1074 peer->precision = PPS_PRECISION;
1075 DPRINTF(2, ("%s PPS_RELATE_EDGE\n",
1076 refnumtoa(&peer->srcadr)));
1079 case PPS_RELATE_NONE:
1082 * Resetting precision and PPS flag is done in
1083 * 'nmea_poll', since it might be a glitch. But
1084 * at the end of the poll cycle we know...
1086 DPRINTF(2, ("%s PPS_RELATE_NONE\n",
1087 refnumtoa(&peer->srcadr)));
1090 #endif /* HAVE_PPSAPI */
1092 refclock_process_offset(pp, rd_reftime, rd_timestamp, rd_fudge);
1097 * -------------------------------------------------------------------
1098 * nmea_poll - called by the transmit procedure
1100 * Does the necessary bookkeeping stuff to keep the reported state of
1101 * the clock in sync with reality.
1103 * We go to great pains to avoid changing state here, since there may
1104 * be more than one eavesdropper receiving the same timecode.
1105 * -------------------------------------------------------------------
1113 struct refclockproc * const pp = peer->procptr;
1114 nmea_unit * const up = (nmea_unit *)pp->unitptr;
1117 * Process median filter samples. If none received, declare a
1118 * timeout and keep going.
1122 * If we don't have PPS pulses and time stamps, turn PPS down
1125 if (!up->ppsapi_gate) {
1126 peer->flags &= ~FLAG_PPS;
1127 peer->precision = PRECISION;
1129 up->ppsapi_gate = FALSE;
1131 #endif /* HAVE_PPSAPI */
1134 * If the median filter is empty, claim a timeout. Else process
1135 * the input data and keep the stats going.
1137 if (pp->coderecv == pp->codeproc) {
1138 refclock_report(peer, CEVNT_TIMEOUT);
1141 pp->lastref = pp->lastrec;
1142 refclock_receive(peer);
1146 * If extended logging is required, write the tally stats to the
1147 * clockstats file; otherwise just do a normal clock stats
1148 * record. Clear the tally stats anyway.
1150 if (peer->ttl & NMEA_EXTLOG_MASK) {
1151 /* Log & reset counters with extended logging */
1152 const char *nmea = pp->a_lastcode;
1153 if (*nmea == '\0') nmea = "(none)";
1154 mprintf_clock_stats(
1155 &peer->srcadr, "%s %u %u %u %u %u %u",
1157 up->tally.total, up->tally.accepted,
1158 up->tally.rejected, up->tally.malformed,
1159 up->tally.filtered, up->tally.pps_used);
1161 record_clock_stats(&peer->srcadr, pp->a_lastcode);
1167 * -------------------------------------------------------------------
1168 * Save the last timecode string, making sure it's properly truncated
1169 * if necessary and NUL terminated in any case.
1173 struct refclockproc * const pp,
1174 const char * const tc,
1178 if (len >= sizeof(pp->a_lastcode))
1179 len = sizeof(pp->a_lastcode) - 1;
1180 pp->lencode = (u_short)len;
1181 memcpy(pp->a_lastcode, tc, len);
1182 pp->a_lastcode[len] = '\0';
1186 #if NMEA_WRITE_SUPPORT
1188 * -------------------------------------------------------------------
1189 * gps_send(fd, cmd, peer) Sends a command to the GPS receiver.
1190 * as in gps_send(fd, "rqts,u", peer);
1192 * If 'cmd' starts with a '$' it is assumed that this command is in raw
1193 * format, that is, starts with '$', ends with '<cr><lf>' and that any
1194 * checksum is correctly provided; the command will be send 'as is' in
1195 * that case. Otherwise the function will create the necessary frame
1196 * (start char, chksum, final CRLF) on the fly.
1198 * We don't currently send any data, but would like to send RTCM SC104
1199 * messages for differential positioning. It should also give us better
1200 * time. Without a PPS output, we're Just fooling ourselves because of
1201 * the serial code paths
1202 * -------------------------------------------------------------------
1211 /* $...*xy<CR><LF><NUL> add 7 */
1212 char buf[NMEA_PROTO_MAXLEN + 7];
1215 const u_char *beg, *end;
1218 /* get checksum and length */
1219 beg = end = (const u_char*)cmd;
1221 while (*end >= ' ' && *end != '*')
1224 /* format into output buffer with overflow check */
1225 len = snprintf(buf, sizeof(buf), "$%.*s*%02X\r\n",
1227 if ((size_t)len >= sizeof(buf)) {
1228 DPRINTF(1, ("%s gps_send: buffer overflow for command '%s'\n",
1229 refnumtoa(&peer->srcadr), cmd));
1230 return; /* game over player 1 */
1237 DPRINTF(1, ("%s gps_send: '%.*s'\n", refnumtoa(&peer->srcadr),
1240 /* send out the whole stuff */
1241 if (write(fd, cmd, len) == -1)
1242 refclock_report(peer, CEVNT_FAULT);
1244 #endif /* NMEA_WRITE_SUPPORT */
1247 * -------------------------------------------------------------------
1248 * helpers for faster field splitting
1249 * -------------------------------------------------------------------
1251 * set up a field record, check syntax and verify checksum
1253 * format is $XXXXX,1,2,3,4*ML
1255 * 8-bit XOR of characters between $ and * noninclusive is transmitted
1256 * in last two chars M and L holding most and least significant nibbles
1257 * in hex representation such as:
1259 * $GPGLL,5057.970,N,00146.110,E,142451,A*27
1260 * $GPVTG,089.0,T,,,15.2,N,,*7F
1262 * Some other constraints:
1263 * + The field name must at least 5 upcase characters or digits and must
1264 * start with a character.
1265 * + The checksum (if present) must be uppercase hex digits.
1266 * + The length of a sentence is limited to 80 characters (not including
1267 * the final CR/LF nor the checksum, but including the leading '$')
1271 * The data does not form a valid NMEA sentence or a checksum error
1274 * The data is a valid NMEA sentence but contains no checksum.
1276 * The data is a valid NMEA sentence and passed the checksum test.
1277 * -------------------------------------------------------------------
1281 nmea_data * data, /* context structure */
1282 char * cptr, /* start of raw data */
1283 int dlen /* data len, not counting trailing NUL */
1286 u_char cs_l; /* checksum local computed */
1287 u_char cs_r; /* checksum remote given */
1288 char * eptr; /* buffer end end pointer */
1289 char tmp; /* char buffer */
1293 /* some basic input constraints */
1299 /* load data context */
1305 /* syntax check follows here. check allowed character
1306 * sequences, updating the local computed checksum as we go.
1308 * regex equiv: '^\$[A-Z][A-Z0-9]{4,}[^*]*(\*[0-9A-F]{2})?$'
1311 /* -*- start character: '^\$' */
1315 return CHECK_INVALID;
1317 /* -*- advance context beyond start character */
1322 /* -*- field name: '[A-Z][A-Z0-9]{4,},' */
1323 if (*cptr < 'A' || *cptr > 'Z')
1324 return CHECK_INVALID;
1326 while ((*cptr >= 'A' && *cptr <= 'Z') ||
1327 (*cptr >= '0' && *cptr <= '9') )
1329 if (*cptr != ',' || (cptr - data->base) < NMEA_PROTO_IDLEN)
1330 return CHECK_INVALID;
1333 /* -*- data: '[^*]*' */
1334 while (*cptr && *cptr != '*')
1337 /* -*- checksum field: (\*[0-9A-F]{2})?$ */
1340 if (*cptr != '*' || cptr != eptr - 3 ||
1341 (cptr - data->base) >= NMEA_PROTO_MAXLEN)
1342 return CHECK_INVALID;
1344 for (cptr++; (tmp = *cptr) != '\0'; cptr++) {
1345 if (tmp >= '0' && tmp <= '9')
1346 cs_r = (cs_r << 4) + (tmp - '0');
1347 else if (tmp >= 'A' && tmp <= 'F')
1348 cs_r = (cs_r << 4) + (tmp - 'A' + 10);
1353 /* -*- make sure we are at end of string and csum matches */
1354 if (cptr != eptr || cs_l != cs_r)
1355 return CHECK_INVALID;
1357 return CHECK_CSVALID;
1361 * -------------------------------------------------------------------
1362 * fetch a data field by index, zero being the name field. If this
1363 * function is called repeatedly with increasing indices, the total load
1364 * is O(n), n being the length of the string; if it is called with
1365 * decreasing indices, the total load is O(n^2). Try not to go backwards
1367 * -------------------------------------------------------------------
1377 if (fn < data->cidx) {
1379 data->cptr = data->base;
1381 while ((fn > data->cidx) && (tmp = *data->cptr) != '\0') {
1382 data->cidx += (tmp == ',');
1389 * -------------------------------------------------------------------
1390 * Wipe (that is, overwrite with '_') data fields and the checksum in
1391 * the last timecode. The list of field indices is given as integers
1392 * in a varargs list, preferrably in ascending order, in any case
1393 * terminated by a negative field index.
1395 * A maximum number of 8 fields can be overwritten at once to guard
1396 * against runaway (that is, unterminated) argument lists.
1398 * This function affects what a remote user can see with
1400 * ntpq -c clockvar <server>
1402 * Note that this also removes the wiped fields from any clockstats
1403 * log. Some NTP operators monitor their NMEA GPS using the change in
1404 * location in clockstats over time as as a proxy for the quality of
1405 * GPS reception and thereby time reported.
1406 * -------------------------------------------------------------------
1414 va_list va; /* vararg index list */
1415 int fcnt; /* safeguard against runaway arglist */
1416 int fidx; /* field to nuke, or -1 for checksum */
1417 char * cp; /* overwrite destination */
1423 fidx = va_arg(va, int);
1424 if (fidx >= 0 && fidx <= NMEA_PROTO_FIELDS) {
1425 cp = field_parse(data, fidx);
1427 cp = data->base + data->blen;
1428 if (data->blen >= 3 && cp[-3] == '*')
1431 for ( ; '\0' != *cp && '*' != *cp && ',' != *cp; cp++)
1434 } while (fcnt-- && fidx >= 0);
1439 * -------------------------------------------------------------------
1441 * -------------------------------------------------------------------
1445 * If the character at the data field start matches the tag value,
1446 * return LEAP_NOWARNING and LEAP_NOTINSYNC otherwise. If the 'inverted'
1447 * flag is given, just the opposite value is returned. If there is no
1448 * data field (*cp points to the NUL byte) the result is LEAP_NOTINSYNC.
1449 * -------------------------------------------------------------------
1459 static const u_char table[2] =
1460 { LEAP_NOTINSYNC, LEAP_NOWARNING };
1463 dp = field_parse(rd, idx);
1465 return table[ *dp && ((*dp == tag) == !inv) ];
1469 * -------------------------------------------------------------------
1470 * Parse a time stamp in HHMMSS[.sss] format with error checking.
1472 * returns 1 on success, 0 on failure
1473 * -------------------------------------------------------------------
1477 struct calendar * jd, /* result calendar pointer */
1478 long * ns, /* storage for nsec fraction */
1483 static const unsigned long weight[4] = {
1484 0, 100000000, 10000000, 1000000
1496 dp = field_parse(rd, idx);
1497 rc = sscanf(dp, "%2u%2u%2u%n.%3lu%n", &h, &m, &s, &p1, &f, &p2);
1498 if (rc < 3 || p1 != 6) {
1499 DPRINTF(1, ("nmea: invalid time code: '%.6s'\n", dp));
1503 /* value sanity check */
1504 if (h > 23 || m > 59 || s > 60) {
1505 DPRINTF(1, ("nmea: invalid time spec %02u:%02u:%02u\n",
1510 jd->hour = (u_char)h;
1511 jd->minute = (u_char)m;
1512 jd->second = (u_char)s;
1513 /* if we have a fraction, scale it up to nanoseconds. */
1515 *ns = f * weight[p2 - p1 - 1];
1523 * -------------------------------------------------------------------
1524 * Parse a date string from an NMEA sentence. This could either be a
1525 * partial date in DDMMYY format in one field, or DD,MM,YYYY full date
1526 * spec spanning three fields. This function does some extensive error
1527 * checking to make sure the date string was consistent.
1529 * returns 1 on success, 0 on failure
1530 * -------------------------------------------------------------------
1534 struct calendar * jd, /* result pointer */
1547 dp = field_parse(rd, idx);
1551 rc = sscanf(dp, "%2u%2u%2u%n", &d, &m, &y, &p);
1552 if (rc != 3 || p != 6) {
1553 DPRINTF(1, ("nmea: invalid date code: '%.6s'\n",
1559 case DATE_3_DDMMYYYY:
1560 rc = sscanf(dp, "%2u,%2u,%4u%n", &d, &m, &y, &p);
1561 if (rc != 3 || p != 10) {
1562 DPRINTF(1, ("nmea: invalid date code: '%.10s'\n",
1569 DPRINTF(1, ("nmea: invalid parse format: %d\n", fmt));
1573 /* value sanity check */
1574 if (d < 1 || d > 31 || m < 1 || m > 12) {
1575 DPRINTF(1, ("nmea: invalid date spec (YMD) %04u:%02u:%02u\n",
1581 jd->monthday = (u_char)d;
1582 jd->month = (u_char)m;
1583 jd->year = (u_short)y;
1589 * -------------------------------------------------------------------
1590 * Parse GPS week time info from an NMEA sentence. This info contains
1591 * the GPS week number, the GPS time-of-week and the leap seconds GPS
1594 * returns 1 on success, 0 on failure
1595 * -------------------------------------------------------------------
1609 /* parse fields and count success */
1610 fcnt = sscanf(field_parse(rd, weekidx), "%hu", &wd->wt_week);
1611 fcnt += sscanf(field_parse(rd, timeidx), "%lu", &secs);
1612 fcnt += sscanf(field_parse(rd, leapidx), "%hd", &wd->wt_leap);
1613 if (fcnt != 3 || wd->wt_week >= 1024 || secs >= 7*SECSPERDAY) {
1614 DPRINTF(1, ("nmea: parse_weekdata: invalid weektime spec\n"));
1617 wd->wt_time = (u_int32)secs;
1623 * -------------------------------------------------------------------
1624 * funny calendar-oriented stuff -- perhaps a bit hard to grok.
1625 * -------------------------------------------------------------------
1627 * Unfold a time-of-day (seconds since midnight) around the current
1628 * system time in a manner that guarantees an absolute difference of
1631 * This function is used for NMEA sentences that contain no date
1632 * information. This requires the system clock to be in +/-12hrs
1633 * around the true time, or the clock will synchronize the system 1day
1634 * off if not augmented with a time sources that also provide the
1635 * necessary date information.
1637 * The function updates the calendar structure it also uses as
1638 * input to fetch the time from.
1640 * returns 1 on success, 0 on failure
1641 * -------------------------------------------------------------------
1645 struct calendar * jd,
1650 ntpcal_split rec_ds;
1653 * basically this is the peridiodic extension of the receive
1654 * time - 12hrs to the time-of-day with a period of 1 day.
1655 * But we would have to execute this in 64bit arithmetic, and we
1656 * cannot assume we can do this; therefore this is done
1657 * in split representation.
1659 rec_qw = ntpcal_ntp_to_ntp(rec_ui - SECSPERDAY/2, NULL);
1660 rec_ds = ntpcal_daysplit(&rec_qw);
1661 rec_ds.lo = ntpcal_periodic_extend(rec_ds.lo,
1662 ntpcal_date_to_daysec(jd),
1664 rec_ds.hi += ntpcal_daysec_to_date(jd, rec_ds.lo);
1665 return (ntpcal_rd_to_date(jd, rec_ds.hi + DAY_NTP_STARTS) >= 0);
1669 * -------------------------------------------------------------------
1670 * A 2-digit year is expanded into full year spec around the year found
1671 * in 'jd->year'. This should be in +79/-19 years around the system time,
1672 * or the result will be off by 100 years. The assymetric behaviour was
1673 * chosen to enable inital sync for systems that do not have a
1674 * battery-backup clock and start with a date that is typically years in
1677 * Since the GPS epoch starts at 1980-01-06, the resulting year will be
1678 * not be before 1980 in any case.
1680 * returns 1 on success, 0 on failure
1681 * -------------------------------------------------------------------
1685 struct calendar * jd,
1689 struct calendar rec;
1692 ntpcal_ntp_to_date(&rec, rec_ui, NULL);
1693 baseyear = rec.year - 20;
1694 if (baseyear < g_gpsMinYear)
1695 baseyear = g_gpsMinYear;
1696 jd->year = (u_short)ntpcal_periodic_extend(baseyear, jd->year,
1699 return ((baseyear <= jd->year) && (baseyear + 100 > jd->year));
1703 * -------------------------------------------------------------------
1704 * A 2-digit year is expanded into a full year spec by correlation with
1705 * a GPS week number and the current leap second count.
1707 * The GPS week time scale counts weeks since Sunday, 1980-01-06, modulo
1708 * 1024 and seconds since start of the week. The GPS time scale is based
1709 * on international atomic time (TAI), so the leap second difference to
1710 * UTC is also needed for a proper conversion.
1712 * A brute-force analysis (that is, test for every date) shows that a
1713 * wrong assignment of the century can not happen between the years 1900
1714 * to 2399 when comparing the week signatures for different
1715 * centuries. (I *think* that will not happen for 400*1024 years, but I
1716 * have no valid proof. -*-perlinger@ntp.org-*-)
1718 * This function is bound to to work between years 1980 and 2399
1719 * (inclusive), which should suffice for now ;-)
1721 * Note: This function needs a full date&time spec on input due to the
1722 * necessary leap second corrections!
1724 * returns 1 on success, 0 on failure
1725 * -------------------------------------------------------------------
1729 struct calendar * jd,
1730 const gps_weektm * wd,
1740 /* Get day offset. Assumes that the input time is in range and
1741 * that the leap seconds do not shift more than +/-1 day.
1743 doff = ntpcal_date_to_daysec(jd) + wd->wt_leap;
1744 doff = (doff >= SECSPERDAY) - (doff < 0);
1747 * Loop over centuries to get a match, starting with the last
1748 * successful one. (Or with the 19th century if the cached value
1749 * is out of range...)
1751 year = jd->year % 100;
1752 for (loop = 5; loop > 0; loop--,(*century)++) {
1753 if (*century < 19 || *century >= 24)
1755 /* Get days and week in GPS epoch */
1756 jd->year = year + *century * 100;
1757 days = ntpcal_date_to_rd(jd) - DAY_GPS_STARTS + doff;
1758 week = (days / 7) % 1024;
1759 if (days >= 0 && wd->wt_week == week)
1760 return TRUE; /* matched... */
1764 return FALSE; /* match failed... */
1768 * -------------------------------------------------------------------
1769 * And now the final execise: Considering the fact that many (most?)
1770 * GPS receivers cannot handle a GPS epoch wrap well, we try to
1771 * compensate for that problem by unwrapping a GPS epoch around the
1772 * receive stamp. Another execise in periodic unfolding, of course,
1773 * but with enough points to take care of.
1775 * Note: The integral part of 'tofs' is intended to handle small(!)
1776 * systematic offsets, as -1 for handling $GPZDG, which gives the
1777 * following second. (sigh...) The absolute value shall be less than a
1778 * day (86400 seconds).
1779 * -------------------------------------------------------------------
1783 struct peer * peer, /* for logging etc */
1784 const struct calendar * gpst, /* GPS time stamp */
1785 const struct timespec * tofs, /* GPS frac second & offset */
1786 const l_fp * xrecv /* receive time stamp */
1789 struct refclockproc * const pp = peer->procptr;
1790 nmea_unit * const up = (nmea_unit *)pp->unitptr;
1794 /* components of calculation */
1795 int32_t rcv_sec, rcv_day; /* receive ToD and day */
1796 int32_t gps_sec, gps_day; /* GPS ToD and day in NTP epoch */
1797 int32_t adj_day, weeks; /* adjusted GPS day and week shift */
1799 /* some temporaries to shuffle data */
1803 /* evaluate time stamp from receiver. */
1804 gps_sec = ntpcal_date_to_daysec(gpst);
1805 gps_day = ntpcal_date_to_rd(gpst) - DAY_NTP_STARTS;
1807 /* merge in fractional offset */
1808 retv = tspec_intv_to_lfp(*tofs);
1809 gps_sec += retv.l_i;
1811 /* If we fully trust the GPS receiver, just combine days and
1812 * seconds and be done. */
1813 if (peer->ttl & NMEA_DATETRUST_MASK) {
1814 retv.l_ui = ntpcal_dayjoin(gps_day, gps_sec).D_s.lo;
1818 /* So we do not trust the GPS receiver to deliver a correct date
1819 * due to the GPS epoch changes. We map the date from the
1820 * receiver into the +/-512 week interval around the receive
1821 * time in that case. This would be a tad easier with 64bit
1822 * calculations, but again, we restrict the code to 32bit ops
1825 /* - make sure the GPS fractional day is normalised
1826 * Applying the offset value might have put us slightly over the
1827 * edge of the allowed range for seconds-of-day. Doing a full
1828 * division with floor correction is overkill here; a simple
1829 * addition or subtraction step is sufficient. Using WHILE loops
1830 * gives the right result even if the offset exceeds one day,
1831 * which is NOT what it's intented for! */
1832 while (gps_sec >= SECSPERDAY) {
1833 gps_sec -= SECSPERDAY;
1836 while (gps_sec < 0) {
1837 gps_sec += SECSPERDAY;
1841 /* - get unfold base: day of full recv time - 512 weeks */
1842 vi64 = ntpcal_ntp_to_ntp(xrecv->l_ui, NULL);
1843 rs64 = ntpcal_daysplit(&vi64);
1845 rcv_day = rs64.hi - 512 * 7;
1847 /* - take the fractional days into account
1848 * If the fractional day of the GPS time is smaller than the
1849 * fractional day of the receive time, we shift the base day for
1850 * the unfold by 1. */
1851 if ( gps_sec < rcv_sec
1852 || (gps_sec == rcv_sec && retv.l_uf < xrecv->l_uf))
1855 /* - don't warp ahead of GPS invention! */
1856 if (rcv_day < g_gpsMinBase)
1857 rcv_day = g_gpsMinBase;
1859 /* - let the magic happen: */
1860 adj_day = ntpcal_periodic_extend(rcv_day, gps_day, 1024*7);
1862 /* - check if we should log a GPS epoch warp */
1863 weeks = (adj_day - gps_day) / 7;
1864 if (weeks != up->epoch_warp) {
1865 up->epoch_warp = weeks;
1866 LOGIF(CLOCKINFO, (LOG_INFO,
1867 "%s Changed GPS epoch warp to %d weeks",
1868 refnumtoa(&peer->srcadr), weeks));
1871 /* - build result and be done */
1872 retv.l_ui = ntpcal_dayjoin(adj_day, gps_sec).D_s.lo;
1877 * ===================================================================
1881 * original nmead support added by Jon Miner (cp_n18@yahoo.com)
1883 * See http://home.hiwaay.net/~taylorc/gps/nmea-server/
1884 * for information about nmead
1886 * To use this, you need to create a link from /dev/gpsX to
1887 * the server:port where nmead is running. Something like this:
1889 * ln -s server:port /dev/gps1
1891 * Split into separate function by Juergen Perlinger
1892 * (perlinger-at-ntp-dot-org)
1894 * ===================================================================
1901 int fd = -1; /* result file descriptor */
1903 #ifdef HAVE_READLINK
1904 char host[80]; /* link target buffer */
1905 char * port; /* port name or number */
1906 int rc; /* result code (several)*/
1907 int sh; /* socket handle */
1908 struct addrinfo ai_hint; /* resolution hint */
1909 struct addrinfo *ai_list; /* resolution result */
1910 struct addrinfo *ai; /* result scan ptr */
1914 /* try to read as link, make sure no overflow occurs */
1915 rc = readlink(device, host, sizeof(host));
1916 if ((size_t)rc >= sizeof(host))
1917 return fd; /* error / overflow / truncation */
1918 host[rc] = '\0'; /* readlink does not place NUL */
1921 port = strchr(host, ':');
1923 return fd; /* not 'host:port' syntax ? */
1924 *port++ = '\0'; /* put in separator */
1926 /* get address infos and try to open socket
1928 * This getaddrinfo() is naughty in ntpd's nonblocking main
1929 * thread, but you have to go out of your wary to use this code
1930 * and typically the blocking is at startup where its impact is
1931 * reduced. The same holds for the 'connect()', as it is
1935 ai_hint.ai_protocol = IPPROTO_TCP;
1936 ai_hint.ai_socktype = SOCK_STREAM;
1937 if (getaddrinfo(host, port, &ai_hint, &ai_list))
1940 for (ai = ai_list; ai && (fd == -1); ai = ai->ai_next) {
1941 sh = socket(ai->ai_family, ai->ai_socktype,
1943 if (INVALID_SOCKET == sh)
1945 rc = connect(sh, ai->ai_addr, ai->ai_addrlen);
1951 freeaddrinfo(ai_list);
1959 NONEMPTY_TRANSLATION_UNIT
1960 #endif /* REFCLOCK && CLOCK_NMEA */