2 * This software was developed by the Computer Systems Engineering group
3 * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66.
5 * Copyright (c) 1992 The Regents of the University of California.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Lawrence Berkeley Laboratory.
20 * 4. The name of the University may not be used to endorse or promote
21 * products derived from this software without specific prior
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * Modified: Marc Brett <marc.brett@westgeo.com> Sept, 1999.
40 * 1. Added support for alternate PPS schemes, with code mostly
41 * copied from the Oncore driver (Thanks, Poul-Henning Kamp).
42 * This code runs on SunOS 4.1.3 with ppsclock-1.6a1 and Solaris 7.
50 #if defined(REFCLOCK) && defined(CLOCK_MX4200) && defined(HAVE_PPSAPI)
54 #include "ntp_refclock.h"
55 #include "ntp_unixtime.h"
56 #include "ntp_stdlib.h"
63 #ifdef HAVE_SYS_TERMIOS_H
64 # include <sys/termios.h>
66 #ifdef HAVE_SYS_PPSCLOCK_H
67 # include <sys/ppsclock.h>
70 #ifndef HAVE_STRUCT_PPSCLOCKEV
72 # ifdef HAVE_STRUCT_TIMESPEC
79 #endif /* ! HAVE_STRUCT_PPSCLOCKEV */
82 # include "ppsapi_timepps.h"
83 #endif /* HAVE_PPSAPI */
86 * This driver supports the Magnavox Model MX 4200 GPS Receiver
87 * adapted to precision timing applications. It requires the
88 * ppsclock line discipline or streams module described in the
89 * Line Disciplines and Streams Drivers page. It also requires a
90 * gadget box and 1-PPS level converter, such as described in the
91 * Pulse-per-second (PPS) Signal Interfacing page.
93 * It's likely that other compatible Magnavox receivers such as the
94 * MX 4200D, MX 9212, MX 9012R, MX 9112 will be supported by this code.
98 * Check this every time you edit the code!
100 #define YEAR_LAST_MODIFIED 2000
105 #define DEVICE "/dev/gps%d" /* device name and unit */
106 #define SPEED232 B4800 /* baud */
109 * Radio interface parameters
111 #define PRECISION (-18) /* precision assumed (about 4 us) */
112 #define REFID "GPS\0" /* reference id */
113 #define DESCRIPTION "Magnavox MX4200 GPS Receiver" /* who we are */
114 #define DEFFUDGETIME 0 /* default fudge time (ms) */
116 #define SLEEPTIME 32 /* seconds to wait for reconfig to complete */
119 * Position Averaging.
121 #define INTERVAL 1 /* Interval between position measurements (s) */
122 #define AVGING_TIME 24 /* Number of hours to average */
123 #define NOT_INITIALIZED -9999. /* initial pivot longitude */
126 * MX4200 unit control structure.
129 u_int pollcnt; /* poll message counter */
130 u_int polled; /* Hand in a time sample? */
131 u_int lastserial; /* last pps serial number */
132 struct ppsclockev ppsev; /* PPS control structure */
133 double avg_lat; /* average latitude */
134 double avg_lon; /* average longitude */
135 double avg_alt; /* average height */
136 double central_meridian; /* central meridian */
137 double N_fixes; /* Number of position measurements */
138 int last_leap; /* leap second warning */
139 u_int moving; /* mobile platform? */
140 u_long sloppyclockflag; /* fudge flags */
141 u_int known; /* position known yet? */
142 u_long clamp_time; /* when to stop postion averaging */
143 u_long log_time; /* when to print receiver status */
149 static char pmvxg[] = "PMVXG";
151 /* XXX should be somewhere else */
153 #if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 5)
154 #ifndef __attribute__
155 #define __attribute__(args)
156 #endif /* __attribute__ */
157 #endif /* __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 5) */
159 #ifndef __attribute__
160 #define __attribute__(args)
161 #endif /* __attribute__ */
162 #endif /* __GNUC__ */
166 * Function prototypes
168 static int mx4200_start (int, struct peer *);
169 static void mx4200_shutdown (int, struct peer *);
170 static void mx4200_receive (struct recvbuf *);
171 static void mx4200_poll (int, struct peer *);
173 static char * mx4200_parse_t (struct peer *);
174 static char * mx4200_parse_p (struct peer *);
175 static char * mx4200_parse_s (struct peer *);
176 int mx4200_cmpl_fp (const void *, const void *);
177 static int mx4200_config (struct peer *);
178 static void mx4200_ref (struct peer *);
179 static void mx4200_send (struct peer *, char *, ...)
180 __attribute__ ((format (printf, 2, 3)));
181 static u_char mx4200_cksum (char *, int);
182 static int mx4200_jday (int, int, int);
183 static void mx4200_debug (struct peer *, char *, ...)
184 __attribute__ ((format (printf, 2, 3)));
185 static int mx4200_pps (struct peer *);
190 struct refclock refclock_mx4200 = {
191 mx4200_start, /* start up driver */
192 mx4200_shutdown, /* shut down driver */
193 mx4200_poll, /* transmit poll message */
194 noentry, /* not used (old mx4200_control) */
195 noentry, /* initialize driver (not used) */
196 noentry, /* not used (old mx4200_buginfo) */
197 NOFLAGS /* not used */
203 * mx4200_start - open the devices and initialize data for processing
211 register struct mx4200unit *up;
212 struct refclockproc *pp;
219 snprintf(gpsdev, sizeof(gpsdev), DEVICE, unit);
220 fd = refclock_open(gpsdev, SPEED232, LDISC_PPS);
225 * Allocate unit structure
227 up = emalloc_zero(sizeof(*up));
229 pp->io.clock_recv = mx4200_receive;
230 pp->io.srcclock = peer;
233 if (!io_addclock(&pp->io)) {
242 * Initialize miscellaneous variables
244 peer->precision = PRECISION;
245 pp->clockdesc = DESCRIPTION;
246 memcpy((char *)&pp->refid, REFID, 4);
248 /* Ensure the receiver is properly configured */
249 return mx4200_config(peer);
254 * mx4200_shutdown - shut down the clock
262 register struct mx4200unit *up;
263 struct refclockproc *pp;
268 io_closeclock(&pp->io);
275 * mx4200_config - Configure the receiver
284 register struct mx4200unit *up;
285 struct refclockproc *pp;
292 * Initialize the unit variables
294 * STRANGE BEHAVIOUR WARNING: The fudge flags are not available
295 * at the time mx4200_start is called. These are set later,
296 * and so the code must be prepared to handle changing flags.
298 up->sloppyclockflag = pp->sloppyclockflag;
299 if (pp->sloppyclockflag & CLK_FLAG2) {
300 up->moving = 1; /* Receiver on mobile platform */
301 msyslog(LOG_DEBUG, "mx4200_config: mobile platform");
303 up->moving = 0; /* Static Installation */
311 up->central_meridian = NOT_INITIALIZED;
313 up->last_leap = 0; /* LEAP_NOWARNING */
314 up->clamp_time = current_time + (AVGING_TIME * 60 * 60);
315 up->log_time = current_time + SLEEPTIME;
317 if (time_pps_create(pp->io.fd, &up->pps_h) < 0) {
318 perror("time_pps_create");
320 "mx4200_config: time_pps_create failed: %m");
323 if (time_pps_getcap(up->pps_h, &mode) < 0) {
325 "mx4200_config: time_pps_getcap failed: %m");
329 if (time_pps_getparams(up->pps_h, &up->pps_p) < 0) {
331 "mx4200_config: time_pps_getparams failed: %m");
335 /* nb. only turn things on, if someone else has turned something
336 * on before we get here, leave it alone!
339 up->pps_p.mode = PPS_CAPTUREASSERT | PPS_TSFMT_TSPEC;
340 up->pps_p.mode &= mode; /* only set what is legal */
342 if (time_pps_setparams(up->pps_h, &up->pps_p) < 0) {
343 perror("time_pps_setparams");
345 "mx4200_config: time_pps_setparams failed: %m");
349 if (time_pps_kcbind(up->pps_h, PPS_KC_HARDPPS, PPS_CAPTUREASSERT,
350 PPS_TSFMT_TSPEC) < 0) {
351 perror("time_pps_kcbind");
353 "mx4200_config: time_pps_kcbind failed: %m");
359 * "007" Control Port Configuration
360 * Zero the output list (do it twice to flush possible junk)
362 mx4200_send(peer, "%s,%03d,,%d,,,,,,", pmvxg,
364 /* control port output block Label */
365 1); /* clear current output control list (1=yes) */
366 /* add/delete sentences from list */
368 /* sentence output rate (sec) */
369 /* precision for position output */
370 /* nmea version for cga & gll output */
371 /* pass-through control */
372 mx4200_send(peer, "%s,%03d,,%d,,,,,,", pmvxg,
373 PMVXG_S_PORTCONF, 1);
376 * Request software configuration so we can syslog the firmware version
378 mx4200_send(peer, "%s,%03d", "CDGPQ", PMVXG_D_SOFTCONF);
381 * "001" Initialization/Mode Control, Part A
384 mx4200_send(peer, "%s,%03d,,,,,,,,,,", pmvxg,
390 /* latitude DDMM.MMMM */
392 /* longitude DDDMM.MMMM */
395 /* Altitude Reference 1=MSL */
398 * "001" Initialization/Mode Control, Part B
399 * Start off in 2d/3d coast mode, holding altitude to last known
400 * value if only 3 satellites available.
402 mx4200_send(peer, "%s,%03d,%d,,%.1f,%.1f,%d,%d,%d,%c,%d",
403 pmvxg, PMVXG_S_INITMODEB,
406 0.1, /* hor accel fact as per Steve (m/s**2) */
407 0.1, /* ver accel fact as per Steve (m/s**2) */
409 10, /* hdop limit as per Steve */
410 5, /* elevation limit as per Steve (deg) */
411 'U', /* time output mode (UTC) */
412 0); /* local time offset from gmt (HHHMM) */
415 * "023" Time Recovery Configuration
416 * Get UTC time from a stationary receiver.
417 * (Set field 1 'D' == dynamic if we are on a moving platform).
418 * (Set field 1 'S' == static if we are not moving).
419 * (Set field 1 'K' == known position if we can initialize lat/lon/alt).
422 if (pp->sloppyclockflag & CLK_FLAG2)
423 up->moving = 1; /* Receiver on mobile platform */
425 up->moving = 0; /* Static Installation */
429 /* dynamic: solve for pos, alt, time, while moving */
432 /* static: solve for pos, alt, time, while stationary */
435 mx4200_send(peer, "%s,%03d,%c,%c,%c,%d,%d,%d,", pmvxg,
437 tr_mode, /* time recovery mode (see above ) */
438 'U', /* synchronize to UTC */
439 'A', /* always output a time pulse */
440 500, /* max time error in ns */
441 0, /* user bias in ns */
442 1); /* output "830" sentences to control port */
443 /* Multi-satellite mode */
446 * Output position information (to calculate fixed installation
447 * location) only if we are not moving
450 add_mode = 2; /* delete from list */
452 add_mode = 1; /* add to list */
457 * "007" Control Port Configuration
458 * Output "021" position, height, velocity reports
460 mx4200_send(peer, "%s,%03d,%03d,%d,%d,,%d,,,", pmvxg,
462 PMVXG_D_PHV, /* control port output block Label */
463 0, /* clear current output control list (0=no) */
464 add_mode, /* add/delete sentences from list (1=add, 2=del) */
466 INTERVAL); /* sentence output rate (sec) */
467 /* precision for position output */
468 /* nmea version for cga & gll output */
469 /* pass-through control */
475 * mx4200_ref - Reconfigure unit as a reference station at a known position.
482 register struct mx4200unit *up;
483 struct refclockproc *pp;
484 double minute, lat, lon, alt;
485 char lats[16], lons[16];
491 /* Should never happen! */
492 if (up->moving) return;
495 * Set up to output status information in the near future
497 up->log_time = current_time + SLEEPTIME;
500 * "007" Control Port Configuration
501 * Stop outputting "021" position, height, velocity reports
503 mx4200_send(peer, "%s,%03d,%03d,%d,%d,,,,,", pmvxg,
505 PMVXG_D_PHV, /* control port output block Label */
506 0, /* clear current output control list (0=no) */
507 2); /* add/delete sentences from list (2=delete) */
509 /* sentence output rate (sec) */
510 /* precision for position output */
511 /* nmea version for cga & gll output */
512 /* pass-through control */
515 * "001" Initialization/Mode Control, Part B
516 * Put receiver in fully-constrained 2d nav mode
518 mx4200_send(peer, "%s,%03d,%d,,%.1f,%.1f,%d,%d,%d,%c,%d",
519 pmvxg, PMVXG_S_INITMODEB,
522 0.1, /* hor accel fact as per Steve (m/s**2) */
523 0.1, /* ver accel fact as per Steve (m/s**2) */
525 10, /* hdop limit as per Steve */
526 5, /* elevation limit as per Steve (deg) */
527 'U', /* time output mode (UTC) */
528 0); /* local time offset from gmt (HHHMM) */
531 * "023" Time Recovery Configuration
532 * Get UTC time from a stationary receiver. Solve for time only.
533 * This should improve the time resolution dramatically.
535 mx4200_send(peer, "%s,%03d,%c,%c,%c,%d,%d,%d,", pmvxg,
537 'K', /* known position: solve for time only */
538 'U', /* synchronize to UTC */
539 'A', /* always output a time pulse */
540 500, /* max time error in ns */
541 0, /* user bias in ns */
542 1); /* output "830" sentences to control port */
543 /* Multi-satellite mode */
546 * "000" Initialization/Mode Control - Part A
547 * Fix to our averaged position.
549 if (up->central_meridian != NOT_INITIALIZED) {
550 up->avg_lon += up->central_meridian;
551 if (up->avg_lon < -180.0) up->avg_lon += 360.0;
552 if (up->avg_lon > 180.0) up->avg_lon -= 360.0;
555 if (up->avg_lat >= 0.0) {
559 lat = up->avg_lat * (-1.0);
562 if (up->avg_lon >= 0.0) {
566 lon = up->avg_lon * (-1.0);
570 minute = (lat - (double)(int)lat) * 60.0;
571 snprintf(lats, sizeof(lats), "%02d%02.4f", (int)lat, minute);
572 minute = (lon - (double)(int)lon) * 60.0;
573 snprintf(lons, sizeof(lons), "%03d%02.4f", (int)lon, minute);
575 mx4200_send(peer, "%s,%03d,,,,,%s,%c,%s,%c,%.2f,%d", pmvxg,
581 lats, /* latitude DDMM.MMMM */
582 nsc, /* north/south */
583 lons, /* longitude DDDMM.MMMM */
586 1); /* Altitude Reference (0=WGS84 ellipsoid, 1=MSL geoid)*/
589 "mx4200: reconfig to fixed location: %s %c, %s %c, %.2f m",
590 lats, nsc, lons, ewc, alt );
595 * mx4200_poll - mx4200 watchdog routine
603 register struct mx4200unit *up;
604 struct refclockproc *pp;
610 * You don't need to poll this clock. It puts out timecodes
611 * once per second. If asked for a timestamp, take note.
612 * The next time a timecode comes in, it will be fed back.
616 * If we haven't had a response in a while, reset the receiver.
618 if (up->pollcnt > 0) {
621 refclock_report(peer, CEVNT_TIMEOUT);
624 * Request a "000" status message which should trigger a
627 mx4200_send(peer, "%s,%03d",
628 "CDGPQ", /* query from CDU to GPS */
629 PMVXG_D_STATUS); /* label of desired sentence */
633 * polled every 64 seconds. Ask mx4200_receive to hand in
640 * Output receiver status information.
642 if ((up->log_time > 0) && (current_time > up->log_time)) {
645 * Output the following messages once, for debugging.
647 * "523" Time Recovery Parameters
649 mx4200_send(peer, "%s,%03d", "CDGPQ", PMVXG_D_MODEDATA);
650 mx4200_send(peer, "%s,%03d", "CDGPQ", PMVXG_D_TRECOVUSEAGE);
654 static char char2hex[] = "0123456789ABCDEF";
657 * mx4200_receive - receive gps data
661 struct recvbuf *rbufp
664 register struct mx4200unit *up;
665 struct refclockproc *pp;
672 * Initialize pointers and read the timecode and timestamp.
674 peer = rbufp->recv_peer;
679 * If operating mode has been changed, then reinitialize the receiver
680 * before doing anything else.
682 if ((pp->sloppyclockflag & CLK_FLAG2) !=
683 (up->sloppyclockflag & CLK_FLAG2)) {
684 up->sloppyclockflag = pp->sloppyclockflag;
686 "mx4200_receive: mode switch: reset receiver\n");
690 up->sloppyclockflag = pp->sloppyclockflag;
693 * Read clock output. Automatically handles STREAMS, CLKLDISC.
695 pp->lencode = refclock_gtlin(rbufp, pp->a_lastcode, BMAX, &pp->lastrec);
698 * There is a case where <cr><lf> generates 2 timestamps.
700 if (pp->lencode == 0)
704 pp->a_lastcode[pp->lencode] = '\0';
705 record_clock_stats(&peer->srcadr, pp->a_lastcode);
706 mx4200_debug(peer, "mx4200_receive: %d %s\n",
707 pp->lencode, pp->a_lastcode);
710 * The structure of the control port sentences is based on the
711 * NMEA-0183 Standard for interfacing Marine Electronics
712 * Navigation Devices (Version 1.5)
714 * $PMVXG,XXX, ....................*CK<cr><lf>
716 * $ Sentence Start Identifier (reserved char)
717 * (Start-of-Sentence Identifier)
718 * P Special ID (Proprietary)
719 * MVX Originator ID (Magnavox)
720 * G Interface ID (GPS)
721 * , Field Delimiters (reserved char)
724 * * Checksum Field Delimiter (reserved char)
726 * <cr><lf> Carriage-Return/Line Feed (reserved chars)
727 * (End-of-Sentence Identifier)
729 * Reject if any important landmarks are missing.
731 cp = pp->a_lastcode + pp->lencode - 3;
732 if (cp < pp->a_lastcode || *pp->a_lastcode != '$' || cp[0] != '*' ) {
733 mx4200_debug(peer, "mx4200_receive: bad format\n");
734 refclock_report(peer, CEVNT_BADREPLY);
739 * Check and discard the checksum
741 ck = mx4200_cksum(&pp->a_lastcode[1], pp->lencode - 4);
742 if (char2hex[ck >> 4] != cp[1] || char2hex[ck & 0xf] != cp[2]) {
743 mx4200_debug(peer, "mx4200_receive: bad checksum\n");
744 refclock_report(peer, CEVNT_BADREPLY);
750 * Get the sentence type.
753 if ((cp = strchr(pp->a_lastcode, ',')) == NULL) {
754 mx4200_debug(peer, "mx4200_receive: no sentence\n");
755 refclock_report(peer, CEVNT_BADREPLY);
759 sentence_type = strtol(cp, &cp, 10);
762 * Process the sentence according to its type.
764 switch (sentence_type) {
767 * "000" Status message
772 * Since we configure the receiver to not give us status
773 * messages and since the receiver outputs status messages by
774 * default after being reset to factory defaults when sent the
775 * "$PMVXG,018,C\r\n" message, any status message we get
776 * indicates the reciever needs to be initialized; thus, it is
777 * not necessary to decode the status message.
779 if ((cp = mx4200_parse_s(peer)) != NULL) {
781 "mx4200_receive: status: %s\n", cp);
783 mx4200_debug(peer, "mx4200_receive: reset receiver\n");
788 * "021" Position, Height, Velocity message,
789 * if we are still averaging our position
794 * Parse the message, calculating our averaged position.
796 if ((cp = mx4200_parse_p(peer)) != NULL) {
797 mx4200_debug(peer, "mx4200_receive: pos: %s\n", cp);
801 "mx4200_receive: position avg %f %.9f %.9f %.4f\n",
802 up->N_fixes, up->avg_lat, up->avg_lon, up->avg_alt);
804 * Reinitialize as a reference station
805 * if position is well known.
807 if (current_time > up->clamp_time) {
809 mx4200_debug(peer, "mx4200_receive: reconfiguring!\n");
816 * Print to the syslog:
818 * "030" Software Configuration
819 * "523" Time Recovery Parameters Currently in Use
821 case PMVXG_D_MODEDATA:
822 case PMVXG_D_SOFTCONF:
823 case PMVXG_D_TRECOVUSEAGE:
825 if ((cp = mx4200_parse_s(peer)) != NULL) {
827 "mx4200_receive: multi-record: %s\n", cp);
832 * "830" Time Recovery Results message
834 case PMVXG_D_TRECOVOUT:
837 * Capture the last PPS signal.
838 * Precision timestamp is returned in pp->lastrec
840 if (0 != mx4200_pps(peer)) {
841 mx4200_debug(peer, "mx4200_receive: pps failure\n");
842 refclock_report(peer, CEVNT_FAULT);
848 * Parse the time recovery message, and keep the info
849 * to print the pretty billboards.
851 if ((cp = mx4200_parse_t(peer)) != NULL) {
852 mx4200_debug(peer, "mx4200_receive: time: %s\n", cp);
853 refclock_report(peer, CEVNT_BADREPLY);
858 * Add the new sample to a median filter.
860 if (!refclock_process(pp)) {
861 mx4200_debug(peer,"mx4200_receive: offset: %.6f\n",
863 refclock_report(peer, CEVNT_BADTIME);
868 * The clock will blurt a timecode every second but we only
869 * want one when polled. If we havn't been polled, bail out.
875 * Return offset and dispersion to control module. We use
876 * lastrec as both the reference time and receive time in
877 * order to avoid being cute, like setting the reference time
878 * later than the receive time, which may cause a paranoid
879 * protocol module to chuck out the data.
881 mx4200_debug(peer, "mx4200_receive: process time: ");
882 mx4200_debug(peer, "%4d-%03d %02d:%02d:%02d at %s, %.6f\n",
883 pp->year, pp->day, pp->hour, pp->minute, pp->second,
884 prettydate(&pp->lastrec), pp->offset);
885 pp->lastref = pp->lastrec;
886 refclock_receive(peer);
889 * We have succeeded in answering the poll.
890 * Turn off the flag and return
896 * Ignore all other sentence types
901 } /* switch (sentence_type) */
908 * Parse a mx4200 time recovery message. Returns a string if error.
910 * A typical message looks like this. Checksum has already been stripped.
912 * $PMVXG,830,T,YYYY,MM,DD,HH:MM:SS,U,S,FFFFFF,PPPPP,BBBBBB,LL
914 * Field Field Contents
915 * ----- --------------
916 * Block Label: $PMVXG
917 * Sentence Type: 830=Time Recovery Results
918 * This sentence is output approximately 1 second
919 * preceding the 1PPS output. It indicates the
920 * exact time of the next pulse, whether or not the
921 * time mark will be valid (based on operator-specified
922 * error tolerance), the time to which the pulse is
923 * synchronized, the receiver operating mode,
924 * and the time error of the *last* 1PPS output.
925 * 1 char Time Mark Valid: T=Valid, F=Not Valid
927 * 3 int Month of Year: 1-12
928 * 4 int Day of Month: 1-31
929 * 5 int Time of Day: HH:MM:SS
930 * 6 char Time Synchronization: U=UTC, G=GPS
931 * 7 char Time Recovery Mode: D=Dynamic, S=Static,
932 * K=Known Position, N=No Time Recovery
933 * 8 int Oscillator Offset: The filter's estimate of the oscillator
934 * frequency error, in parts per billion (ppb).
935 * 9 int Time Mark Error: The computed error of the *last* pulse
936 * output, in nanoseconds.
937 * 10 int User Time Bias: Operator specified bias, in nanoseconds
938 * 11 int Leap Second Flag: Indicates that a leap second will
939 * occur. This value is usually zero, except during
940 * the week prior to the leap second occurrence, when
941 * this value will be set to +1 or -1. A value of
942 * +1 indicates that GPS time will be 1 second
943 * further ahead of UTC time.
951 struct refclockproc *pp;
952 struct mx4200unit *up;
953 char time_mark_valid, time_sync, op_mode;
954 int sentence_type, valid;
955 int year, day_of_year, month, day_of_month;
956 int hour, minute, second, leapsec_warn;
957 int oscillator_offset, time_mark_error, time_bias;
962 leapsec_warn = 0; /* Not all receivers output leap second warnings (!) */
963 sscanf(pp->a_lastcode,
964 "$PMVXG,%d,%c,%d,%d,%d,%d:%d:%d,%c,%c,%d,%d,%d,%d",
965 &sentence_type, &time_mark_valid, &year, &month, &day_of_month,
966 &hour, &minute, &second, &time_sync, &op_mode,
967 &oscillator_offset, &time_mark_error, &time_bias, &leapsec_warn);
969 if (sentence_type != PMVXG_D_TRECOVOUT)
970 return ("wrong rec-type");
972 switch (time_mark_valid) {
980 return ("bad pulse-valid");
985 return ("synchronized to GPS; should be UTC");
987 break; /* UTC -> ok */
989 return ("not synchronized to UTC");
993 * Check for insane time (allow for possible leap seconds)
995 if (second > 60 || minute > 59 || hour > 23 ||
996 second < 0 || minute < 0 || hour < 0) {
998 "mx4200_parse_t: bad time %02d:%02d:%02d",
999 hour, minute, second);
1000 if (leapsec_warn != 0)
1001 mx4200_debug(peer, " (leap %+d\n)", leapsec_warn);
1002 mx4200_debug(peer, "\n");
1003 refclock_report(peer, CEVNT_BADTIME);
1004 return ("bad time");
1006 if ( second == 60 ) {
1008 "mx4200: leap second! %02d:%02d:%02d",
1009 hour, minute, second);
1013 * Check for insane date
1014 * (Certainly can't be any year before this code was last altered!)
1016 if (day_of_month > 31 || month > 12 ||
1017 day_of_month < 1 || month < 1 || year < YEAR_LAST_MODIFIED) {
1019 "mx4200_parse_t: bad date (%4d-%02d-%02d)\n",
1020 year, month, day_of_month);
1021 refclock_report(peer, CEVNT_BADDATE);
1022 return ("bad date");
1026 * Silly Hack for MX4200:
1027 * ASCII message is for *next* 1PPS signal, but we have the
1028 * timestamp for the *last* 1PPS signal. So we have to subtract
1029 * a second. Discard if we are on a month boundary to avoid
1030 * possible leap seconds and leap days.
1042 if (day_of_month < 1) {
1043 return ("sorry, month boundary");
1050 * Calculate Julian date
1052 if (!(day_of_year = mx4200_jday(year, month, day_of_month))) {
1054 "mx4200_parse_t: bad julian date %d (%4d-%02d-%02d)\n",
1055 day_of_year, year, month, day_of_month);
1056 refclock_report(peer, CEVNT_BADDATE);
1057 return("invalid julian date");
1061 * Setup leap second indicator
1063 switch (leapsec_warn) {
1065 pp->leap = LEAP_NOWARNING;
1068 pp->leap = LEAP_ADDSECOND;
1071 pp->leap = LEAP_DELSECOND;
1074 pp->leap = LEAP_NOTINSYNC;
1078 * Any change to the leap second warning status?
1080 if (leapsec_warn != up->last_leap ) {
1082 "mx4200: leap second warning: %d to %d (%d)",
1083 up->last_leap, leapsec_warn, pp->leap);
1085 up->last_leap = leapsec_warn;
1088 * Copy time data for billboard monitoring.
1092 pp->day = day_of_year;
1094 pp->minute = minute;
1095 pp->second = second;
1098 * Toss if sentence is marked invalid
1100 if (!valid || pp->leap == LEAP_NOTINSYNC) {
1101 mx4200_debug(peer, "mx4200_parse_t: time mark not valid\n");
1102 refclock_report(peer, CEVNT_BADTIME);
1103 return ("pulse invalid");
1110 * Calculate the checksum
1120 for (ck = 0; n-- > 0; cp++)
1126 * Tables to compute the day of year. Viva la leap.
1128 static int day1tab[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
1129 static int day2tab[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
1132 * Calculate the the Julian Day
1141 register int day, i;
1145 * Is this a leap year ?
1148 leap_year = 0; /* FALSE */
1151 leap_year = 1; /* TRUE */
1154 leap_year = 0; /* FALSE */
1156 leap_year = 1; /* TRUE */
1162 * Calculate the Julian Date
1168 if (day > day2tab[month - 1]) {
1171 for (i = 0; i < month - 1; i++)
1174 /* not a leap year */
1175 if (day > day1tab[month - 1]) {
1178 for (i = 0; i < month - 1; i++)
1185 * Parse a mx4200 position/height/velocity sentence.
1187 * A typical message looks like this. Checksum has already been stripped.
1189 * $PMVXG,021,SSSSSS.SS,DDMM.MMMM,N,DDDMM.MMMM,E,HHHHH.H,GGGG.G,EEEE.E,WWWW.W,MM
1191 * Field Field Contents
1192 * ----- --------------
1193 * Block Label: $PMVXG
1194 * Sentence Type: 021=Position, Height Velocity Data
1195 * This sentence gives the receiver position, height,
1196 * navigation mode, and velocity north/east.
1197 * *This sentence is intended for post-analysis
1199 * 1 float UTC measurement time (seconds into week)
1200 * 2 float WGS-84 Lattitude (degrees, minutes)
1201 * 3 char N=North, S=South
1202 * 4 float WGS-84 Longitude (degrees, minutes)
1203 * 5 char E=East, W=West
1204 * 6 float Altitude (meters above mean sea level)
1205 * 7 float Geoidal height (meters)
1206 * 8 float East velocity (m/sec)
1207 * 9 float West Velocity (m/sec)
1208 * 10 int Navigation Mode
1209 * Mode if navigating:
1210 * 1 = Position from remote device
1213 * 4 = 2-D differential position
1214 * 5 = 3-D differential position
1216 * 8 = Position known -- reference station
1217 * 9 = Position known -- Navigator
1218 * Mode if not navigating:
1219 * 51 = Too few satellites
1220 * 52 = DOPs too large
1221 * 53 = Position STD too large
1222 * 54 = Velocity STD too large
1223 * 55 = Too many iterations for velocity
1224 * 56 = Too many iterations for position
1225 * 57 = 3 sat startup failed
1226 * 58 = Command abort
1233 struct refclockproc *pp;
1234 struct mx4200unit *up;
1235 int sentence_type, mode;
1236 double mtime, lat, lon, alt, geoid, vele, veln;
1237 char north_south, east_west;
1242 /* Should never happen! */
1243 if (up->moving) return ("mobile platform - no pos!");
1245 sscanf ( pp->a_lastcode,
1246 "$PMVXG,%d,%lf,%lf,%c,%lf,%c,%lf,%lf,%lf,%lf,%d",
1247 &sentence_type, &mtime, &lat, &north_south, &lon, &east_west,
1248 &alt, &geoid, &vele, &veln, &mode);
1251 if (sentence_type != PMVXG_D_PHV)
1252 return ("wrong rec-type");
1255 * return if not navigating
1258 return ("not navigating");
1259 if (mode != 3 && mode != 5)
1260 return ("not navigating in 3D");
1262 /* Latitude (always +ve) and convert DDMM.MMMM to decimal */
1263 if (lat < 0.0) return ("negative latitude");
1264 if (lat > 9000.0) lat = 9000.0;
1266 lat = ((int)lat) + (((lat - (int)lat)) * 1.6666666666666666);
1269 switch (north_south) {
1276 return ("invalid north/south indicator");
1279 /* Longitude (always +ve) and convert DDDMM.MMMM to decimal */
1280 if (lon < 0.0) return ("negative longitude");
1281 if (lon > 180.0) lon = 180.0;
1283 lon = ((int)lon) + (((lon - (int)lon)) * 1.6666666666666666);
1286 switch (east_west) {
1293 return ("invalid east/west indicator");
1297 * Normalize longitude to near 0 degrees.
1298 * Assume all data are clustered around first reading.
1300 if (up->central_meridian == NOT_INITIALIZED) {
1301 up->central_meridian = lon;
1303 "mx4200_receive: central meridian = %.9f \n",
1304 up->central_meridian);
1306 lon -= up->central_meridian;
1307 if (lon < -180.0) lon += 360.0;
1308 if (lon > 180.0) lon -= 360.0;
1311 * Calculate running averages
1314 up->avg_lon = (up->N_fixes * up->avg_lon) + lon;
1315 up->avg_lat = (up->N_fixes * up->avg_lat) + lat;
1316 up->avg_alt = (up->N_fixes * up->avg_alt) + alt;
1320 up->avg_lon /= up->N_fixes;
1321 up->avg_lat /= up->N_fixes;
1322 up->avg_alt /= up->N_fixes;
1325 "mx4200_receive: position rdg %.0f: %.9f %.9f %.4f (CM=%.9f)\n",
1326 up->N_fixes, lat, lon, alt, up->central_meridian);
1332 * Parse a mx4200 Status sentence
1333 * Parse a mx4200 Mode Data sentence
1334 * Parse a mx4200 Software Configuration sentence
1335 * Parse a mx4200 Time Recovery Parameters Currently in Use sentence
1336 * (used only for logging raw strings)
1338 * A typical message looks like this. Checksum has already been stripped.
1340 * $PMVXG,000,XXX,XX,X,HHMM,X
1342 * Field Field Contents
1343 * ----- --------------
1344 * Block Label: $PMVXG
1345 * Sentence Type: 000=Status.
1346 * Returns status of the receiver to the controller.
1347 * 1 Current Receiver Status:
1348 * ACQ = Satellite re-acquisition
1349 * ALT = Constellation selection
1350 * COR = Providing corrections (for reference stations only)
1351 * IAC = Initial acquisition
1352 * IDL = Idle, no satellites
1354 * STS = Search the Sky (no almanac available)
1356 * 2 Number of satellites that should be visible
1357 * 3 Number of satellites being tracked
1358 * 4 Time since last navigation status if not currently navigating
1360 * 5 Initialization status:
1361 * 0 = Waiting for initialization parameters
1362 * 1 = Initialization completed
1364 * A typical message looks like this. Checksum has already been stripped.
1366 * $PMVXG,004,C,R,D,H.HH,V.VV,TT,HHHH,VVVV,T
1368 * Field Field Contents
1369 * ----- --------------
1370 * Block Label: $PMVXG
1371 * Sentence Type: 004=Software Configuration.
1372 * Defines the navigation mode and criteria for
1373 * acceptable navigation for the receiver.
1374 * 1 Constrain Altitude Mode:
1375 * 0 = Auto. Constrain altitude (2-D solution) and use
1376 * manual altitude input when 3 sats avalable. Do
1377 * not constrain altitude (3-D solution) when 4 sats
1379 * 1 = Always constrain altitude (2-D solution).
1380 * 2 = Never constrain altitude (3-D solution).
1381 * 3 = Coast. Constrain altitude (2-D solution) and use
1382 * last GPS altitude calculation when 3 sats avalable.
1383 * Do not constrain altitude (3-D solution) when 4 sats
1385 * 2 Altitude Reference: (always 0 for MX4200)
1388 * 3 Differential Navigation Control:
1391 * 4 Horizontal Acceleration Constant (m/sec**2)
1392 * 5 Vertical Acceleration Constant (m/sec**2) (0 for MX4200)
1393 * 6 Tracking Elevation Limit (degrees)
1396 * 9 Time Output Mode:
1399 * 10 Local Time Offset (minutes) (absent on MX4200)
1401 * A typical message looks like this. Checksum has already been stripped.
1403 * $PMVXG,030,NNNN,FFF
1405 * Field Field Contents
1406 * ----- --------------
1407 * Block Label: $PMVXG
1408 * Sentence Type: 030=Software Configuration.
1409 * This sentence contains the navigation processor
1410 * and baseband firmware version numbers.
1411 * 1 Nav Processor Version Number
1412 * 2 Baseband Firmware Version Number
1414 * A typical message looks like this. Checksum has already been stripped.
1416 * $PMVXG,523,M,S,M,EEEE,BBBBBB,C,R
1418 * Field Field Contents
1419 * ----- --------------
1420 * Block Label: $PMVXG
1421 * Sentence Type: 523=Time Recovery Parameters Currently in Use.
1422 * This sentence contains the configuration of the
1423 * time recovery feature of the receiver.
1424 * 1 Time Recovery Mode:
1425 * D = Dynamic; solve for position and time while moving
1426 * S = Static; solve for position and time while stationary
1427 * K = Known position input, solve for time only
1428 * N = No time recovery
1429 * 2 Time Synchronization:
1433 * A = Always output a time pulse
1434 * V = Only output time pulse if time is valid (as determined
1435 * by Maximum Time Error)
1436 * 4 Maximum Time Error - the maximum error (in nanoseconds) for
1437 * which a time mark will be considered valid.
1438 * 5 User Time Bias - external bias in nanoseconds
1439 * 6 Time Message Control:
1440 * 0 = Do not output the time recovery message
1441 * 1 = Output the time recovery message (record 830) to
1443 * 2 = Output the time recovery message (record 830) to
1446 * 8 Position Known PRN (absent on MX 4200)
1454 struct refclockproc *pp;
1455 struct mx4200unit *up;
1461 sscanf ( pp->a_lastcode, "$PMVXG,%d", &sentence_type);
1464 switch (sentence_type) {
1466 case PMVXG_D_STATUS:
1468 "mx4200: status: %s", pp->a_lastcode);
1470 case PMVXG_D_MODEDATA:
1472 "mx4200: mode data: %s", pp->a_lastcode);
1474 case PMVXG_D_SOFTCONF:
1476 "mx4200: firmware configuration: %s", pp->a_lastcode);
1478 case PMVXG_D_TRECOVUSEAGE:
1480 "mx4200: time recovery parms: %s", pp->a_lastcode);
1483 return ("wrong rec-type");
1490 * Process a PPS signal, placing a timestamp in pp->lastrec.
1498 struct refclockproc *pp;
1499 struct mx4200unit *up;
1501 struct timespec timeout;
1507 * Grab the timestamp of the PPS signal.
1509 temp_serial = up->pps_i.assert_sequence;
1511 timeout.tv_nsec = 0;
1512 if (time_pps_fetch(up->pps_h, PPS_TSFMT_TSPEC, &(up->pps_i),
1515 "mx4200_pps: time_pps_fetch: serial=%lu, %m\n",
1516 (unsigned long)up->pps_i.assert_sequence);
1517 refclock_report(peer, CEVNT_FAULT);
1520 if (temp_serial == up->pps_i.assert_sequence) {
1522 "mx4200_pps: assert_sequence serial not incrementing: %lu\n",
1523 (unsigned long)up->pps_i.assert_sequence);
1524 refclock_report(peer, CEVNT_FAULT);
1528 * Check pps serial number against last one
1530 if (up->lastserial + 1 != up->pps_i.assert_sequence &&
1531 up->lastserial != 0) {
1532 if (up->pps_i.assert_sequence == up->lastserial) {
1533 mx4200_debug(peer, "mx4200_pps: no new pps event\n");
1535 mx4200_debug(peer, "mx4200_pps: missed %lu pps events\n",
1536 up->pps_i.assert_sequence - up->lastserial - 1UL);
1538 refclock_report(peer, CEVNT_FAULT);
1540 up->lastserial = up->pps_i.assert_sequence;
1543 * Return the timestamp in pp->lastrec
1546 pp->lastrec.l_ui = up->pps_i.assert_timestamp.tv_sec +
1548 pp->lastrec.l_uf = ((double)(up->pps_i.assert_timestamp.tv_nsec) *
1549 4.2949672960) + 0.5;
1555 * mx4200_debug - print debug messages
1558 mx4200_debug(struct peer *peer, char *fmt, ...)
1562 struct refclockproc *pp;
1563 struct mx4200unit *up;
1572 * Print debug message to stdout
1573 * In the future, we may want to get get more creative...
1583 * Send a character string to the receiver. Checksum is appended here.
1585 #if defined(__STDC__)
1587 mx4200_send(struct peer *peer, char *fmt, ...)
1590 mx4200_send(peer, fmt, va_alist)
1594 #endif /* __STDC__ */
1596 struct refclockproc *pp;
1597 struct mx4200unit *up;
1605 #if defined(__STDC__)
1609 #endif /* __STDC__ */
1616 n = VSNPRINTF((cp, sizeof(buf) - 1, fmt, ap));
1617 ck = mx4200_cksum(cp, n);
1620 n += SNPRINTF((cp, sizeof(buf) - n - 5, "*%02X\r\n", ck));
1622 m = write(pp->io.fd, buf, (unsigned)n);
1624 msyslog(LOG_ERR, "mx4200_send: write: %m (%s)", buf);
1625 mx4200_debug(peer, "mx4200_send: %d %s\n", m, buf);
1630 int refclock_mx4200_bs;
1631 #endif /* REFCLOCK */