2 * refclock_chu - clock driver for Canadian CHU time/frequency station
8 #if defined(REFCLOCK) && defined(CLOCK_CHU)
12 #include "ntp_refclock.h"
13 #include "ntp_calendar.h"
14 #include "ntp_stdlib.h"
22 #endif /* HAVE_AUDIO */
24 #define ICOM 1 /* undefine to suppress ICOM code */
31 * Audio CHU demodulator/decoder
33 * This driver synchronizes the computer time using data encoded in
34 * radio transmissions from Canadian time/frequency station CHU in
35 * Ottawa, Ontario. Transmissions are made continuously on 3330 kHz,
36 * 7335 kHz and 14670 kHz in upper sideband, compatible AM mode. An
37 * ordinary shortwave receiver can be tuned manually to one of these
38 * frequencies or, in the case of ICOM receivers, the receiver can be
39 * tuned automatically using this program as propagation conditions
40 * change throughout the day and night.
42 * The driver receives, demodulates and decodes the radio signals when
43 * connected to the audio codec of a Sun workstation running SunOS or
44 * Solaris, and with a little help, other workstations with similar
45 * codecs or sound cards. In this implementation, only one audio driver
46 * and codec can be supported on a single machine.
48 * The driver can be compiled to use a Bell 103 compatible modem or
49 * modem chip to receive the radio signal and demodulate the data.
50 * Alternatively, the driver can be compiled to use the audio codec of
51 * the Sun workstation or another with compatible audio drivers. In the
52 * latter case, the driver implements the modem using DSP routines, so
53 * the radio can be connected directly to either the microphone on line
54 * input port. In either case, the driver decodes the data using a
55 * maximum likelihood technique which exploits the considerable degree
56 * of redundancy available to maximize accuracy and minimize errors.
58 * The CHU time broadcast includes an audio signal compatible with the
59 * Bell 103 modem standard (mark = 2225 Hz, space = 2025 Hz). It consist
60 * of nine, ten-character bursts transmitted at 300 bps and beginning
61 * each second from second 31 to second 39 of the minute. Each character
62 * consists of eight data bits plus one start bit and two stop bits to
63 * encode two hex digits. The burst data consist of five characters (ten
64 * hex digits) followed by a repeat of these characters. In format A,
65 * the characters are repeated in the same polarity; in format B, the
66 * characters are repeated in the opposite polarity.
68 * Format A bursts are sent at seconds 32 through 39 of the minute in
71 * 6dddhhmmss6dddhhmmss
73 * The first ten digits encode a frame marker (6) followed by the day
74 * (ddd), hour (hh in UTC), minute (mm) and the second (ss). Since
75 * format A bursts are sent during the third decade of seconds the tens
76 * digit of ss is always 3. The driver uses this to determine correct
77 * burst synchronization. These digits are then repeated with the same
80 * Format B bursts are sent at second 31 of the minute in hex digits
82 * xdyyyyttaaxdyyyyttaa
84 * The first ten digits encode a code (x described below) followed by
85 * the DUT1 (d in deciseconds), Gregorian year (yyyy), difference TAI -
86 * UTC (tt) and daylight time indicator (aa) peculiar to Canada. These
87 * digits are then repeated with inverted polarity.
91 * 1 Sign of DUT (0 = +)
92 * 2 Leap second warning. One second will be added.
93 * 4 Leap second warning. One second will be subtracted.
94 * 8 Even parity bit for this nibble.
96 * By design, the last stop bit of the last character in the burst
97 * coincides with 0.5 second. Since characters have 11 bits and are
98 * transmitted at 300 bps, the last stop bit of the first character
99 * coincides with 0.5 - 10 * 11/300 = 0.133 second. Depending on the
100 * UART, character interrupts can vary somewhere between the beginning
101 * of bit 9 and end of bit 11. These eccentricities can be corrected
102 * along with the radio propagation delay using fudge time 1.
106 * The timecode format used for debugging and data recording includes
107 * data helpful in diagnosing problems with the radio signal and serial
108 * connections. With debugging enabled (-d -d -d on the ntpd command
109 * line), the driver produces one line for each burst in two formats
110 * corresponding to format A and B. Following is format A:
114 * where n is the number of characters in the burst (0-11), b the burst
115 * distance (0-40), f the field alignment (-1, 0, 1), s the
116 * synchronization distance (0-16), m the burst number (2-9) and code
117 * the burst characters as received. Note that the hex digits in each
118 * character are reversed, so the burst
120 * 10 38 0 16 9 06851292930685129293
122 * is interpreted as containing 11 characters with burst distance 38,
123 * field alignment 0, synchronization distance 16 and burst number 9.
124 * The nibble-swapped timecode shows day 58, hour 21, minute 29 and
127 * When the audio driver is compiled, format A is preceded by
128 * the current gain (0-255) and relative signal level (0-9999). The
129 * receiver folume control should be set so that the gain is somewhere
130 * near the middle of the range 0-255, which results in a signal level
133 * Following is format B:
137 * where n is the number of characters in the burst (0-11), b the burst
138 * distance (0-40), s the synchronization distance (0-40) and code the
139 * burst characters as received. Note that the hex digits in each
140 * character are reversed and the last ten digits inverted, so the burst
142 * 11 40 1091891300ef6e76ecff
144 * is interpreted as containing 11 characters with burst distance 40.
145 * The nibble-swapped timecode shows DUT1 +0.1 second, year 1998 and TAI
148 * In addition to the above, the reference timecode is updated and
149 * written to the clockstats file and debug score after the last burst
150 * received in the minute. The format is
152 * qq yyyy ddd hh:mm:ss nn dd tt
154 * where qq are the error flags, as described below, yyyy is the year,
155 * ddd the day, hh:mm:ss the time of day, nn the number of format A
156 * bursts received during the previous minute, dd the decoding distance
157 * and tt the number of timestamps. The error flags are cleared after
162 * For accuracies better than the low millisceconds, fudge time1 can be
163 * set to the radio propagation delay from CHU to the receiver. This can
164 * be done conviently using the minimuf program. When the modem driver
165 * is compiled, fudge flag3 enables the ppsclock line discipline. Fudge
166 * flag4 causes the dubugging output described above to be recorded in
167 * the clockstats file.
169 * When the audio driver is compiled, fudge flag2 selects the audio
170 * input port, where 0 is the mike port (default) and 1 is the line-in
171 * port. It does not seem useful to select the compact disc player port.
172 * Fudge flag3 enables audio monitoring of the input signal. For this
173 * purpose, the speaker volume must be set before the driver is started.
175 * The audio codec code is normally compiled in the driver if the
176 * architecture supports it (HAVE_AUDIO defined), but is used only if the
177 * link /dev/chu_audio is defined and valid. The serial port
178 * code is alwasy compiled in the driver, but is used only if the autdio
179 * codec is not available and the link /dev/chu%d is defined and valid.
180 * The ICOM code is normally compiled in the driver if selected (ICOM
181 * defined), but is used only if the link /dev/icom%d is defined and
182 * valid and the mode keyword on the server configuration command
183 * specifies a nonzero mode (ICOM ID select code). The C-IV speed is
184 * 9600 bps if the high order 0x80 bit of the mode is zero and 1200 bps
185 * if one. The C-IV trace is turned on if the debug level is greater
189 * Interface definitions
191 #define SPEED232 B300 /* uart speed (300 baud) */
192 #define PRECISION (-10) /* precision assumed (about 1 ms) */
193 #define REFID "CHU" /* reference ID */
194 #define DEVICE "/dev/chu%d" /* device name and unit */
195 #define SPEED232 B300 /* UART speed (300 baud) */
197 #define DWELL 5 /* minutes before qsy */
198 #define NCHAN 3 /* number of channels */
203 * Audio demodulator definitions
205 #define SECOND 8000 /* nominal sample rate (Hz) */
206 #define BAUD 300 /* modulation rate (bps) */
207 #define OFFSET 128 /* companded sample offset */
208 #define SIZE 256 /* decompanding table size */
209 #define MAXSIG 6000. /* maximum signal level */
210 #define LIMIT 1000. /* soft limiter threshold */
211 #define AGAIN 6. /* baseband gain */
212 #define LAG 10 /* discriminator lag */
213 #define DEVICE_AUDIO "/dev/chu_audio" /* device name */
214 #define DESCRIPTION "CHU Audio/Modem Receiver" /* WRU */
216 #define DESCRIPTION "CHU Modem Receiver" /* WRU */
217 #endif /* HAVE_AUDIO */
220 * Decoder definitions
222 #define CHAR (11. / 300.) /* character time (s) */
223 #define FUDGE .185 /* offset to first stop bit (s) */
224 #define BURST 11 /* max characters per burst */
225 #define MINCHAR 9 /* min characters per burst */
226 #define MINDIST 28 /* min burst distance (of 40) */
227 #define MINSYNC 8 /* min sync distance (of 16) */
228 #define MINSTAMP 20 /* min timestamps (of 60) */
229 #define PANIC (4 * 1440) /* panic restart */
232 * Hex extension codes (>= 16)
234 #define HEX_MISS 16 /* miss */
235 #define HEX_SOFT 17 /* soft error */
236 #define HEX_HARD 18 /* hard error */
239 * Status bits (status)
241 #define RUNT 0x0001 /* runt burst */
242 #define NOISE 0x0002 /* noise burst */
243 #define BFRAME 0x0004 /* invalid format B frame sync */
244 #define BFORMAT 0x0008 /* invalid format B data */
245 #define AFRAME 0x0010 /* invalid format A frame sync */
246 #define AFORMAT 0x0020 /* invalid format A data */
247 #define DECODE 0x0040 /* invalid data decode */
248 #define STAMP 0x0080 /* too few timestamps */
249 #define INYEAR 0x0100 /* valid B frame */
250 #define INSYNC 0x0200 /* clock synchronized */
253 * Alarm status bits (alarm)
255 * These alarms are set at the end of a minute in which at least one
256 * burst was received. SYNERR is raised if the AFRAME or BFRAME status
257 * bits are set during the minute, FMTERR is raised if the AFORMAT or
258 * BFORMAT status bits are set, DECERR is raised if the DECODE status
259 * bit is set and TSPERR is raised if the STAMP status bit is set.
261 #define SYNERR 0x01 /* frame sync error */
262 #define FMTERR 0x02 /* data format error */
263 #define DECERR 0x04 /* data decoding error */
264 #define TSPERR 0x08 /* insufficient data */
268 double shift[12]; /* mark register */
269 double es_max, es_min; /* max/min envelope signals */
270 double dist; /* sample distance */
271 int uart; /* decoded character */
273 #endif /* HAVE_AUDIO */
276 * CHU unit control structure
279 u_char decode[20][16]; /* maximum likelihood decoding matrix */
280 l_fp cstamp[BURST]; /* character timestamps */
281 l_fp tstamp[MAXSTAGE]; /* timestamp samples */
282 l_fp timestamp; /* current buffer timestamp */
283 l_fp laststamp; /* last buffer timestamp */
284 l_fp charstamp; /* character time as a l_fp */
285 int errflg; /* error flags */
286 int status; /* status bits */
287 int bufptr; /* buffer index pointer */
288 char ident[10]; /* transmitter frequency */
290 int fd_icom; /* ICOM file descriptor */
291 int chan; /* frequency identifier */
292 int dwell; /* dwell minutes at current frequency */
296 * Character burst variables
298 int cbuf[BURST]; /* character buffer */
299 int ntstamp; /* number of timestamp samples */
300 int ndx; /* buffer start index */
301 int prevsec; /* previous burst second */
302 int burdist; /* burst distance */
303 int mindist; /* minimum distance */
304 int syndist; /* sync distance */
305 int burstcnt; /* format A bursts this minute */
310 int leap; /* leap/dut code */
311 int dut; /* UTC1 correction */
312 int tai; /* TAI - UTC correction */
313 int dst; /* Canadian DST code */
317 * Audio codec variables
319 int fd_audio; /* audio port file descriptor */
320 double comp[SIZE]; /* decompanding table */
321 int port; /* codec port */
322 int gain; /* codec gain */
323 int bufcnt; /* samples in buffer */
324 int clipcnt; /* sample clip count */
325 int seccnt; /* second interval counter */
330 l_fp tick; /* audio sample increment */
331 double bpf[9]; /* IIR bandpass filter */
332 double disc[LAG]; /* discriminator shift register */
333 double lpf[27]; /* FIR lowpass filter */
334 double monitor; /* audio monitor */
335 double maxsignal; /* signal level */
336 int discptr; /* discriminator pointer */
339 * Maximum likelihood UART variables
341 double baud; /* baud interval */
342 struct surv surv[8]; /* UART survivor structures */
343 int decptr; /* decode pointer */
344 int dbrk; /* holdoff counter */
345 #endif /* HAVE_AUDIO */
349 * Function prototypes
351 static int chu_start P((int, struct peer *));
352 static void chu_shutdown P((int, struct peer *));
353 static void chu_receive P((struct recvbuf *));
354 static void chu_poll P((int, struct peer *));
357 * More function prototypes
359 static void chu_decode P((struct peer *, int));
360 static void chu_burst P((struct peer *));
361 static void chu_clear P((struct peer *));
362 static void chu_a P((struct peer *, int));
363 static void chu_b P((struct peer *, int));
364 static int chu_dist P((int, int));
365 static int chu_major P((struct peer *));
367 static void chu_uart P((struct surv *, double));
368 static void chu_rf P((struct peer *, double));
369 static void chu_gain P((struct peer *));
370 static void chu_audio_receive P((struct recvbuf *rbufp));
371 #endif /* HAVE_AUDIO */
372 static void chu_serial_receive P((struct recvbuf *rbufp));
377 static char hexchar[] = "0123456789abcdef_-=";
379 static double qsy[NCHAN] = {3.33, 7.335, 14.67}; /* frequencies (MHz) */
385 struct refclock refclock_chu = {
386 chu_start, /* start up driver */
387 chu_shutdown, /* shut down driver */
388 chu_poll, /* transmit poll message */
389 noentry, /* not used (old chu_control) */
390 noentry, /* initialize driver (not used) */
391 noentry, /* not used (old chu_buginfo) */
392 NOFLAGS /* not used */
397 * chu_start - open the devices and initialize data for processing
401 int unit, /* instance number (not used) */
402 struct peer *peer /* peer structure pointer */
406 struct refclockproc *pp;
407 char device[20]; /* device name */
408 int fd; /* file descriptor */
410 char tbuf[80]; /* trace buffer */
414 int fd_audio; /* audio port file descriptor */
416 double step; /* codec adjustment */
421 fd_audio = audio_init(DEVICE_AUDIO);
423 if (fd_audio > 0 && debug)
428 * Open serial port in raw mode.
433 sprintf(device, DEVICE, unit);
434 fd = refclock_open(device, SPEED232, LDISC_RAW);
436 #else /* HAVE_AUDIO */
439 * Open serial port in raw mode.
441 sprintf(device, DEVICE, unit);
442 fd = refclock_open(device, SPEED232, LDISC_RAW);
443 #endif /* HAVE_AUDIO */
448 * Allocate and initialize unit structure
450 if (!(up = (struct chuunit *)
451 emalloc(sizeof(struct chuunit)))) {
455 memset((char *)up, 0, sizeof(struct chuunit));
457 pp->unitptr = (caddr_t)up;
458 pp->io.clock_recv = chu_receive;
459 pp->io.srcclock = (caddr_t)peer;
462 if (!io_addclock(&pp->io)) {
469 * Initialize miscellaneous variables
471 peer->precision = PRECISION;
472 pp->clockdesc = DESCRIPTION;
473 memcpy((char *)&pp->refid, REFID, 4);
474 DTOLFP(CHAR, &up->charstamp);
478 * The companded samples are encoded sign-magnitude. The table
479 * contains all the 256 values in the interest of speed. We do
480 * this even if the audio codec is not available. C'est la lazy.
482 up->fd_audio = fd_audio;
484 up->comp[0] = up->comp[OFFSET] = 0.;
485 up->comp[1] = 1; up->comp[OFFSET + 1] = -1.;
486 up->comp[2] = 3; up->comp[OFFSET + 2] = -3.;
488 for (i = 3; i < OFFSET; i++) {
489 up->comp[i] = up->comp[i - 1] + step;
490 up->comp[OFFSET + i] = -up->comp[i];
494 DTOLFP(1. / SECOND, &up->tick);
495 #endif /* HAVE_AUDIO */
496 strcpy(up->ident, "X");
503 if (peer->ttlmax > 0) {
504 if (peer->ttlmax & 0x80)
505 up->fd_icom = icom_init("/dev/icom", B1200,
508 up->fd_icom = icom_init("/dev/icom", B9600,
511 if (up->fd_icom > 0) {
512 if (icom_freq(up->fd_icom, peer->ttlmax & 0x7f,
513 qsy[up->chan]) < 0) {
514 NLOG(NLOG_SYNCEVENT | NLOG_SYSEVENT)
516 "ICOM bus error; autotune disabled");
517 up->errflg = CEVNT_FAULT;
521 sprintf(up->ident, "%.1f", qsy[up->chan]);
522 sprintf(tbuf, "chu: QSY to %s MHz", up->ident);
523 record_clock_stats(&peer->srcadr, tbuf);
526 printf("%s\n", tbuf);
536 * chu_shutdown - shut down the clock
540 int unit, /* instance number (not used) */
541 struct peer *peer /* peer structure pointer */
545 struct refclockproc *pp;
548 up = (struct chuunit *)pp->unitptr;
551 io_closeclock(&pp->io);
558 * chu_receive - receive data from the audio or serial device
562 struct recvbuf *rbufp /* receive buffer structure pointer */
567 struct refclockproc *pp;
570 peer = (struct peer *)rbufp->recv_srcclock;
572 up = (struct chuunit *)pp->unitptr;
575 * If the audio codec is warmed up, the buffer contains codec
576 * samples which need to be demodulated and decoded into CHU
577 * characters using the software UART. Otherwise, the buffer
578 * contains CHU characters from the serial port, so the software
579 * UART is bypassed. In this case the CPU will probably run a
580 * few degrees cooler.
582 if (up->fd_audio > 0)
583 chu_audio_receive(rbufp);
585 chu_serial_receive(rbufp);
587 chu_serial_receive(rbufp);
588 #endif /* HAVE_AUDIO */
594 * chu_audio_receive - receive data from the audio device
598 struct recvbuf *rbufp /* receive buffer structure pointer */
602 struct refclockproc *pp;
605 double sample; /* codec sample */
606 u_char *dpt; /* buffer pointer */
607 l_fp ltemp; /* l_fp temp */
608 int isneg; /* parity flag */
612 peer = (struct peer *)rbufp->recv_srcclock;
614 up = (struct chuunit *)pp->unitptr;
617 * Main loop - read until there ain't no more. Note codec
618 * samples are bit-inverted.
620 up->timestamp = rbufp->recv_time;
621 up->bufcnt = rbufp->recv_length;
622 DTOLFP(up->bufcnt * 1. / SECOND, <emp);
623 L_SUB(&up->timestamp, <emp);
624 dpt = (u_char *)&rbufp->recv_space;
625 for (up->bufptr = 0; up->bufptr < up->bufcnt; up->bufptr++) {
626 sample = up->comp[~*dpt & 0xff];
629 * Clip noise spikes greater than MAXSIG. If no clips,
630 * increase the gain a tad; if the clips are too high,
633 if (sample > MAXSIG) {
636 } else if (sample < -MAXSIG) {
640 up->seccnt = (up->seccnt + 1) % SECOND;
641 if (up->seccnt == 0) {
642 if (pp->sloppyclockflag & CLK_FLAG2)
648 chu_rf(peer, sample);
651 * During development, it is handy to have an audio
652 * monitor that can be switched to various signals. This
653 * code converts the linear signal left in up->monitor
654 * to codec format. If we can get the grass out of this
655 * thing and improve modem performance, this expensive
656 * code will be permanently nixed.
667 if (dtemp > up->comp[i])
669 else if (dtemp < up->comp[i])
676 *dpt = ~(i + OFFSET);
680 L_ADD(&up->timestamp, &up->tick);
684 * Squawk to the monitor speaker if enabled.
686 if (pp->sloppyclockflag & CLK_FLAG3)
687 if (write(pp->io.fd, (u_char *)&rbufp->recv_space,
688 (u_int)up->bufcnt) < 0)
694 * chu_rf - filter and demodulate the FSK signal
696 * This routine implements a 300-baud Bell 103 modem with mark 2225 Hz
697 * and space 2025 Hz. It uses a bandpass filter followed by a soft
698 * limiter, FM discriminator and lowpass filter. A maximum likelihood
699 * decoder samples the baseband signal at eight times the baud rate and
700 * detects the start bit of each character.
702 * The filters are built for speed, which explains the rather clumsy
703 * code. Hopefully, the compiler will efficiently implement the move-
704 * and-muiltiply-and-add operations.
708 struct peer *peer, /* peer structure pointer */
709 double sample /* analog sample */
712 struct refclockproc *pp;
719 double signal; /* bandpass signal */
720 double limit; /* limiter signal */
721 double disc; /* discriminator signal */
722 double lpf; /* lowpass signal */
723 double span; /* UART signal span */
724 double dist; /* UART signal distance */
728 up = (struct chuunit *)pp->unitptr;
731 * Bandpass filter. 4th-order elliptic, 500-Hz bandpass centered
732 * at 2125 Hz. Passband ripple 0.3 dB, stopband ripple 50 dB.
734 signal = (up->bpf[8] = up->bpf[7]) * 5.844676e-01;
735 signal += (up->bpf[7] = up->bpf[6]) * 4.884860e-01;
736 signal += (up->bpf[6] = up->bpf[5]) * 2.704384e+00;
737 signal += (up->bpf[5] = up->bpf[4]) * 1.645032e+00;
738 signal += (up->bpf[4] = up->bpf[3]) * 4.644557e+00;
739 signal += (up->bpf[3] = up->bpf[2]) * 1.879165e+00;
740 signal += (up->bpf[2] = up->bpf[1]) * 3.522634e+00;
741 signal += (up->bpf[1] = up->bpf[0]) * 7.315738e-01;
742 up->bpf[0] = sample - signal;
743 signal = up->bpf[0] * 6.176213e-03
744 + up->bpf[1] * 3.156599e-03
745 + up->bpf[2] * 7.567487e-03
746 + up->bpf[3] * 4.344580e-03
747 + up->bpf[4] * 1.190128e-02
748 + up->bpf[5] * 4.344580e-03
749 + up->bpf[6] * 7.567487e-03
750 + up->bpf[7] * 3.156599e-03
751 + up->bpf[8] * 6.176213e-03;
753 up->monitor = signal / 4.; /* note monitor after filter */
756 * Soft limiter/discriminator. The 11-sample discriminator lag
757 * interval corresponds to three cycles of 2125 Hz, which
758 * requires the sample frequency to be 2125 * 11 / 3 = 7791.7
759 * Hz. The discriminator output varies +-0.5 interval for input
760 * frequency 2025-2225 Hz. However, we don't get to sample at
761 * this frequency, so the discriminator output is biased. Life
767 else if (limit < -LIMIT)
769 disc = up->disc[up->discptr] * -limit;
770 up->disc[up->discptr] = limit;
771 up->discptr = (up->discptr + 1 ) % LAG;
778 * Lowpass filter. Raised cosine, Ts = 1 / 300, beta = 0.1.
780 lpf = (up->lpf[26] = up->lpf[25]) * 2.538771e-02;
781 lpf += (up->lpf[25] = up->lpf[24]) * 1.084671e-01;
782 lpf += (up->lpf[24] = up->lpf[23]) * 2.003159e-01;
783 lpf += (up->lpf[23] = up->lpf[22]) * 2.985303e-01;
784 lpf += (up->lpf[22] = up->lpf[21]) * 4.003697e-01;
785 lpf += (up->lpf[21] = up->lpf[20]) * 5.028552e-01;
786 lpf += (up->lpf[20] = up->lpf[19]) * 6.028795e-01;
787 lpf += (up->lpf[19] = up->lpf[18]) * 6.973249e-01;
788 lpf += (up->lpf[18] = up->lpf[17]) * 7.831828e-01;
789 lpf += (up->lpf[17] = up->lpf[16]) * 8.576717e-01;
790 lpf += (up->lpf[16] = up->lpf[15]) * 9.183463e-01;
791 lpf += (up->lpf[15] = up->lpf[14]) * 9.631951e-01;
792 lpf += (up->lpf[14] = up->lpf[13]) * 9.907208e-01;
793 lpf += (up->lpf[13] = up->lpf[12]) * 1.000000e+00;
794 lpf += (up->lpf[12] = up->lpf[11]) * 9.907208e-01;
795 lpf += (up->lpf[11] = up->lpf[10]) * 9.631951e-01;
796 lpf += (up->lpf[10] = up->lpf[9]) * 9.183463e-01;
797 lpf += (up->lpf[9] = up->lpf[8]) * 8.576717e-01;
798 lpf += (up->lpf[8] = up->lpf[7]) * 7.831828e-01;
799 lpf += (up->lpf[7] = up->lpf[6]) * 6.973249e-01;
800 lpf += (up->lpf[6] = up->lpf[5]) * 6.028795e-01;
801 lpf += (up->lpf[5] = up->lpf[4]) * 5.028552e-01;
802 lpf += (up->lpf[4] = up->lpf[3]) * 4.003697e-01;
803 lpf += (up->lpf[3] = up->lpf[2]) * 2.985303e-01;
804 lpf += (up->lpf[2] = up->lpf[1]) * 2.003159e-01;
805 lpf += (up->lpf[1] = up->lpf[0]) * 1.084671e-01;
806 lpf += up->lpf[0] = disc * 2.538771e-02;
809 * Maximum likelihood decoder. The UART updates each of the
810 * eight survivors and determines the span, slice level and
811 * tentative decoded character. Valid 11-bit characters are
812 * framed so that bit 1 and bit 11 (stop bits) are mark and bit
813 * 2 (start bit) is space. When a valid character is found, the
814 * survivor with maximum distance determines the final decoded
817 up->baud += 1. / SECOND;
818 if (up->baud > 1. / (BAUD * 8.)) {
819 up->baud -= 1. / (BAUD * 8.);
820 sp = &up->surv[up->decptr];
821 span = sp->es_max - sp->es_min;
822 up->maxsignal += (span - up->maxsignal) / 80.;
825 } else if ((sp->uart & 0x403) == 0x401 && span > 1000.)
829 for (i = 0; i < 8; i++) {
830 if (up->surv[i].dist > dist) {
831 dist = up->surv[i].dist;
835 chu_decode(peer, (up->surv[j].uart >> 2) &
839 up->decptr = (up->decptr + 1) % 8;
840 chu_uart(sp, -lpf * AGAIN);
846 * chu_uart - maximum likelihood UART
848 * This routine updates a shift register holding the last 11 envelope
849 * samples. It then computes the slice level and span over these samples
850 * and determines the tentative data bits and distance. The calling
851 * program selects over the last eight survivors the one with maximum
852 * distance to determine the decoded character.
856 struct surv *sp, /* survivor structure pointer */
857 double sample /* baseband signal */
860 double es_max, es_min; /* max/min envelope */
861 double slice; /* slice level */
862 double dist; /* distance */
867 * Save the sample and shift right. At the same time, measure
868 * the maximum and minimum over all eleven samples.
872 sp->shift[0] = sample;
873 for (i = 11; i > 0; i--) {
874 sp->shift[i] = sp->shift[i - 1];
875 if (sp->shift[i] > es_max)
876 es_max = sp->shift[i];
877 if (sp->shift[i] < es_min)
878 es_min = sp->shift[i];
882 * Determine the slice level midway beteen the maximum and
883 * minimum and the span as the maximum less the minimum. Compute
884 * the distance on the assumption the first and last bits must
885 * be mark, the second space and the rest either mark or space.
887 slice = (es_max + es_min) / 2.;
890 for (i = 1; i < 12; i++) {
892 dtemp = sp->shift[i];
895 if (i == 1 || i == 11) {
896 dist += dtemp - es_min;
897 } else if (i == 10) {
898 dist += es_max - dtemp;
901 dist += dtemp - es_min;
903 dist += es_max - dtemp;
908 sp->dist = dist / (11 * (es_max - es_min));
910 #endif /* HAVE_AUDIO */
914 * chu_serial_receive - receive data from the serial device
918 struct recvbuf *rbufp /* receive buffer structure pointer */
922 struct refclockproc *pp;
925 u_char *dpt; /* receive buffer pointer */
927 peer = (struct peer *)rbufp->recv_srcclock;
929 up = (struct chuunit *)pp->unitptr;
932 * Initialize pointers and read the timecode and timestamp.
934 up->timestamp = rbufp->recv_time;
935 dpt = (u_char *)&rbufp->recv_space;
936 chu_decode(peer, *dpt);
941 * chu_decode - decode the character data
945 struct peer *peer, /* peer structure pointer */
946 int hexhex /* data character */
949 struct refclockproc *pp;
952 l_fp tstmp; /* timestamp temp */
956 up = (struct chuunit *)pp->unitptr;
959 * If the interval since the last character is greater than the
960 * longest burst, process the last burst and start a new one. If
961 * the interval is less than this but greater than two
962 * characters, consider this a noise burst and reject it.
964 tstmp = up->timestamp;
965 if (L_ISZERO(&up->laststamp))
966 up->laststamp = up->timestamp;
967 L_SUB(&tstmp, &up->laststamp);
968 up->laststamp = up->timestamp;
969 LFPTOD(&tstmp, dtemp);
970 if (dtemp > BURST * CHAR) {
973 } else if (dtemp > 2.5 * CHAR) {
978 * Append the character to the current burst and append the
979 * timestamp to the timestamp list.
981 if (up->ndx < BURST) {
982 up->cbuf[up->ndx] = hexhex & 0xff;
983 up->cstamp[up->ndx] = up->timestamp;
991 * chu_burst - search for valid burst format
999 struct refclockproc *pp;
1004 up = (struct chuunit *)pp->unitptr;
1007 * Correlate a block of five characters with the next block of
1008 * five characters. The burst distance is defined as the number
1009 * of bits that match in the two blocks for format A and that
1010 * match the inverse for format B.
1012 if (up->ndx < MINCHAR) {
1017 for (i = 0; i < 5 && i < up->ndx - 5; i++)
1018 up->burdist += chu_dist(up->cbuf[i], up->cbuf[i + 5]);
1021 * If the burst distance is at least MINDIST, this must be a
1022 * format A burst; if the value is not greater than -MINDIST, it
1023 * must be a format B burst. If the B burst is perfect, we
1024 * believe it; otherwise, it is a noise burst and of no use to
1027 if (up->burdist >= MINDIST) {
1028 chu_a(peer, up->ndx);
1029 } else if (up->burdist <= -MINDIST) {
1030 chu_b(peer, up->ndx);
1032 up->status |= NOISE;
1037 * If this is a valid burst, wait a guard time of ten seconds to
1038 * allow for more bursts, then arm the poll update routine to
1039 * process the minute. Don't do this if this is called from the
1040 * timer interrupt routine.
1042 if (peer->outdate != current_time)
1043 peer->nextdate = current_time + 10;
1048 * chu_b - decode format B burst
1056 struct refclockproc *pp;
1059 u_char code[11]; /* decoded timecode */
1060 char tbuf[80]; /* trace buffer */
1061 l_fp offset; /* timestamp offset */
1065 up = (struct chuunit *)pp->unitptr;
1068 * In a format B burst, a character is considered valid only if
1069 * the first occurrence matches the last occurrence. The burst
1070 * is considered valid only if all characters are valid; that
1071 * is, only if the distance is 40.
1073 sprintf(tbuf, "chuB %04x %2d %2d ", up->status, nchar,
1075 for (i = 0; i < nchar; i++)
1076 sprintf(&tbuf[strlen(tbuf)], "%02x",
1078 if (pp->sloppyclockflag & CLK_FLAG4)
1079 record_clock_stats(&peer->srcadr, tbuf);
1082 printf("%s\n", tbuf);
1084 if (up->burdist > -40) {
1085 up->status |= BFRAME;
1088 up->status |= INYEAR;
1091 * Convert the burst data to internal format. If this succeeds,
1092 * save the timestamps for later.
1094 for (i = 0; i < 5; i++) {
1095 code[2 * i] = hexchar[up->cbuf[i] & 0xf];
1096 code[2 * i + 1] = hexchar[(up->cbuf[i] >>
1099 if (sscanf((char *)code, "%1x%1d%4d%2d%2x", &up->leap, &up->dut,
1100 &pp->year, &up->tai, &up->dst) != 5) {
1101 up->status |= BFORMAT;
1108 for (i = 0; i < nchar && i < 10; i++) {
1109 up->tstamp[up->ntstamp] = up->cstamp[i];
1110 L_SUB(&up->tstamp[up->ntstamp], &offset);
1111 L_ADD(&offset, &up->charstamp);
1112 if (up->ntstamp < MAXSTAGE)
1119 * chu_a - decode format A burst
1127 struct refclockproc *pp;
1130 char tbuf[80]; /* trace buffer */
1131 l_fp offset; /* timestamp offset */
1132 int val; /* distance */
1137 up = (struct chuunit *)pp->unitptr;
1140 * Determine correct burst phase. There are three cases
1141 * corresponding to in-phase, one character early or one
1142 * character late. These cases are distinguished by the position
1143 * of the framing digits x6 at positions 0 and 5 and x3 at
1144 * positions 4 and 9. The correct phase is when the distance
1145 * relative to the framing digits is maximum. The burst is valid
1146 * only if the maximum distance is at least MINSYNC.
1148 up->syndist = k = 0;
1150 for (i = -1; i < 2; i++) {
1151 temp = up->cbuf[i + 4] & 0xf;
1153 temp |= (up->cbuf[i] & 0xf) << 4;
1154 val = chu_dist(temp, 0x63);
1155 temp = (up->cbuf[i + 5] & 0xf) << 4;
1157 temp |= up->cbuf[i + 9] & 0xf;
1158 val += chu_dist(temp, 0x63);
1159 if (val > up->syndist) {
1164 temp = (up->cbuf[k + 4] >> 4) & 0xf;
1165 if (temp > 9 || k + 9 >= nchar || temp != ((up->cbuf[k + 9] >>
1170 sprintf(tbuf, "chuA %04x %4.0f %2d %2d %2d %2d %1d ",
1171 up->status, up->maxsignal, nchar, up->burdist, k,
1174 sprintf(tbuf, "chuA %04x %2d %2d %2d %2d %1d ",
1175 up->status, nchar, up->burdist, k, up->syndist,
1179 sprintf(tbuf, "chuA %04x %2d %2d %2d %2d %1d ", up->status,
1180 nchar, up->burdist, k, up->syndist, temp);
1181 #endif /* HAVE_AUDIO */
1182 for (i = 0; i < nchar; i++)
1183 sprintf(&tbuf[strlen(tbuf)], "%02x",
1185 if (pp->sloppyclockflag & CLK_FLAG4)
1186 record_clock_stats(&peer->srcadr, tbuf);
1189 printf("%s\n", tbuf);
1191 if (up->syndist < MINSYNC) {
1192 up->status |= AFRAME;
1197 * A valid burst requires the first seconds number to match the
1198 * last seconds number. If so, the burst timestamps are
1199 * corrected to the current minute and saved for later
1200 * processing. In addition, the seconds decode is advanced from
1201 * the previous burst to the current one.
1204 offset.l_ui = 30 + temp;
1208 offset = up->charstamp;
1211 for (; i < nchar && i < k + 10; i++) {
1212 up->tstamp[up->ntstamp] = up->cstamp[i];
1213 L_SUB(&up->tstamp[up->ntstamp], &offset);
1214 L_ADD(&offset, &up->charstamp);
1215 if (up->ntstamp < MAXSTAGE)
1218 while (temp > up->prevsec) {
1219 for (j = 15; j > 0; j--) {
1220 up->decode[9][j] = up->decode[9][j - 1];
1222 up->decode[19][j - 1];
1224 up->decode[9][j] = up->decode[19][j] = 0;
1229 for (j = 0; j < nchar; j++) {
1230 if (i < 0 || i > 19) {
1234 up->decode[i][up->cbuf[j] & 0xf]++;
1236 up->decode[i][(up->cbuf[j] >> 4) & 0xf]++;
1244 * chu_poll - called by the transmit procedure
1249 struct peer *peer /* peer structure pointer */
1252 struct refclockproc *pp;
1254 char synchar, qual, leapchar;
1258 char tbuf[80]; /* trace buffer */
1261 up = (struct chuunit *)pp->unitptr;
1262 if (pp->coderecv == pp->codeproc)
1263 up->errflg = CEVNT_TIMEOUT;
1266 minset = ((current_time - peer->update) + 30) / 60;
1267 if (up->status & INSYNC) {
1275 * Process the last burst, if still in the burst buffer.
1276 * Don't mess with anything if nothing has been heard.
1280 if (up->burstcnt > 2) {
1282 } else if (up->dwell < DWELL) {
1284 } else if (up->fd_icom > 0) {
1286 up->chan = (up->chan + 1) % NCHAN;
1287 icom_freq(up->fd_icom, peer->ttlmax & 0x7f, qsy[up->chan]);
1288 sprintf(up->ident, "%.3f", qsy[up->chan]);
1289 sprintf(tbuf, "chu: QSY to %s MHz", up->ident);
1290 record_clock_stats(&peer->srcadr, tbuf);
1293 printf("%s\n", tbuf);
1297 if (up->burstcnt == 0)
1299 temp = chu_major(peer);
1300 if (up->status & INYEAR)
1301 up->status |= INSYNC;
1303 if (up->status & (BFRAME | AFRAME))
1305 if (up->status & (BFORMAT | AFORMAT))
1307 if (up->status & DECODE)
1309 if (up->status & STAMP)
1311 synchar = leapchar = ' ';
1312 if (!(up->status & INSYNC)) {
1313 pp->leap = LEAP_NOTINSYNC;
1315 } else if (up->leap & 0x2) {
1316 pp->leap = LEAP_ADDSECOND;
1319 pp->leap = LEAP_NOWARNING;
1323 sprintf(pp->a_lastcode,
1324 "%c%1X %4d %3d %02d:%02d:%02d.000 %c%x %+d %d %d %s %d %d %d %d",
1325 synchar, qual, pp->year, pp->day, pp->hour,
1326 pp->minute, pp->second, leapchar, up->dst, up->dut,
1327 minset, up->gain, up->ident, up->tai, up->burstcnt,
1328 up->mindist, up->ntstamp);
1330 sprintf(pp->a_lastcode,
1331 "%c%1X %4d %3d %02d:%02d:%02d.000 %c%x %+d %d %s %d %d %d %d",
1332 synchar, qual, pp->year, pp->day, pp->hour,
1333 pp->minute, pp->second, leapchar, up->dst, up->dut,
1334 minset, up->ident, up->tai, up->burstcnt,
1335 up->mindist, up->ntstamp);
1337 sprintf(pp->a_lastcode,
1338 "%c%1X %4d %3d %02d:%02d:%02d.000 %c%x %+d %d %s %d %d %d %d",
1339 synchar, qual, pp->year, pp->day, pp->hour, pp->minute,
1340 pp->second, leapchar, up->dst, up->dut, minset,
1341 up->ident, up->tai, up->burstcnt, up->mindist, up->ntstamp);
1342 #endif /* HAVE_AUDIO */
1343 pp->lencode = strlen(pp->a_lastcode);
1346 * If timestamps have been stuffed, the timecode is ipso fatso
1347 * correct and can be selected to discipline the clock.
1350 record_clock_stats(&peer->srcadr, pp->a_lastcode);
1351 refclock_receive(peer);
1352 } else if (pp->sloppyclockflag & CLK_FLAG4) {
1353 record_clock_stats(&peer->srcadr, pp->a_lastcode);
1357 printf("chu: timecode %d %s\n", pp->lencode,
1362 refclock_report(peer, up->errflg);
1368 * chu_major - majority decoder
1372 struct peer *peer /* peer structure pointer */
1375 struct refclockproc *pp;
1378 u_char code[11]; /* decoded timecode */
1379 l_fp toffset, offset; /* l_fp temps */
1380 int val1, val2; /* maximum distance */
1381 int synchar; /* stray cat */
1387 up = (struct chuunit *)pp->unitptr;
1390 * Majority decoder. Each burst encodes two replications at each
1391 * digit position in the timecode. Each row of the decoding
1392 * matrix encodes the number of occurences of each digit found
1393 * at the corresponding position. The maximum over all
1394 * occurences at each position is the distance for this position
1395 * and the corresponding digit is the maximumn likelihood
1396 * candidate. If the distance is zero, assume a miss '_'; if the
1397 * distance is not more than half the total number of
1398 * occurences, assume a soft error '-'; if two different digits
1399 * with the same distance are found, assume a hard error '='.
1400 * These will later cause a format error when the timecode is
1401 * interpreted. The decoding distance is defined as the minimum
1402 * distance over the first nine digits. The tenth digit varies
1403 * over the seconds, so we don't count it.
1406 for (i = 0; i < 9; i++) {
1409 for (j = 0; j < 16; j++) {
1410 temp = up->decode[i][j] + up->decode[i + 10][j];
1419 else if (val1 == val2)
1421 else if (val1 <= up->burstcnt)
1425 if (val1 < up->mindist)
1427 code[i] = hexchar[code[i]];
1432 * A valid timecode requires at least three bursts and a
1433 * decoding distance greater than half the total number of
1434 * occurences. A valid timecode also requires at least 20 valid
1437 if (up->burstcnt < 3 || up->mindist <= up->burstcnt)
1438 up->status |= DECODE;
1439 if (up->ntstamp < MINSTAMP)
1440 up->status |= STAMP;
1443 * Compute the timecode timestamp from the days, hours and
1444 * minutes of the timecode. Use clocktime() for the aggregate
1445 * minutes and the minute offset computed from the burst
1446 * seconds. Note that this code relies on the filesystem time
1447 * for the years and does not use the years of the timecode.
1449 if (sscanf((char *)code, "%1x%3d%2d%2d", &synchar, &pp->day,
1450 &pp->hour, &pp->minute) != 4) {
1451 up->status |= AFORMAT;
1454 if (up->status & (DECODE | STAMP)) {
1455 up->errflg = CEVNT_BADREPLY;
1459 if (!clocktime(pp->day, pp->hour, pp->minute, 0, GMT,
1460 up->tstamp[0].l_ui, &pp->yearstart, &offset.l_ui)) {
1461 up->errflg = CEVNT_BADTIME;
1464 pp->lastref = offset;
1465 for (i = 0; i < up->ntstamp; i++) {
1467 L_SUB(&toffset, &up->tstamp[i]);
1468 LFPTOD(&toffset, dtemp);
1469 SAMPLE(dtemp + FUDGE + pp->fudgetime1);
1476 * chu_clear - clear decoding matrix
1480 struct peer *peer /* peer structure pointer */
1483 struct refclockproc *pp;
1488 up = (struct chuunit *)pp->unitptr;
1491 * Clear stuff for the minute.
1493 up->ndx = up->prevsec = 0;
1494 up->burstcnt = up->mindist = up->ntstamp = 0;
1495 up->status &= INSYNC | INYEAR;
1497 for (i = 0; i < 20; i++) {
1498 for (j = 0; j < 16; j++)
1499 up->decode[i][j] = 0;
1505 * chu_dist - determine the distance of two octet arguments
1509 int x, /* an octet of bits */
1510 int y /* another octet of bits */
1513 int val; /* bit count */
1518 * The distance is determined as the weight of the exclusive OR
1519 * of the two arguments. The weight is determined by the number
1520 * of one bits in the result. Each one bit increases the weight,
1521 * while each zero bit decreases it.
1525 for (i = 0; i < 8; i++) {
1526 if ((temp & 0x1) == 0)
1538 * chu_gain - adjust codec gain
1540 * This routine is called once each second. If the signal envelope
1541 * amplitude is too low, the codec gain is bumped up by four units; if
1542 * too high, it is bumped down. The decoder is relatively insensitive to
1543 * amplitude, so this crudity works just fine. The input port is set and
1544 * the error flag is cleared, mostly to be ornery.
1548 struct peer *peer /* peer structure pointer */
1551 struct refclockproc *pp;
1555 up = (struct chuunit *)pp->unitptr;
1558 * Apparently, the codec uses only the high order bits of the
1559 * gain control field. Thus, it may take awhile for changes to
1560 * wiggle the hardware bits.
1562 if (up->clipcnt == 0) {
1566 } else if (up->clipcnt > SECOND / 100) {
1571 audio_gain(up->gain, up->port);
1574 #endif /* HAVE_AUDIO */
1578 int refclock_chu_bs;
1579 #endif /* REFCLOCK */