2 * refclock_chu - clock driver for Canadian radio CHU receivers
9 #if defined(REFCLOCK) && defined(CLOCK_CHU)
11 /* #define AUDIO_CHUa */
20 #ifdef HAVE_SYS_AUDIOIO_H
21 #include <sys/audioio.h>
22 #endif /* HAVE_SYS_AUDIOIO_H */
23 #ifdef HAVE_SUN_AUDIOIO_H
24 #include <sun/audioio.h>
25 #endif /* HAVE_SUN_AUDIOIO_H */
26 #endif /* AUDIO_CHU */
30 #include "ntp_refclock.h"
31 #include "ntp_calendar.h"
32 #include "ntp_stdlib.h"
35 * Clock driver for Canadian radio CHU receivers
37 * This driver synchronizes the computer time using data encoded in
38 * radio transmissions from Canadian time/frequency station CHU in
39 * Ottawa, Ontario. Transmissions are made continuously on 3330 kHz,
40 * 7335 kHz and 14670 kHz in upper sideband, compatible AM mode. An
41 * ordinary shortwave receiver can be tuned manually to one of these
42 * frequencies or, in the case of ICOM receivers, the receiver can be
43 * tuned automatically using the minimuf and icom programs as
44 * propagation conditions change throughout the day and night.
46 * The driver can be compiled to use a Bell 103 compatible modem or
47 * modem chip to receive the radio signal and demodulate the data.
48 * Alternatively, the driver can be compiled to use the audio codec of
49 * the Sun workstation or another with compatible audio drivers. In the
50 * latter case, the driver implements the modem using DSP routines, so
51 * the radio can be connected directly to either the microphone on line
52 * input port. In either case, the driver decodes the data using a
53 * maximum likelihood technique which exploits the considerable degree
54 * of redundancy available to maximize accuracy and minimize errors.
56 * The CHU time broadcast includes an audio signal compatible with the
57 * Bell 103 modem standard (mark = 2225 Hz, space = 2025 Hz). It consist
58 * of nine, ten-character bursts transmitted at 300 bps and beginning
59 * each second from second 31 to second 39 of the minute. Each character
60 * consists of eight data bits plus one start bit and two stop bits to
61 * encode two hex digits. The burst data consist of five characters (ten
62 * hex digits) followed by a repeat of these characters. In format A,
63 * the characters are repeated in the same polarity; in format B, the
64 * characters are repeated in the opposite polarity.
66 * Format A bursts are sent at seconds 32 through 39 of the minute in
69 * 6dddhhmmss6dddhhmmss
71 * The first ten digits encode a frame marker (6) followed by the day
72 * (ddd), hour (hh in UTC), minute (mm) and the second (ss). Since
73 * format A bursts are sent during the third decade of seconds the tens
74 * digit of ss is always 3. The driver uses this to determine correct
75 * burst synchronization. These digits are then repeated with the same
78 * Format B bursts are sent at second 31 of the minute in hex digits
80 * xdyyyyttaaxdyyyyttaa
82 * The first ten digits encode a code (x described below) followed by
83 * the DUT1 (d in deciseconds), Gregorian year (yyyy), difference TAI -
84 * UTC (tt) and daylight time indicator (aa) peculiar to Canada. These
85 * digits are then repeated with inverted polarity.
89 * 1 Sign of DUT (0 = +)
90 * 2 Leap second warning. One second will be added.
91 * 4 Leap second warning. One second will be subtracted.
92 * 8 Even parity bit for this nibble.
94 * By design, the last stop bit of the last character in the burst
95 * coincides with 0.5 second. Since characters have 11 bits and are
96 * transmitted at 300 bps, the last stop bit of the first character
97 * coincides with 0.5 - 10 * 11/300 = 0.133 second. Depending on the
98 * UART, character interrupts can vary somewhere between the beginning
99 * of bit 9 and end of bit 11. These eccentricities can be corrected
100 * along with the radio propagation delay using fudge time 1.
104 * The timecode format used for debugging and data recording includes
105 * data helpful in diagnosing problems with the radio signal and serial
106 * connections. With debugging enabled (-d -d -d on the ntpd command
107 * line), the driver produces one line for each burst in two formats
108 * corresponding to format A and B. Following is format A:
112 * where n is the number of characters in the burst (0-11), b the burst
113 * distance (0-40), f the field alignment (-1, 0, 1), s the
114 * synchronization distance (0-16), m the burst number (2-9) and code
115 * the burst characters as received. Note that the hex digits in each
116 * character are reversed, so the burst
118 * 10 38 0 16 9 06851292930685129293
120 * is interpreted as containing 11 characters with burst distance 38,
121 * field alignment 0, synchronization distance 16 and burst number 9.
122 * The nibble-swapped timecode shows day 58, hour 21, minute 29 and
125 * When the audio driver is compiled, format A is preceded by
126 * the current gain (0-255) and relative signal level (0-9999). The
127 * receiver folume control should be set so that the gain is somewhere
128 * near the middle of the range 0-255, which results in a signal level
131 * Following is format B:
135 * where n is the number of characters in the burst (0-11), b the burst
136 * distance (0-40), s the synchronization distance (0-40) and code the
137 * burst characters as received. Note that the hex digits in each
138 * character are reversed and the last ten digits inverted, so the burst
140 * 11 40 1091891300ef6e76ecff
142 * is interpreted as containing 11 characters with burst distance 40.
143 * The nibble-swapped timecode shows DUT1 +0.1 second, year 1998 and TAI
146 * In addition to the above, the reference timecode is updated and
147 * written to the clockstats file and debug score after the last burst
148 * received in the minute. The format is
150 * qq yyyy ddd hh:mm:ss nn dd tt
152 * where qq are the error flags, as described below, yyyy is the year,
153 * ddd the day, hh:mm:ss the time of day, nn the number of format A
154 * bursts received during the previous minute, dd the decoding distance
155 * and tt the number of timestamps. The error flags are cleared after
160 * For accuracies better than the low millisceconds, fudge time1 can be
161 * set to the radio propagation delay from CHU to the receiver. This can
162 * be done conviently using the minimuf program. When the modem driver
163 * is compiled, fudge flag3 enables the ppsclock line discipline. Fudge
164 * flag4 causes the dubugging output described above to be recorded in
165 * the clockstats file.
167 * When the audio driver is compiled, fudge flag2 selects the audio
168 * input port, where 0 is the mike port (default) and 1 is the line-in
169 * port. It does not seem useful to select the compact disc player port.
170 * Fudge flag3 enables audio monitoring of the input signal. For this
171 * purpose, the speaker volume must be set before the driver is started.
175 * Interface definitions
177 #define SPEED232 B300 /* uart speed (300 baud) */
178 #define PRECISION (-10) /* precision assumed (about 1 ms) */
179 #define REFID "CHU" /* reference ID */
181 #define DESCRIPTION "CHU Modem Receiver" /* WRU */
184 * Audio demodulator definitions
186 #define AUDIO_BUFSIZ 160 /* codec buffer size (Solaris only) */
187 #define SAMPLE 8000 /* nominal sample rate (Hz) */
188 #define BAUD 300 /* modulation rate (bps) */
189 #define OFFSET 128 /* companded sample offset */
190 #define SIZE 256 /* decompanding table size */
191 #define MAXSIG 6000. /* maximum signal level */
192 #define DRPOUT 100. /* dropout signal level */
193 #define LIMIT 1000. /* soft limiter threshold */
194 #define AGAIN 6. /* baseband gain */
195 #define LAG 10 /* discriminator lag */
197 #define DEVICE "/dev/chu%d" /* device name and unit */
198 #define SPEED232 B300 /* UART speed (300 baud) */
199 #define DESCRIPTION "CHU Audio Receiver" /* WRU */
200 #endif /* AUDIO_CHU */
203 * Decoder definitions
205 #define CHAR (11. / 300.) /* character time (s) */
206 #define FUDGE .185 /* offset to first stop bit (s) */
207 #define BURST 11 /* max characters per burst */
208 #define MINCHAR 9 /* min characters per burst */
209 #define MINDIST 28 /* min burst distance (of 40) */
210 #define MINSYNC 8 /* min sync distance (of 16) */
211 #define MINDEC .5 /* decoder majority rule (of 1.) */
212 #define MINSTAMP 20 /* min timestamps (of 60) */
215 * Hex extension codes (>= 16)
217 #define HEX_MISS 16 /* miss */
218 #define HEX_SOFT 17 /* soft error */
219 #define HEX_HARD 18 /* hard error */
222 * Error flags (up->errflg)
224 #define CHU_ERR_RUNT 0x001 /* runt burst */
225 #define CHU_ERR_NOISE 0x002 /* noise burst */
226 #define CHU_ERR_BFRAME 0x004 /* invalid format B frame sync */
227 #define CHU_ERR_BFORMAT 0x008 /* invalid format B data */
228 #define CHU_ERR_AFRAME 0x010 /* invalid format A frame sync */
229 #define CHU_ERR_DECODE 0x020 /* invalid data decode */
230 #define CHU_ERR_STAMP 0x040 /* too few timestamps */
231 #define CHU_ERR_AFORMAT 0x080 /* invalid format A data */
233 #define CHU_ERR_ERROR 0x100 /* codec error (overrun) */
234 #endif /* AUDIO_CHU */
238 double shift[12]; /* mark register */
239 double max, min; /* max/min envelope signals */
240 double dist; /* sample distance */
241 int uart; /* decoded character */
243 #endif /* AUDIO_CHU */
246 * CHU unit control structure
249 u_char decode[20][16]; /* maximum likelihood decoding matrix */
250 l_fp cstamp[BURST]; /* character timestamps */
251 l_fp tstamp[MAXSTAGE]; /* timestamp samples */
252 l_fp timestamp; /* current buffer timestamp */
253 l_fp laststamp; /* last buffer timestamp */
254 l_fp charstamp; /* character time as a l_fp */
255 int errflg; /* error flags */
256 int bufptr; /* buffer index pointer */
257 int pollcnt; /* poll message counter */
260 * Character burst variables
262 int cbuf[BURST]; /* character buffer */
263 int ntstamp; /* number of timestamp samples */
264 int ndx; /* buffer start index */
265 int prevsec; /* previous burst second */
266 int burdist; /* burst distance */
267 int syndist; /* sync distance */
268 int burstcnt; /* format A bursts this minute */
272 * Audio codec variables
274 double comp[SIZE]; /* decompanding table */
275 int port; /* codec port */
276 int gain; /* codec gain */
277 int bufcnt; /* samples in buffer */
278 int clipcnt; /* sample clip count */
279 int seccnt; /* second interval counter */
284 l_fp tick; /* audio sample increment */
285 double bpf[9]; /* IIR bandpass filter */
286 double disc[LAG]; /* discriminator shift register */
287 double lpf[27]; /* FIR lowpass filter */
288 double monitor; /* audio monitor */
289 double maxsignal; /* signal level */
290 int discptr; /* discriminator pointer */
293 * Maximum likelihood UART variables
295 double baud; /* baud interval */
296 struct surv surv[8]; /* UART survivor structures */
297 int decptr; /* decode pointer */
298 int dbrk; /* holdoff counter */
299 #endif /* AUDIO_CHU */
303 * Function prototypes
305 static int chu_start P((int, struct peer *));
306 static void chu_shutdown P((int, struct peer *));
307 static void chu_receive P((struct recvbuf *));
308 static void chu_poll P((int, struct peer *));
311 * More function prototypes
313 static void chu_decode P((struct peer *, int));
314 static void chu_burst P((struct peer *));
315 static void chu_clear P((struct peer *));
316 static void chu_update P((struct peer *, int));
317 static void chu_year P((struct peer *, int));
318 static int chu_dist P((int, int));
320 static void chu_uart P((struct surv *, double));
321 static void chu_rf P((struct peer *, double));
322 static void chu_gain P((struct peer *));
323 static int chu_audio P((void));
324 static void chu_debug P((void));
325 #endif /* AUDIO_CHU */
330 static char hexchar[] = "0123456789abcdef_-=";
332 #ifdef HAVE_SYS_AUDIOIO_H
333 struct audio_device device; /* audio device ident */
334 #endif /* HAVE_SYS_AUDIOIO_H */
335 static struct audio_info info; /* audio device info */
336 static int chu_ctl_fd; /* audio control file descriptor */
337 #endif /* AUDIO_CHU */
342 struct refclock refclock_chu = {
343 chu_start, /* start up driver */
344 chu_shutdown, /* shut down driver */
345 chu_poll, /* transmit poll message */
346 noentry, /* not used (old chu_control) */
347 noentry, /* initialize driver (not used) */
348 noentry, /* not used (old chu_buginfo) */
349 NOFLAGS /* not used */
354 * chu_start - open the devices and initialize data for processing
358 int unit, /* instance number (not used) */
359 struct peer *peer /* peer structure pointer */
363 struct refclockproc *pp;
368 int fd; /* file descriptor */
371 double step; /* codec adjustment */
376 fd = open("/dev/audio", O_RDWR | O_NONBLOCK, 0777);
378 perror("chu: audio");
382 char device[20]; /* device name */
385 * Open serial port. Use RAW line discipline (required).
387 (void)sprintf(device, DEVICE, unit);
388 if (!(fd = refclock_open(device, SPEED232, LDISC_RAW))) {
391 #endif /* AUDIO_CHU */
394 * Allocate and initialize unit structure
396 if (!(up = (struct chuunit *)
397 emalloc(sizeof(struct chuunit)))) {
401 memset((char *)up, 0, sizeof(struct chuunit));
403 pp->unitptr = (caddr_t)up;
404 pp->io.clock_recv = chu_receive;
405 pp->io.srcclock = (caddr_t)peer;
408 if (!io_addclock(&pp->io)) {
415 * Initialize miscellaneous variables
417 peer->precision = PRECISION;
418 pp->clockdesc = DESCRIPTION;
419 memcpy((char *)&pp->refid, REFID, 4);
420 DTOLFP(CHAR, &up->charstamp);
423 up->gain = (AUDIO_MAX_GAIN - AUDIO_MIN_GAIN) / 2;
424 if (chu_audio() < 0) {
425 io_closeclock(&pp->io);
431 * The companded samples are encoded sign-magnitude. The table
432 * contains all the 256 values in the interest of speed.
434 up->comp[0] = up->comp[OFFSET] = 0.;
435 up->comp[1] = 1; up->comp[OFFSET + 1] = -1.;
436 up->comp[2] = 3; up->comp[OFFSET + 2] = -3.;
438 for (i = 3; i < OFFSET; i++) {
439 up->comp[i] = up->comp[i - 1] + step;
440 up->comp[OFFSET + i] = -up->comp[i];
444 DTOLFP(1. / SAMPLE, &up->tick);
445 #endif /* AUDIO_CHU */
451 * chu_shutdown - shut down the clock
455 int unit, /* instance number (not used) */
456 struct peer *peer /* peer structure pointer */
460 struct refclockproc *pp;
463 up = (struct chuunit *)pp->unitptr;
464 io_closeclock(&pp->io);
471 * chu_receive - receive data from the audio device
475 struct recvbuf *rbufp /* receive buffer structure pointer */
479 struct refclockproc *pp;
485 double sample; /* codec sample */
486 u_char *dpt; /* buffer pointer */
487 l_fp ltemp; /* l_fp temp */
488 double dtemp; /* double temp */
489 int isneg; /* parity flag */
490 int i, j; /* index temps */
492 peer = (struct peer *)rbufp->recv_srcclock;
494 up = (struct chuunit *)pp->unitptr;
497 * Main loop - read until there ain't no more. Note codec
498 * samples are bit-inverted.
500 up->timestamp = rbufp->recv_time;
501 up->bufcnt = rbufp->recv_length;
502 DTOLFP(up->bufcnt * 1. / SAMPLE, <emp);
503 L_SUB(&up->timestamp, <emp);
504 dpt = (u_char *)&rbufp->recv_space;
505 for (up->bufptr = 0; up->bufptr < up->bufcnt; up->bufptr++) {
506 sample = up->comp[~*dpt & 0xff];
509 * Clip noise spikes greater than MAXSIG. If no clips,
510 * increase the gain a tad; if the clips are too high,
513 if (sample > MAXSIG) {
516 } else if (sample < -MAXSIG) {
520 up->seccnt = (up->seccnt + 1) % SAMPLE;
521 if (up->seccnt == 0) {
522 if (pp->sloppyclockflag & CLK_FLAG2)
523 up->port = AUDIO_LINE_IN;
525 up->port = AUDIO_MICROPHONE;
529 chu_rf(peer, sample);
532 * During development, it is handy to have an audio
533 * monitor that can be switched to various signals. This
534 * code converts the linear signal left in up->monitor
535 * to codec format. If we can get the grass out of this
536 * thing and improve modem performance, this expensive
537 * code will be permanently nixed.
548 if (dtemp > up->comp[i])
550 else if (dtemp < up->comp[i])
557 *dpt = ~(i + OFFSET);
561 L_ADD(&up->timestamp, &up->tick);
565 * Squawk to the monitor speaker if enabled.
567 if (pp->sloppyclockflag & CLK_FLAG3)
568 if (write(pp->io.fd, (u_char *)&rbufp->recv_space,
569 (u_int)up->bufcnt) < 0)
575 * chu_rf - filter and demodulate the FSK signal
577 * This routine implements a 300-baud Bell 103 modem with mark 2225 Hz
578 * and space 2025 Hz. It uses a bandpass filter followed by a soft
579 * limiter, FM discriminator and lowpass filter. A maximum likelihood
580 * decoder samples the baseband signal at eight times the baud rate and
581 * detects the start bit of each character.
583 * The filters are built for speed, which explains the rather clumsy
584 * code. Hopefully, the compiler will efficiently implement the move-
585 * and-muiltiply-and-add operations.
589 struct peer *peer, /* peer structure pointer */
590 double sample /* analog sample */
593 struct refclockproc *pp;
600 double signal; /* bandpass signal */
601 double limit; /* limiter signal */
602 double disc; /* discriminator signal */
603 double lpf; /* lowpass signal */
604 double span; /* UART signal span */
605 double dist; /* UART signal distance */
606 int i, j; /* index temps */
609 up = (struct chuunit *)pp->unitptr;
611 * Bandpass filter. 4th-order elliptic, 500-Hz bandpass centered
612 * at 2125 Hz. Passband ripple 0.3 dB, stopband ripple 50 dB.
614 signal = (up->bpf[8] = up->bpf[7]) * 5.844676e-01;
615 signal += (up->bpf[7] = up->bpf[6]) * 4.884860e-01;
616 signal += (up->bpf[6] = up->bpf[5]) * 2.704384e+00;
617 signal += (up->bpf[5] = up->bpf[4]) * 1.645032e+00;
618 signal += (up->bpf[4] = up->bpf[3]) * 4.644557e+00;
619 signal += (up->bpf[3] = up->bpf[2]) * 1.879165e+00;
620 signal += (up->bpf[2] = up->bpf[1]) * 3.522634e+00;
621 signal += (up->bpf[1] = up->bpf[0]) * 7.315738e-01;
622 up->bpf[0] = sample - signal;
623 signal = up->bpf[0] * 6.176213e-03
624 + up->bpf[1] * 3.156599e-03
625 + up->bpf[2] * 7.567487e-03
626 + up->bpf[3] * 4.344580e-03
627 + up->bpf[4] * 1.190128e-02
628 + up->bpf[5] * 4.344580e-03
629 + up->bpf[6] * 7.567487e-03
630 + up->bpf[7] * 3.156599e-03
631 + up->bpf[8] * 6.176213e-03;
633 up->monitor = signal / 4.; /* note monitor after filter */
636 * Soft limiter/discriminator. The 11-sample discriminator lag
637 * interval corresponds to three cycles of 2125 Hz, which
638 * requires the sample frequency to be 2125 * 11 / 3 = 7791.7
639 * Hz. The discriminator output varies +-0.5 interval for input
640 * frequency 2025-2225 Hz. However, we don't get to sample at
641 * this frequency, so the discriminator output is biased. Life
647 else if (limit < -LIMIT)
649 disc = up->disc[up->discptr] * -limit;
650 up->disc[up->discptr] = limit;
651 up->discptr = (up->discptr + 1 ) % LAG;
658 * Lowpass filter. Raised cosine, Ts = 1 / 300, beta = 0.1.
660 lpf = (up->lpf[26] = up->lpf[25]) * 2.538771e-02;
661 lpf += (up->lpf[25] = up->lpf[24]) * 1.084671e-01;
662 lpf += (up->lpf[24] = up->lpf[23]) * 2.003159e-01;
663 lpf += (up->lpf[23] = up->lpf[22]) * 2.985303e-01;
664 lpf += (up->lpf[22] = up->lpf[21]) * 4.003697e-01;
665 lpf += (up->lpf[21] = up->lpf[20]) * 5.028552e-01;
666 lpf += (up->lpf[20] = up->lpf[19]) * 6.028795e-01;
667 lpf += (up->lpf[19] = up->lpf[18]) * 6.973249e-01;
668 lpf += (up->lpf[18] = up->lpf[17]) * 7.831828e-01;
669 lpf += (up->lpf[17] = up->lpf[16]) * 8.576717e-01;
670 lpf += (up->lpf[16] = up->lpf[15]) * 9.183463e-01;
671 lpf += (up->lpf[15] = up->lpf[14]) * 9.631951e-01;
672 lpf += (up->lpf[14] = up->lpf[13]) * 9.907208e-01;
673 lpf += (up->lpf[13] = up->lpf[12]) * 1.000000e+00;
674 lpf += (up->lpf[12] = up->lpf[11]) * 9.907208e-01;
675 lpf += (up->lpf[11] = up->lpf[10]) * 9.631951e-01;
676 lpf += (up->lpf[10] = up->lpf[9]) * 9.183463e-01;
677 lpf += (up->lpf[9] = up->lpf[8]) * 8.576717e-01;
678 lpf += (up->lpf[8] = up->lpf[7]) * 7.831828e-01;
679 lpf += (up->lpf[7] = up->lpf[6]) * 6.973249e-01;
680 lpf += (up->lpf[6] = up->lpf[5]) * 6.028795e-01;
681 lpf += (up->lpf[5] = up->lpf[4]) * 5.028552e-01;
682 lpf += (up->lpf[4] = up->lpf[3]) * 4.003697e-01;
683 lpf += (up->lpf[3] = up->lpf[2]) * 2.985303e-01;
684 lpf += (up->lpf[2] = up->lpf[1]) * 2.003159e-01;
685 lpf += (up->lpf[1] = up->lpf[0]) * 1.084671e-01;
686 lpf += up->lpf[0] = disc * 2.538771e-02;
688 printf("%8.3f %8.3f\n", disc, lpf);
692 * Maximum likelihood decoder. The UART updates each of the
693 * eight survivors and determines the span, slice level and
694 * tentative decoded character. Valid 11-bit characters are
695 * framed so that bit 1 and bit 11 (stop bits) are mark and bit
696 * 2 (start bit) is space. When a valid character is found, the
697 * survivor with maximum distance determines the final decoded
700 up->baud += 1. / SAMPLE;
701 if (up->baud > 1. / (BAUD * 8.)) {
702 up->baud -= 1. / (BAUD * 8.);
703 sp = &up->surv[up->decptr];
704 span = sp->max - sp->min;
705 up->maxsignal += (span - up->maxsignal) / 80.;
708 } else if ((sp->uart & 0x403) == 0x401 && span > 1000.)
712 for (i = 0; i < 8; i++) {
713 if (up->surv[i].dist > dist) {
714 dist = up->surv[i].dist;
718 chu_decode(peer, (up->surv[j].uart >> 2) &
722 up->decptr = (up->decptr + 1) % 8;
723 chu_uart(sp, -lpf * AGAIN);
729 * chu_uart - maximum likelihood UART
731 * This routine updates a shift register holding the last 11 envelope
732 * samples. It then computes the slice level and span over these samples
733 * and determines the tentative data bits and distance. The calling
734 * program selects over the last eight survivors the one with maximum
735 * distance to determine the decoded character.
739 struct surv *sp, /* survivor structure pointer */
740 double sample /* baseband signal */
746 double max, min; /* max/min envelope */
747 double slice; /* slice level */
748 double dist; /* distance */
749 double dtemp; /* double temp */
750 int i; /* index temp */
753 * Save the sample and shift right. At the same time, measure
754 * the maximum and minimum over all eleven samples.
758 sp->shift[0] = sample;
759 for (i = 11; i > 0; i--) {
760 sp->shift[i] = sp->shift[i - 1];
761 if (sp->shift[i] > max)
763 if (sp->shift[i] < min)
768 * Determine the slice level midway beteen the maximum and
769 * minimum and the span as the maximum less the minimum. Compute
770 * the distance on the assumption the first and last bits must
771 * be mark, the second space and the rest either mark or space.
773 slice = (max + min) / 2.;
776 for (i = 1; i < 12; i++) {
778 dtemp = sp->shift[i];
781 if (i == 1 || i == 11) {
783 } else if (i == 10) {
794 sp->dist = dist / (11 * (max - min));
798 #else /* AUDIO_CHU */
800 * chu_receive - receive data from the serial interface
804 struct recvbuf *rbufp /* receive buffer structure pointer */
808 struct refclockproc *pp;
811 u_char *dpt; /* receive buffer pointer */
813 peer = (struct peer *)rbufp->recv_srcclock;
815 up = (struct chuunit *)pp->unitptr;
818 * Initialize pointers and read the timecode and timestamp.
820 up->timestamp = rbufp->recv_time;
821 dpt = (u_char *)&rbufp->recv_space;
822 chu_decode(peer, *dpt);
824 #endif /* AUDIO_CHU */
828 * chu_decode - decode the data
832 struct peer *peer, /* peer structure pointer */
833 int hexhex /* data character */
836 struct refclockproc *pp;
842 l_fp tstmp; /* timestamp temp */
843 double dtemp; /* double temp */
846 up = (struct chuunit *)pp->unitptr;
849 * If the interval since the last character is greater than the
850 * longest burst, process the last burst and start a new one. If
851 * the interval is less than this but greater than two
852 * characters, consider this a noise burst and reject it.
854 tstmp = up->timestamp;
855 if (L_ISZERO(&up->laststamp))
856 up->laststamp = up->timestamp;
857 L_SUB(&tstmp, &up->laststamp);
858 up->laststamp = up->timestamp;
859 LFPTOD(&tstmp, dtemp);
860 if (dtemp > BURST * CHAR) {
863 } else if (dtemp > 2.5 * CHAR) {
868 * Append the character to the current burst and append the
869 * timestamp to the timestamp list.
871 if (up->ndx < BURST) {
872 up->cbuf[up->ndx] = hexhex & 0xff;
873 up->cstamp[up->ndx] = up->timestamp;
881 * chu_burst - search for valid burst format
889 struct refclockproc *pp;
894 int i; /* index temp */
897 up = (struct chuunit *)pp->unitptr;
900 * Correlate a block of five characters with the next block of
901 * five characters. The burst distance is defined as the number
902 * of bits that match in the two blocks for format A and that
903 * match the inverse for format B.
905 if (up->ndx < MINCHAR) {
906 up->errflg |= CHU_ERR_RUNT;
910 for (i = 0; i < 5 && i < up->ndx - 5; i++)
911 up->burdist += chu_dist(up->cbuf[i], up->cbuf[i + 5]);
914 * If the burst distance is at least MINDIST, this must be a
915 * format A burst; if the value is not greater than -MINDIST, it
916 * must be a format B burst; otherwise, it is a noise burst and
917 * of no use to anybody.
919 if (up->burdist >= MINDIST) {
920 chu_update(peer, up->ndx);
921 } else if (up->burdist <= -MINDIST) {
922 chu_year(peer, up->ndx);
924 up->errflg |= CHU_ERR_NOISE;
929 * If this is a valid burst, wait a guard time of ten seconds to
930 * allow for more bursts, then arm the poll update routine to
931 * process the minute. Don't do this if this is called from the
932 * timer interrupt routine.
934 if (peer->outdate == current_time)
937 peer->nextdate = current_time + 10;
942 * chu_year - decode format B burst
950 struct refclockproc *pp;
956 u_char code[11]; /* decoded timecode */
957 l_fp offset; /* timestamp offset */
958 int leap; /* leap/dut code */
959 int dut; /* UTC1 correction */
960 int tai; /* TAI - UTC correction */
961 int dst; /* Canadian DST code */
962 int i; /* index temp */
965 up = (struct chuunit *)pp->unitptr;
968 * In a format B burst, a character is considered valid only if
969 * the first occurrence matches the last occurrence. The burst
970 * is considered valid only if all characters are valid; that
971 * is, only if the distance is 40.
973 sprintf(pp->a_lastcode, "%2d %2d ", nchar, -up->burdist);
974 for (i = 0; i < nchar; i++)
975 sprintf(&pp->a_lastcode[strlen(pp->a_lastcode)], "%02x",
977 pp->lencode = strlen(pp->a_lastcode);
978 if (pp->sloppyclockflag & CLK_FLAG4)
979 record_clock_stats(&peer->srcadr, pp->a_lastcode);
982 printf("chu: %s\n", pp->a_lastcode);
984 if (-up->burdist < 40) {
985 up->errflg |= CHU_ERR_BFRAME;
990 * Convert the burst data to internal format. If this succeeds,
991 * save the timestamps for later. The leap, dut, tai and dst are
994 for (i = 0; i < 5; i++) {
995 code[2 * i] = hexchar[up->cbuf[i] & 0xf];
996 code[2 * i + 1] = hexchar[(up->cbuf[i] >>
999 if (sscanf((char *)code, "%1x%1d%4d%2d%2x", &leap, &dut,
1000 &pp->year, &tai, &dst) != 5) {
1001 up->errflg |= CHU_ERR_BFORMAT;
1006 for (i = 0; i < nchar && i < 10; i++) {
1007 up->tstamp[up->ntstamp] = up->cstamp[i];
1008 L_SUB(&up->tstamp[up->ntstamp], &offset);
1009 L_ADD(&offset, &up->charstamp);
1010 if (up->ntstamp < MAXSTAGE)
1017 * chu_update - decode format A burst
1025 struct refclockproc *pp;
1031 l_fp offset; /* timestamp offset */
1032 int val; /* distance */
1033 int temp; /* common temp */
1034 int i, j, k; /* index temps */
1037 up = (struct chuunit *)pp->unitptr;
1040 * Determine correct burst phase. There are three cases
1041 * corresponding to in-phase, one character early or one
1042 * character late. These cases are distinguished by the position
1043 * of the framing digits x6 at positions 0 and 5 and x3 at
1044 * positions 4 and 9. The correct phase is when the distance
1045 * relative to the framing digits is maximum. The burst is valid
1046 * only if the maximum distance is at least MINSYNC.
1048 up->syndist = k = 0;
1050 for (i = -1; i < 2; i++) {
1051 temp = up->cbuf[i + 4] & 0xf;
1053 temp |= (up->cbuf[i] & 0xf) << 4;
1054 val = chu_dist(temp, 0x63);
1055 temp = (up->cbuf[i + 5] & 0xf) << 4;
1057 temp |= up->cbuf[i + 9] & 0xf;
1058 val += chu_dist(temp, 0x63);
1059 if (val > up->syndist) {
1065 temp = (up->cbuf[k + 4] >> 4) & 0xf;
1066 if (temp > 9 || k + 9 >= nchar || temp != ((up->cbuf[k + 9] >>
1070 sprintf(pp->a_lastcode, "%3d %4.0f %2d %2d %2d %2d %1d ",
1071 up->gain, up->maxsignal, nchar, up->burdist, k, up->syndist,
1074 sprintf(pp->a_lastcode, "%2d %2d %2d %2d %1d ", nchar,
1075 up->burdist, k, up->syndist, temp);
1076 #endif /* AUDIO_CHU */
1077 for (i = 0; i < nchar; i++)
1078 sprintf(&pp->a_lastcode[strlen(pp->a_lastcode)], "%02x",
1080 pp->lencode = strlen(pp->a_lastcode);
1081 if (pp->sloppyclockflag & CLK_FLAG4)
1082 record_clock_stats(&peer->srcadr, pp->a_lastcode);
1085 printf("chu: %s\n", pp->a_lastcode);
1087 if (up->syndist < MINSYNC) {
1088 up->errflg |= CHU_ERR_AFRAME;
1093 * A valid burst requires the first seconds number to match the
1094 * last seconds number. If so, the burst timestamps are
1095 * corrected to the current minute and saved for later
1096 * processing. In addition, the seconds decode is advanced from
1097 * the previous burst to the current one.
1100 offset.l_ui = 30 + temp;
1104 offset = up->charstamp;
1107 for (; i < nchar && i < k + 10; i++) {
1108 up->tstamp[up->ntstamp] = up->cstamp[i];
1109 L_SUB(&up->tstamp[up->ntstamp], &offset);
1110 L_ADD(&offset, &up->charstamp);
1111 if (up->ntstamp < MAXSTAGE)
1114 while (temp > up->prevsec) {
1115 for (j = 15; j > 0; j--) {
1116 up->decode[9][j] = up->decode[9][j - 1];
1118 up->decode[19][j - 1];
1120 up->decode[9][j] = up->decode[19][j] = 0;
1125 for (j = 0; j < nchar; j++) {
1126 if (i < 0 || i > 19) {
1130 up->decode[i++][up->cbuf[j] & 0xf]++;
1131 up->decode[i++][(up->cbuf[j] >> 4) & 0xf]++;
1138 * chu_poll - called by the transmit procedure
1146 struct refclockproc *pp;
1152 u_char code[11]; /* decoded timecode */
1153 l_fp toffset, offset; /* l_fp temps */
1154 int mindist; /* minimum distance */
1155 int val1, val2; /* maximum distance */
1156 int synchar; /* should be a 6 in traffic */
1157 double dtemp; /* double temp */
1158 int temp; /* common temp */
1159 int i, j, k; /* index temps */
1162 up = (struct chuunit *)pp->unitptr;
1165 * Process the last burst, if still in the burst buffer.
1166 * Don't mess with anything if nothing has been heard.
1169 if (up->pollcnt == 0)
1170 refclock_report(peer, CEVNT_TIMEOUT);
1173 if (up->burstcnt == 0) {
1179 * Majority decoder. Select the character with the most
1180 * occurrences for each burst position. The distance for the
1181 * character is this number of occurrences. If no occurrences
1182 * are found, assume a miss '_'; if only a single occurrence is
1183 * found, assume a soft error '-'; if two different characters
1184 * with the same distance are found, assume a hard error '='.
1185 * The decoding distance is defined as the minimum of the
1186 * character distances.
1189 for (i = 0; i < 10; i++) {
1192 for (j = 0; j < 16; j++) {
1193 temp = up->decode[i][j] + up->decode[i + 10][j];
1200 if (val1 > 0 && val1 == val2)
1208 code[i] = hexchar[code[i]];
1211 if (mindist < up->burstcnt * 2 * MINDEC)
1212 up->errflg |= CHU_ERR_DECODE;
1213 if (up->ntstamp < MINSTAMP)
1214 up->errflg |= CHU_ERR_STAMP;
1217 * Compute the timecode timestamp from the days, hours and
1218 * minutes of the timecode. Use clocktime() for the aggregate
1219 * minutes and the minute offset computed from the burst
1220 * seconds. Note that this code relies on the filesystem time
1221 * for the years and does not use the years of the timecode.
1223 if (sscanf((char *)code, "%1x%3d%2d%2d", &synchar, &pp->day, &pp->hour,
1225 up->errflg |= CHU_ERR_AFORMAT;
1226 sprintf(pp->a_lastcode,
1227 "%02x %4d %3d %02d:%02d:%02d %2d %2d %2d",
1228 up->errflg, pp->year, pp->day, pp->hour, pp->minute,
1229 pp->second, up->burstcnt, mindist, up->ntstamp);
1230 pp->lencode = strlen(pp->a_lastcode);
1231 record_clock_stats(&peer->srcadr, pp->a_lastcode);
1234 printf("chu: %s\n", pp->a_lastcode);
1236 if (up->errflg & (CHU_ERR_DECODE | CHU_ERR_STAMP |
1238 refclock_report(peer, CEVNT_BADREPLY);
1243 if (!clocktime(pp->day, pp->hour, pp->minute, 0, GMT,
1244 up->tstamp[0].l_ui, &pp->yearstart, &offset.l_ui)) {
1245 refclock_report(peer, CEVNT_BADTIME);
1250 pp->leap = LEAP_NOWARNING;
1251 pp->lastref = offset;
1253 for (i = 0; i < up->ntstamp; i++) {
1255 L_SUB(&toffset, &up->tstamp[i]);
1256 LFPTOD(&toffset, dtemp);
1257 SAMPLE(dtemp + FUDGE + pp->fudgetime1);
1260 refclock_receive(peer);
1266 * chu_clear - clear decoding matrix
1273 struct refclockproc *pp;
1279 int i, j; /* index temps */
1282 up = (struct chuunit *)pp->unitptr;
1285 * Clear stuff for following minute.
1287 up->ndx = up->ntstamp = up->prevsec = 0;
1290 for (i = 0; i < 20; i++) {
1291 for (j = 0; j < 16; j++)
1292 up->decode[i][j] = 0;
1298 * chu_dist - determine the distance of two octet arguments
1302 int x, /* an octet of bits */
1303 int y /* another octet of bits */
1309 int val; /* bit count */
1310 int temp; /* misc temporary */
1311 int i; /* index temporary */
1314 * The distance is determined as the weight of the exclusive OR
1315 * of the two arguments. The weight is determined by the number
1316 * of one bits in the result. Each one bit increases the weight,
1317 * while each zero bit decreases it.
1321 for (i = 0; i < 8; i++) {
1322 if ((temp & 0x1) == 0)
1334 * chu_gain - adjust codec gain
1336 * This routine is called once each second. If the signal envelope
1337 * amplitude is too low, the codec gain is bumped up by four units; if
1338 * too high, it is bumped down. The decoder is relatively insensitive to
1339 * amplitude, so this crudity works just fine. The input port is set and
1340 * the error flag is cleared, mostly to be ornery.
1344 struct peer *peer /* peer structure pointer */
1347 struct refclockproc *pp;
1351 up = (struct chuunit *)pp->unitptr;
1354 * Apparently, the codec uses only the high order bits of the
1355 * gain control field. Thus, it may take awhile for changes to
1356 * wiggle the hardware bits. Set the new bits in the structure
1357 * and call AUDIO_SETINFO. Upon return, the old bits are in the
1360 if (up->clipcnt == 0) {
1362 if (up->gain > AUDIO_MAX_GAIN)
1363 up->gain = AUDIO_MAX_GAIN;
1364 } else if (up->clipcnt > SAMPLE / 100) {
1366 if (up->gain < AUDIO_MIN_GAIN)
1367 up->gain = AUDIO_MIN_GAIN;
1369 AUDIO_INITINFO(&info);
1370 info.record.port = up->port;
1371 info.record.gain = up->gain;
1372 info.record.error = 0;
1373 ioctl(chu_ctl_fd, (int)AUDIO_SETINFO, &info);
1374 if (info.record.error)
1375 up->errflg |= CHU_ERR_ERROR;
1380 * chu_audio - initialize audio device
1382 * This code works with SunOS 4.1.3 and Solaris 2.6; however, it is
1383 * believed generic and applicable to other systems with a minor twid
1384 * or two. All it does is open the device, set the buffer size (Solaris
1385 * only), preset the gain and set the input port. It assumes that the
1386 * codec sample rate (8000 Hz), precision (8 bits), number of channels
1387 * (1) and encoding (ITU-T G.711 mu-law companded) have been set by
1395 * Open audio control device
1397 if ((chu_ctl_fd = open("/dev/audioctl", O_RDWR)) < 0) {
1401 #ifdef HAVE_SYS_AUDIOIO_H
1403 * Set audio device parameters.
1405 AUDIO_INITINFO(&info);
1406 info.record.buffer_size = AUDIO_BUFSIZ;
1407 if (ioctl(chu_ctl_fd, (int)AUDIO_SETINFO, &info) < 0) {
1408 perror("AUDIO_SETINFO");
1412 #endif /* HAVE_SYS_AUDIOIO_H */
1422 * chu_debug - display audio parameters
1424 * This code doesn't really do anything, except satisfy curiousity and
1425 * verify the ioctl's work.
1433 #ifdef HAVE_SYS_AUDIOIO_H
1434 ioctl(chu_ctl_fd, (int)AUDIO_GETDEV, &device);
1435 printf("chu: name %s, version %s, config %s\n",
1436 device.name, device.version, device.config);
1437 #endif /* HAVE_SYS_AUDIOIO_H */
1438 ioctl(chu_ctl_fd, (int)AUDIO_GETINFO, &info);
1440 "chu: samples %d, channels %d, precision %d, encoding %d\n",
1441 info.record.sample_rate, info.record.channels,
1442 info.record.precision, info.record.encoding);
1443 #ifdef HAVE_SYS_AUDIOIO_H
1444 printf("chu: gain %d, port %d, buffer %d\n",
1445 info.record.gain, info.record.port,
1446 info.record.buffer_size);
1447 #else /* HAVE_SYS_AUDIOIO_H */
1448 printf("chu: gain %d, port %d\n",
1449 info.record.gain, info.record.port);
1450 #endif /* HAVE_SYS_AUDIOIO_H */
1452 "chu: samples %d, eof %d, pause %d, error %d, waiting %d, balance %d\n",
1453 info.record.samples, info.record.eof,
1454 info.record.pause, info.record.error,
1455 info.record.waiting, info.record.balance);
1456 printf("chu: monitor %d, muted %d\n",
1457 info.monitor_gain, info.output_muted);
1460 #endif /* AUDIO_CHU */
1463 int refclock_chu_bs;
1464 #endif /* REFCLOCK */