Expand PMF_FN_* macros.
[netbsd-mini2440.git] / dist / ntp / ntpd / refclock_chu.c
blob59db051d6bd286279ee5b46cbdb06cf903f4f0c3
1 /* $NetBSD: refclock_chu.c,v 1.6 2006/06/11 19:34:12 kardel Exp $ */
3 /*
4 * refclock_chu - clock driver for Canadian CHU time/frequency station
5 */
6 #ifdef HAVE_CONFIG_H
7 #include <config.h>
8 #endif
10 #if defined(REFCLOCK) && defined(CLOCK_CHU)
12 #include "ntpd.h"
13 #include "ntp_io.h"
14 #include "ntp_refclock.h"
15 #include "ntp_calendar.h"
16 #include "ntp_stdlib.h"
18 #include <stdio.h>
19 #include <ctype.h>
20 #include <math.h>
22 #ifdef HAVE_AUDIO
23 #include "audio.h"
24 #endif /* HAVE_AUDIO */
26 #define ICOM 1 /* undefine to suppress ICOM code */
28 #ifdef ICOM
29 #include "icom.h"
30 #endif /* ICOM */
33 * Audio CHU demodulator/decoder
35 * This driver synchronizes the computer time using data encoded in
36 * radio transmissions from Canadian time/frequency station CHU in
37 * Ottawa, Ontario. Transmissions are made continuously on 3330 kHz,
38 * 7335 kHz and 14670 kHz in upper sideband, compatible AM mode. An
39 * ordinary shortwave receiver can be tuned manually to one of these
40 * frequencies or, in the case of ICOM receivers, the receiver can be
41 * tuned automatically using this program as propagation conditions
42 * change throughout the day and night.
44 * The driver receives, demodulates and decodes the radio signals when
45 * connected to the audio codec of a suported workstation hardware and
46 * operating system. These include Solaris, SunOS, FreeBSD, NetBSD and
47 * Linux. In this implementation, only one audio driver and codec can be
48 * supported on a single machine.
50 * The driver can be compiled to use a Bell 103 compatible modem or
51 * modem chip to receive the radio signal and demodulate the data.
52 * Alternatively, the driver can be compiled to use the audio codec of
53 * the Sun workstation or another with compatible audio drivers. In the
54 * latter case, the driver implements the modem using DSP routines, so
55 * the radio can be connected directly to either the microphone on line
56 * input port. In either case, the driver decodes the data using a
57 * maximum likelihood technique which exploits the considerable degree
58 * of redundancy available to maximize accuracy and minimize errors.
60 * The CHU time broadcast includes an audio signal compatible with the
61 * Bell 103 modem standard (mark = 2225 Hz, space = 2025 Hz). It consist
62 * of nine, ten-character bursts transmitted at 300 bps and beginning
63 * each second from second 31 to second 39 of the minute. Each character
64 * consists of eight data bits plus one start bit and two stop bits to
65 * encode two hex digits. The burst data consist of five characters (ten
66 * hex digits) followed by a repeat of these characters. In format A,
67 * the characters are repeated in the same polarity; in format B, the
68 * characters are repeated in the opposite polarity.
70 * Format A bursts are sent at seconds 32 through 39 of the minute in
71 * hex digits
73 * 6dddhhmmss6dddhhmmss
75 * The first ten digits encode a frame marker (6) followed by the day
76 * (ddd), hour (hh in UTC), minute (mm) and the second (ss). Since
77 * format A bursts are sent during the third decade of seconds the tens
78 * digit of ss is always 3. The driver uses this to determine correct
79 * burst synchronization. These digits are then repeated with the same
80 * polarity.
82 * Format B bursts are sent at second 31 of the minute in hex digits
84 * xdyyyyttaaxdyyyyttaa
86 * The first ten digits encode a code (x described below) followed by
87 * the DUT1 (d in deciseconds), Gregorian year (yyyy), difference TAI -
88 * UTC (tt) and daylight time indicator (aa) peculiar to Canada. These
89 * digits are then repeated with inverted polarity.
91 * The x is coded
93 * 1 Sign of DUT (0 = +)
94 * 2 Leap second warning. One second will be added.
95 * 4 Leap second warning. One second will be subtracted.
96 * 8 Even parity bit for this nibble.
98 * By design, the last stop bit of the last character in the burst
99 * coincides with 0.5 second. Since characters have 11 bits and are
100 * transmitted at 300 bps, the last stop bit of the first character
101 * coincides with 0.5 - 10 * 11/300 = 0.133 second. Depending on the
102 * UART, character interrupts can vary somewhere between the beginning
103 * of bit 9 and end of bit 11. These eccentricities can be corrected
104 * along with the radio propagation delay using fudge time 1.
106 * Debugging aids
108 * The timecode format used for debugging and data recording includes
109 * data helpful in diagnosing problems with the radio signal and serial
110 * connections. With debugging enabled (-d on the ntpd command line),
111 * the driver produces one line for each burst in two formats
112 * corresponding to format A and B. Following is format A:
114 * n b f s m code
116 * where n is the number of characters in the burst (0-11), b the burst
117 * distance (0-40), f the field alignment (-1, 0, 1), s the
118 * synchronization distance (0-16), m the burst number (2-9) and code
119 * the burst characters as received. Note that the hex digits in each
120 * character are reversed, so the burst
122 * 10 38 0 16 9 06851292930685129293
124 * is interpreted as containing 11 characters with burst distance 38,
125 * field alignment 0, synchronization distance 16 and burst number 9.
126 * The nibble-swapped timecode shows day 58, hour 21, minute 29 and
127 * second 39.
129 * When the audio driver is compiled, format A is preceded by
130 * the current gain (0-255) and relative signal level (0-9999). The
131 * receiver folume control should be set so that the gain is somewhere
132 * near the middle of the range 0-255, which results in a signal level
133 * near 1000.
135 * Following is format B:
137 * n b s code
139 * where n is the number of characters in the burst (0-11), b the burst
140 * distance (0-40), s the synchronization distance (0-40) and code the
141 * burst characters as received. Note that the hex digits in each
142 * character are reversed and the last ten digits inverted, so the burst
144 * 11 40 1091891300ef6e76ecff
146 * is interpreted as containing 11 characters with burst distance 40.
147 * The nibble-swapped timecode shows DUT1 +0.1 second, year 1998 and TAI
148 * - UTC 31 seconds.
150 * In addition to the above, the reference timecode is updated and
151 * written to the clockstats file and debug score after the last burst
152 * received in the minute. The format is
154 * qq yyyy ddd hh:mm:ss nn dd tt
156 * where qq are the error flags, as described below, yyyy is the year,
157 * ddd the day, hh:mm:ss the time of day, nn the number of format A
158 * bursts received during the previous minute, dd the decoding distance
159 * and tt the number of timestamps. The error flags are cleared after
160 * every update.
162 * Fudge factors
164 * For accuracies better than the low millisceconds, fudge time1 can be
165 * set to the radio propagation delay from CHU to the receiver. This can
166 * be done conviently using the minimuf program.
168 * Fudge flag4 causes the dubugging output described above to be
169 * recorded in the clockstats file. When the audio driver is compiled,
170 * fudge flag2 selects the audio input port, where 0 is the mike port
171 * (default) and 1 is the line-in port. It does not seem useful to
172 * select the compact disc player port. Fudge flag3 enables audio
173 * monitoring of the input signal. For this purpose, the monitor gain is
174 * set to a default value.
176 * The audio codec code is normally compiled in the driver if the
177 * architecture supports it (HAVE_AUDIO defined), but is used only if
178 * the link /dev/chu_audio is defined and valid. The serial port code is
179 * always compiled in the driver, but is used only if the autdio codec
180 * is not available and the link /dev/chu%d is defined and valid.
182 * The ICOM code is normally compiled in the driver if selected (ICOM
183 * defined), but is used only if the link /dev/icom%d is defined and
184 * valid and the mode keyword on the server configuration command
185 * specifies a nonzero mode (ICOM ID select code). The C-IV speed is
186 * 9600 bps if the high order 0x80 bit of the mode is zero and 1200 bps
187 * if one. The C-IV trace is turned on if the debug level is greater
188 * than one.
191 * Interface definitions
193 #define SPEED232 B300 /* uart speed (300 baud) */
194 #define PRECISION (-10) /* precision assumed (about 1 ms) */
195 #define REFID "CHU" /* reference ID */
196 #define DEVICE "/dev/chu%d" /* device name and unit */
197 #define SPEED232 B300 /* UART speed (300 baud) */
198 #ifdef ICOM
199 #define TUNE .001 /* offset for narrow filter (kHz) */
200 #define DWELL 5 /* minutes in a probe cycle */
201 #define NCHAN 3 /* number of channels */
202 #define ISTAGE 3 /* number of integrator stages */
203 #endif /* ICOM */
205 #ifdef HAVE_AUDIO
207 * Audio demodulator definitions
209 #define SECOND 8000 /* nominal sample rate (Hz) */
210 #define BAUD 300 /* modulation rate (bps) */
211 #define OFFSET 128 /* companded sample offset */
212 #define SIZE 256 /* decompanding table size */
213 #define MAXAMP 6000. /* maximum signal level */
214 #define MAXCLP 100 /* max clips above reference per s */
215 #define LIMIT 1000. /* soft limiter threshold */
216 #define AGAIN 6. /* baseband gain */
217 #define LAG 10 /* discriminator lag */
218 #define DEVICE_AUDIO "/dev/audio" /* device name */
219 #define DESCRIPTION "CHU Audio/Modem Receiver" /* WRU */
220 #define AUDIO_BUFSIZ 240 /* audio buffer size (30 ms) */
221 #else
222 #define DESCRIPTION "CHU Modem Receiver" /* WRU */
223 #endif /* HAVE_AUDIO */
226 * Decoder definitions
228 #define CHAR (11. / 300.) /* character time (s) */
229 #define FUDGE .185 /* offset to first stop bit (s) */
230 #define BURST 11 /* max characters per burst */
231 #define MINCHAR 9 /* min characters per burst */
232 #define MINDIST 28 /* min burst distance (of 40) */
233 #define MINBURST 4 /* min bursts in minute */
234 #define MINSYNC 8 /* min sync distance (of 16) */
235 #define MINSTAMP 20 /* min timestamps (of 60) */
236 #define METRIC 50. /* min channel metric */
237 #define PANIC 1440 /* panic timeout (m) */
238 #define HOLD 30 /* reach hold (m) */
241 * Hex extension codes (>= 16)
243 #define HEX_MISS 16 /* miss _ */
244 #define HEX_SOFT 17 /* soft error * */
245 #define HEX_HARD 18 /* hard error = */
248 * Status bits (status)
250 #define RUNT 0x0001 /* runt burst */
251 #define NOISE 0x0002 /* noise burst */
252 #define BFRAME 0x0004 /* invalid format B frame sync */
253 #define BFORMAT 0x0008 /* invalid format B data */
254 #define AFRAME 0x0010 /* invalid format A frame sync */
255 #define AFORMAT 0x0020 /* invalid format A data */
256 #define DECODE 0x0040 /* invalid data decode */
257 #define STAMP 0x0080 /* too few timestamps */
258 #define AVALID 0x0100 /* valid A frame */
259 #define BVALID 0x0200 /* valid B frame */
260 #define INSYNC 0x0400 /* clock synchronized */
263 * Alarm status bits (alarm)
265 * These alarms are set at the end of a minute in which at least one
266 * burst was received. SYNERR is raised if the AFRAME or BFRAME status
267 * bits are set during the minute, FMTERR is raised if the AFORMAT or
268 * BFORMAT status bits are set, DECERR is raised if the DECODE status
269 * bit is set and TSPERR is raised if the STAMP status bit is set.
271 #define SYNERR 0x01 /* frame sync error */
272 #define FMTERR 0x02 /* data format error */
273 #define DECERR 0x04 /* data decoding error */
274 #define TSPERR 0x08 /* insufficient data */
276 #ifdef HAVE_AUDIO
278 * Maximum likelihood UART structure. There are eight of these
279 * corresponding to the number of phases.
281 struct surv {
282 double shift[12]; /* mark register */
283 double es_max, es_min; /* max/min envelope signals */
284 double dist; /* sample distance */
285 int uart; /* decoded character */
287 #endif /* HAVE_AUDIO */
289 #ifdef ICOM
291 * CHU station structure. There are three of these corresponding to the
292 * three frequencies.
294 struct xmtr {
295 double integ[ISTAGE]; /* circular integrator */
296 double metric; /* integrator sum */
297 int iptr; /* integrator pointer */
298 int probe; /* dwells since last probe */
300 #endif /* ICOM */
303 * CHU unit control structure
305 struct chuunit {
306 u_char decode[20][16]; /* maximum likelihood decoding matrix */
307 l_fp cstamp[BURST]; /* character timestamps */
308 l_fp tstamp[MAXSTAGE]; /* timestamp samples */
309 l_fp timestamp; /* current buffer timestamp */
310 l_fp laststamp; /* last buffer timestamp */
311 l_fp charstamp; /* character time as a l_fp */
312 int errflg; /* error flags */
313 int status; /* status bits */
314 char ident[5]; /* station ID and channel */
315 #ifdef ICOM
316 int fd_icom; /* ICOM file descriptor */
317 int chan; /* data channel */
318 int achan; /* active channel */
319 int dwell; /* dwell cycle */
320 struct xmtr xmtr[NCHAN]; /* station metric */
321 #endif /* ICOM */
324 * Character burst variables
326 int cbuf[BURST]; /* character buffer */
327 int ntstamp; /* number of timestamp samples */
328 int ndx; /* buffer start index */
329 int prevsec; /* previous burst second */
330 int burdist; /* burst distance */
331 int syndist; /* sync distance */
332 int burstcnt; /* format A bursts this minute */
335 * Format particulars
337 int leap; /* leap/dut code */
338 int dut; /* UTC1 correction */
339 int tai; /* TAI - UTC correction */
340 int dst; /* Canadian DST code */
342 #ifdef HAVE_AUDIO
344 * Audio codec variables
346 int fd_audio; /* audio port file descriptor */
347 double comp[SIZE]; /* decompanding table */
348 int port; /* codec port */
349 int gain; /* codec gain */
350 int mongain; /* codec monitor gain */
351 int clipcnt; /* sample clip count */
352 int seccnt; /* second interval counter */
355 * Modem variables
357 l_fp tick; /* audio sample increment */
358 double bpf[9]; /* IIR bandpass filter */
359 double disc[LAG]; /* discriminator shift register */
360 double lpf[27]; /* FIR lowpass filter */
361 double monitor; /* audio monitor */
362 double maxsignal; /* signal level */
363 int discptr; /* discriminator pointer */
366 * Maximum likelihood UART variables
368 double baud; /* baud interval */
369 struct surv surv[8]; /* UART survivor structures */
370 int decptr; /* decode pointer */
371 int dbrk; /* holdoff counter */
372 #endif /* HAVE_AUDIO */
376 * Function prototypes
378 static int chu_start P((int, struct peer *));
379 static void chu_shutdown P((int, struct peer *));
380 static void chu_receive P((struct recvbuf *));
381 static void chu_poll P((int, struct peer *));
384 * More function prototypes
386 static void chu_decode P((struct peer *, int));
387 static void chu_burst P((struct peer *));
388 static void chu_clear P((struct peer *));
389 static void chu_a P((struct peer *, int));
390 static void chu_b P((struct peer *, int));
391 static int chu_dist P((int, int));
392 static double chu_major P((struct peer *));
393 #ifdef HAVE_AUDIO
394 static void chu_uart P((struct surv *, double));
395 static void chu_rf P((struct peer *, double));
396 static void chu_gain P((struct peer *));
397 static void chu_audio_receive P((struct recvbuf *rbufp));
398 #endif /* HAVE_AUDIO */
399 #ifdef ICOM
400 static int chu_newchan P((struct peer *, double));
401 #endif /* ICOM */
402 static void chu_serial_receive P((struct recvbuf *rbufp));
405 * Global variables
407 static char hexchar[] = "0123456789abcdef_*=";
409 #ifdef ICOM
411 * Note the tuned frequencies are 1 kHz higher than the carrier. CHU
412 * transmits on USB with carrier so we can use AM and the narrow SSB
413 * filter.
415 static double qsy[NCHAN] = {3.330, 7.335, 14.670}; /* freq (MHz) */
416 #endif /* ICOM */
419 * Transfer vector
421 struct refclock refclock_chu = {
422 chu_start, /* start up driver */
423 chu_shutdown, /* shut down driver */
424 chu_poll, /* transmit poll message */
425 noentry, /* not used (old chu_control) */
426 noentry, /* initialize driver (not used) */
427 noentry, /* not used (old chu_buginfo) */
428 NOFLAGS /* not used */
433 * chu_start - open the devices and initialize data for processing
435 static int
436 chu_start(
437 int unit, /* instance number (not used) */
438 struct peer *peer /* peer structure pointer */
441 struct chuunit *up;
442 struct refclockproc *pp;
443 char device[20]; /* device name */
444 int fd; /* file descriptor */
445 #ifdef ICOM
446 int temp;
447 #endif /* ICOM */
448 #ifdef HAVE_AUDIO
449 int fd_audio; /* audio port file descriptor */
450 int i; /* index */
451 double step; /* codec adjustment */
454 * Open audio device.
456 fd_audio = audio_init(DEVICE_AUDIO, AUDIO_BUFSIZ, unit);
457 #ifdef DEBUG
458 if (fd_audio > 0 && debug)
459 audio_show();
460 #endif
463 * Open serial port in raw mode.
465 if (fd_audio > 0) {
466 fd = fd_audio;
467 } else {
468 sprintf(device, DEVICE, unit);
469 fd = refclock_open(device, SPEED232, LDISC_RAW);
471 #else /* HAVE_AUDIO */
474 * Open serial port in raw mode.
476 sprintf(device, DEVICE, unit);
477 fd = refclock_open(device, SPEED232, LDISC_RAW);
478 #endif /* HAVE_AUDIO */
479 if (fd <= 0)
480 return (0);
483 * Allocate and initialize unit structure
485 if (!(up = (struct chuunit *)
486 emalloc(sizeof(struct chuunit)))) {
487 close(fd);
488 return (0);
490 memset((char *)up, 0, sizeof(struct chuunit));
491 pp = peer->procptr;
492 pp->unitptr = (caddr_t)up;
493 pp->io.clock_recv = chu_receive;
494 pp->io.srcclock = (caddr_t)peer;
495 pp->io.datalen = 0;
496 pp->io.fd = fd;
497 if (!io_addclock(&pp->io)) {
498 close(fd);
499 free(up);
500 return (0);
504 * Initialize miscellaneous variables
506 peer->precision = PRECISION;
507 pp->clockdesc = DESCRIPTION;
508 strcpy(up->ident, "CHU");
509 memcpy(&peer->refid, up->ident, 4);
510 DTOLFP(CHAR, &up->charstamp);
511 #ifdef HAVE_AUDIO
514 * The companded samples are encoded sign-magnitude. The table
515 * contains all the 256 values in the interest of speed. We do
516 * this even if the audio codec is not available. C'est la lazy.
518 up->fd_audio = fd_audio;
519 up->gain = 127;
520 up->comp[0] = up->comp[OFFSET] = 0.;
521 up->comp[1] = 1; up->comp[OFFSET + 1] = -1.;
522 up->comp[2] = 3; up->comp[OFFSET + 2] = -3.;
523 step = 2.;
524 for (i = 3; i < OFFSET; i++) {
525 up->comp[i] = up->comp[i - 1] + step;
526 up->comp[OFFSET + i] = -up->comp[i];
527 if (i % 16 == 0)
528 step *= 2.;
530 DTOLFP(1. / SECOND, &up->tick);
531 #endif /* HAVE_AUDIO */
532 #ifdef ICOM
533 temp = 0;
534 #ifdef DEBUG
535 if (debug > 1)
536 temp = P_TRACE;
537 #endif
538 if (peer->ttl > 0) {
539 if (peer->ttl & 0x80)
540 up->fd_icom = icom_init("/dev/icom", B1200,
541 temp);
542 else
543 up->fd_icom = icom_init("/dev/icom", B9600,
544 temp);
546 if (up->fd_icom > 0) {
547 if (chu_newchan(peer, 0) != 0) {
548 NLOG(NLOG_SYNCEVENT | NLOG_SYSEVENT)
549 msyslog(LOG_NOTICE,
550 "icom: radio not found");
551 up->errflg = CEVNT_FAULT;
552 close(up->fd_icom);
553 up->fd_icom = 0;
554 } else {
555 NLOG(NLOG_SYNCEVENT | NLOG_SYSEVENT)
556 msyslog(LOG_NOTICE,
557 "icom: autotune enabled");
560 #endif /* ICOM */
561 return (1);
566 * chu_shutdown - shut down the clock
568 static void
569 chu_shutdown(
570 int unit, /* instance number (not used) */
571 struct peer *peer /* peer structure pointer */
574 struct chuunit *up;
575 struct refclockproc *pp;
577 pp = peer->procptr;
578 up = (struct chuunit *)pp->unitptr;
579 if (up == NULL)
580 return;
582 io_closeclock(&pp->io);
583 #ifdef ICOM
584 if (up->fd_icom > 0)
585 close(up->fd_icom);
586 #endif /* ICOM */
587 free(up);
592 * chu_receive - receive data from the audio or serial device
594 static void
595 chu_receive(
596 struct recvbuf *rbufp /* receive buffer structure pointer */
599 #ifdef HAVE_AUDIO
600 struct chuunit *up;
601 struct refclockproc *pp;
602 struct peer *peer;
604 peer = (struct peer *)rbufp->recv_srcclock;
605 pp = peer->procptr;
606 up = (struct chuunit *)pp->unitptr;
609 * If the audio codec is warmed up, the buffer contains codec
610 * samples which need to be demodulated and decoded into CHU
611 * characters using the software UART. Otherwise, the buffer
612 * contains CHU characters from the serial port, so the software
613 * UART is bypassed. In this case the CPU will probably run a
614 * few degrees cooler.
616 if (up->fd_audio > 0)
617 chu_audio_receive(rbufp);
618 else
619 chu_serial_receive(rbufp);
620 #else
621 chu_serial_receive(rbufp);
622 #endif /* HAVE_AUDIO */
626 #ifdef HAVE_AUDIO
628 * chu_audio_receive - receive data from the audio device
630 static void
631 chu_audio_receive(
632 struct recvbuf *rbufp /* receive buffer structure pointer */
635 struct chuunit *up;
636 struct refclockproc *pp;
637 struct peer *peer;
639 double sample; /* codec sample */
640 u_char *dpt; /* buffer pointer */
641 int bufcnt; /* buffer counter */
642 l_fp ltemp; /* l_fp temp */
644 peer = (struct peer *)rbufp->recv_srcclock;
645 pp = peer->procptr;
646 up = (struct chuunit *)pp->unitptr;
649 * Main loop - read until there ain't no more. Note codec
650 * samples are bit-inverted.
652 DTOLFP((double)rbufp->recv_length / SECOND, &ltemp);
653 L_SUB(&rbufp->recv_time, &ltemp);
654 up->timestamp = rbufp->recv_time;
655 dpt = rbufp->recv_buffer;
656 for (bufcnt = 0; bufcnt < rbufp->recv_length; bufcnt++) {
657 sample = up->comp[~*dpt++ & 0xff];
660 * Clip noise spikes greater than MAXAMP. If no clips,
661 * increase the gain a tad; if the clips are too high,
662 * decrease a tad.
664 if (sample > MAXAMP) {
665 sample = MAXAMP;
666 up->clipcnt++;
667 } else if (sample < -MAXAMP) {
668 sample = -MAXAMP;
669 up->clipcnt++;
671 chu_rf(peer, sample);
672 L_ADD(&up->timestamp, &up->tick);
675 * Once each second ride gain.
677 up->seccnt = (up->seccnt + 1) % SECOND;
678 if (up->seccnt == 0) {
679 pp->second = (pp->second + 1) % 60;
680 chu_gain(peer);
685 * Set the input port and monitor gain for the next buffer.
687 if (pp->sloppyclockflag & CLK_FLAG2)
688 up->port = 2;
689 else
690 up->port = 1;
691 if (pp->sloppyclockflag & CLK_FLAG3)
692 up->mongain = MONGAIN;
693 else
694 up->mongain = 0;
699 * chu_rf - filter and demodulate the FSK signal
701 * This routine implements a 300-baud Bell 103 modem with mark 2225 Hz
702 * and space 2025 Hz. It uses a bandpass filter followed by a soft
703 * limiter, FM discriminator and lowpass filter. A maximum likelihood
704 * decoder samples the baseband signal at eight times the baud rate and
705 * detects the start bit of each character.
707 * The filters are built for speed, which explains the rather clumsy
708 * code. Hopefully, the compiler will efficiently implement the move-
709 * and-muiltiply-and-add operations.
711 static void
712 chu_rf(
713 struct peer *peer, /* peer structure pointer */
714 double sample /* analog sample */
717 struct refclockproc *pp;
718 struct chuunit *up;
719 struct surv *sp;
722 * Local variables
724 double signal; /* bandpass signal */
725 double limit; /* limiter signal */
726 double disc; /* discriminator signal */
727 double lpf; /* lowpass signal */
728 double span; /* UART signal span */
729 double dist; /* UART signal distance */
730 int i, j;
732 pp = peer->procptr;
733 up = (struct chuunit *)pp->unitptr;
736 * Bandpass filter. 4th-order elliptic, 500-Hz bandpass centered
737 * at 2125 Hz. Passband ripple 0.3 dB, stopband ripple 50 dB.
739 signal = (up->bpf[8] = up->bpf[7]) * 5.844676e-01;
740 signal += (up->bpf[7] = up->bpf[6]) * 4.884860e-01;
741 signal += (up->bpf[6] = up->bpf[5]) * 2.704384e+00;
742 signal += (up->bpf[5] = up->bpf[4]) * 1.645032e+00;
743 signal += (up->bpf[4] = up->bpf[3]) * 4.644557e+00;
744 signal += (up->bpf[3] = up->bpf[2]) * 1.879165e+00;
745 signal += (up->bpf[2] = up->bpf[1]) * 3.522634e+00;
746 signal += (up->bpf[1] = up->bpf[0]) * 7.315738e-01;
747 up->bpf[0] = sample - signal;
748 signal = up->bpf[0] * 6.176213e-03
749 + up->bpf[1] * 3.156599e-03
750 + up->bpf[2] * 7.567487e-03
751 + up->bpf[3] * 4.344580e-03
752 + up->bpf[4] * 1.190128e-02
753 + up->bpf[5] * 4.344580e-03
754 + up->bpf[6] * 7.567487e-03
755 + up->bpf[7] * 3.156599e-03
756 + up->bpf[8] * 6.176213e-03;
758 up->monitor = signal / 4.; /* note monitor after filter */
761 * Soft limiter/discriminator. The 11-sample discriminator lag
762 * interval corresponds to three cycles of 2125 Hz, which
763 * requires the sample frequency to be 2125 * 11 / 3 = 7791.7
764 * Hz. The discriminator output varies +-0.5 interval for input
765 * frequency 2025-2225 Hz. However, we don't get to sample at
766 * this frequency, so the discriminator output is biased. Life
767 * at 8000 Hz sucks.
769 limit = signal;
770 if (limit > LIMIT)
771 limit = LIMIT;
772 else if (limit < -LIMIT)
773 limit = -LIMIT;
774 disc = up->disc[up->discptr] * -limit;
775 up->disc[up->discptr] = limit;
776 up->discptr = (up->discptr + 1 ) % LAG;
777 if (disc >= 0)
778 disc = SQRT(disc);
779 else
780 disc = -SQRT(-disc);
783 * Lowpass filter. Raised cosine, Ts = 1 / 300, beta = 0.1.
785 lpf = (up->lpf[26] = up->lpf[25]) * 2.538771e-02;
786 lpf += (up->lpf[25] = up->lpf[24]) * 1.084671e-01;
787 lpf += (up->lpf[24] = up->lpf[23]) * 2.003159e-01;
788 lpf += (up->lpf[23] = up->lpf[22]) * 2.985303e-01;
789 lpf += (up->lpf[22] = up->lpf[21]) * 4.003697e-01;
790 lpf += (up->lpf[21] = up->lpf[20]) * 5.028552e-01;
791 lpf += (up->lpf[20] = up->lpf[19]) * 6.028795e-01;
792 lpf += (up->lpf[19] = up->lpf[18]) * 6.973249e-01;
793 lpf += (up->lpf[18] = up->lpf[17]) * 7.831828e-01;
794 lpf += (up->lpf[17] = up->lpf[16]) * 8.576717e-01;
795 lpf += (up->lpf[16] = up->lpf[15]) * 9.183463e-01;
796 lpf += (up->lpf[15] = up->lpf[14]) * 9.631951e-01;
797 lpf += (up->lpf[14] = up->lpf[13]) * 9.907208e-01;
798 lpf += (up->lpf[13] = up->lpf[12]) * 1.000000e+00;
799 lpf += (up->lpf[12] = up->lpf[11]) * 9.907208e-01;
800 lpf += (up->lpf[11] = up->lpf[10]) * 9.631951e-01;
801 lpf += (up->lpf[10] = up->lpf[9]) * 9.183463e-01;
802 lpf += (up->lpf[9] = up->lpf[8]) * 8.576717e-01;
803 lpf += (up->lpf[8] = up->lpf[7]) * 7.831828e-01;
804 lpf += (up->lpf[7] = up->lpf[6]) * 6.973249e-01;
805 lpf += (up->lpf[6] = up->lpf[5]) * 6.028795e-01;
806 lpf += (up->lpf[5] = up->lpf[4]) * 5.028552e-01;
807 lpf += (up->lpf[4] = up->lpf[3]) * 4.003697e-01;
808 lpf += (up->lpf[3] = up->lpf[2]) * 2.985303e-01;
809 lpf += (up->lpf[2] = up->lpf[1]) * 2.003159e-01;
810 lpf += (up->lpf[1] = up->lpf[0]) * 1.084671e-01;
811 lpf += up->lpf[0] = disc * 2.538771e-02;
814 * Maximum likelihood decoder. The UART updates each of the
815 * eight survivors and determines the span, slice level and
816 * tentative decoded character. Valid 11-bit characters are
817 * framed so that bit 1 and bit 11 (stop bits) are mark and bit
818 * 2 (start bit) is space. When a valid character is found, the
819 * survivor with maximum distance determines the final decoded
820 * character.
822 up->baud += 1. / SECOND;
823 if (up->baud > 1. / (BAUD * 8.)) {
824 up->baud -= 1. / (BAUD * 8.);
825 sp = &up->surv[up->decptr];
826 span = sp->es_max - sp->es_min;
827 up->maxsignal += (span - up->maxsignal) / 80.;
828 if (up->dbrk > 0) {
829 up->dbrk--;
830 } else if ((sp->uart & 0x403) == 0x401 && span > 1000.)
832 dist = 0;
833 j = 0;
834 for (i = 0; i < 8; i++) {
835 if (up->surv[i].dist > dist) {
836 dist = up->surv[i].dist;
837 j = i;
840 chu_decode(peer, (up->surv[j].uart >> 2) &
841 0xff);
842 up->dbrk = 80;
844 up->decptr = (up->decptr + 1) % 8;
845 chu_uart(sp, -lpf * AGAIN);
851 * chu_uart - maximum likelihood UART
853 * This routine updates a shift register holding the last 11 envelope
854 * samples. It then computes the slice level and span over these samples
855 * and determines the tentative data bits and distance. The calling
856 * program selects over the last eight survivors the one with maximum
857 * distance to determine the decoded character.
859 static void
860 chu_uart(
861 struct surv *sp, /* survivor structure pointer */
862 double sample /* baseband signal */
865 double es_max, es_min; /* max/min envelope */
866 double slice; /* slice level */
867 double dist; /* distance */
868 double dtemp;
869 int i;
872 * Save the sample and shift right. At the same time, measure
873 * the maximum and minimum over all eleven samples.
875 es_max = -1e6;
876 es_min = 1e6;
877 sp->shift[0] = sample;
878 for (i = 11; i > 0; i--) {
879 sp->shift[i] = sp->shift[i - 1];
880 if (sp->shift[i] > es_max)
881 es_max = sp->shift[i];
882 if (sp->shift[i] < es_min)
883 es_min = sp->shift[i];
887 * Determine the slice level midway beteen the maximum and
888 * minimum and the span as the maximum less the minimum. Compute
889 * the distance on the assumption the first and last bits must
890 * be mark, the second space and the rest either mark or space.
892 slice = (es_max + es_min) / 2.;
893 dist = 0;
894 sp->uart = 0;
895 for (i = 1; i < 12; i++) {
896 sp->uart <<= 1;
897 dtemp = sp->shift[i];
898 if (dtemp > slice)
899 sp->uart |= 0x1;
900 if (i == 1 || i == 11) {
901 dist += dtemp - es_min;
902 } else if (i == 10) {
903 dist += es_max - dtemp;
904 } else {
905 if (dtemp > slice)
906 dist += dtemp - es_min;
907 else
908 dist += es_max - dtemp;
911 sp->es_max = es_max;
912 sp->es_min = es_min;
913 sp->dist = dist / (11 * (es_max - es_min));
915 #endif /* HAVE_AUDIO */
919 * chu_serial_receive - receive data from the serial device
921 static void
922 chu_serial_receive(
923 struct recvbuf *rbufp /* receive buffer structure pointer */
926 struct chuunit *up;
927 struct refclockproc *pp;
928 struct peer *peer;
930 u_char *dpt; /* receive buffer pointer */
932 peer = (struct peer *)rbufp->recv_srcclock;
933 pp = peer->procptr;
934 up = (struct chuunit *)pp->unitptr;
937 * Initialize pointers and read the timecode and timestamp.
939 up->timestamp = rbufp->recv_time;
940 dpt = (u_char *)&rbufp->recv_space;
941 chu_decode(peer, *dpt);
946 * chu_decode - decode the character data
948 static void
949 chu_decode(
950 struct peer *peer, /* peer structure pointer */
951 int hexhex /* data character */
954 struct refclockproc *pp;
955 struct chuunit *up;
957 l_fp tstmp; /* timestamp temp */
958 double dtemp;
960 pp = peer->procptr;
961 up = (struct chuunit *)pp->unitptr;
964 * If the interval since the last character is greater than the
965 * longest burst, process the last burst and start a new one. If
966 * the interval is less than this but greater than two
967 * characters, consider this a noise burst and reject it.
969 tstmp = up->timestamp;
970 if (L_ISZERO(&up->laststamp))
971 up->laststamp = up->timestamp;
972 L_SUB(&tstmp, &up->laststamp);
973 up->laststamp = up->timestamp;
974 LFPTOD(&tstmp, dtemp);
975 if (dtemp > BURST * CHAR) {
976 chu_burst(peer);
977 up->ndx = 0;
978 } else if (dtemp > 2.5 * CHAR) {
979 up->ndx = 0;
983 * Append the character to the current burst and append the
984 * timestamp to the timestamp list.
986 if (up->ndx < BURST) {
987 up->cbuf[up->ndx] = hexhex & 0xff;
988 up->cstamp[up->ndx] = up->timestamp;
989 up->ndx++;
996 * chu_burst - search for valid burst format
998 static void
999 chu_burst(
1000 struct peer *peer
1003 struct chuunit *up;
1004 struct refclockproc *pp;
1006 int i;
1008 pp = peer->procptr;
1009 up = (struct chuunit *)pp->unitptr;
1012 * Correlate a block of five characters with the next block of
1013 * five characters. The burst distance is defined as the number
1014 * of bits that match in the two blocks for format A and that
1015 * match the inverse for format B.
1017 if (up->ndx < MINCHAR) {
1018 up->status |= RUNT;
1019 return;
1021 up->burdist = 0;
1022 for (i = 0; i < 5 && i < up->ndx - 5; i++)
1023 up->burdist += chu_dist(up->cbuf[i], up->cbuf[i + 5]);
1026 * If the burst distance is at least MINDIST, this must be a
1027 * format A burst; if the value is not greater than -MINDIST, it
1028 * must be a format B burst. If the B burst is perfect, we
1029 * believe it; otherwise, it is a noise burst and of no use to
1030 * anybody.
1032 if (up->burdist >= MINDIST) {
1033 chu_a(peer, up->ndx);
1034 } else if (up->burdist <= -MINDIST) {
1035 chu_b(peer, up->ndx);
1036 } else {
1037 up->status |= NOISE;
1038 return;
1042 * If this is a valid burst, wait a guard time of ten seconds to
1043 * allow for more bursts, then arm the poll update routine to
1044 * process the minute. Don't do this if this is called from the
1045 * timer interrupt routine.
1047 if (peer->outdate != current_time)
1048 peer->nextdate = current_time + 10;
1053 * chu_b - decode format B burst
1055 static void
1056 chu_b(
1057 struct peer *peer,
1058 int nchar
1061 struct refclockproc *pp;
1062 struct chuunit *up;
1064 u_char code[11]; /* decoded timecode */
1065 char tbuf[80]; /* trace buffer */
1066 l_fp offset; /* timestamp offset */
1067 int i;
1069 pp = peer->procptr;
1070 up = (struct chuunit *)pp->unitptr;
1073 * In a format B burst, a character is considered valid only if
1074 * the first occurrence matches the last occurrence. The burst
1075 * is considered valid only if all characters are valid; that
1076 * is, only if the distance is 40. Note that once a valid frame
1077 * has been found errors are ignored.
1079 sprintf(tbuf, "chuB %04x %2d %2d ", up->status, nchar,
1080 -up->burdist);
1081 for (i = 0; i < nchar; i++)
1082 sprintf(&tbuf[strlen(tbuf)], "%02x", up->cbuf[i]);
1083 if (pp->sloppyclockflag & CLK_FLAG4)
1084 record_clock_stats(&peer->srcadr, tbuf);
1085 #ifdef DEBUG
1086 if (debug)
1087 printf("%s\n", tbuf);
1088 #endif
1089 if (up->burdist > -40) {
1090 up->status |= BFRAME;
1091 return;
1093 up->status |= BVALID;
1096 * Convert the burst data to internal format. If this succeeds,
1097 * save the timestamps for later.
1099 for (i = 0; i < 5; i++) {
1100 code[2 * i] = hexchar[up->cbuf[i] & 0xf];
1101 code[2 * i + 1] = hexchar[(up->cbuf[i] >>
1102 4) & 0xf];
1104 if (sscanf((char *)code, "%1x%1d%4d%2d%2x", &up->leap, &up->dut,
1105 &pp->year, &up->tai, &up->dst) != 5) {
1106 up->status |= BFORMAT;
1107 return;
1109 if (up->leap & 0x8)
1110 up->dut = -up->dut;
1111 offset.l_ui = 31;
1112 offset.l_f = 0;
1113 for (i = 0; i < nchar && i < 10; i++) {
1114 up->tstamp[up->ntstamp] = up->cstamp[i];
1115 L_SUB(&up->tstamp[up->ntstamp], &offset);
1116 L_ADD(&offset, &up->charstamp);
1117 if (up->ntstamp < MAXSTAGE - 1)
1118 up->ntstamp++;
1124 * chu_a - decode format A burst
1126 static void
1127 chu_a(
1128 struct peer *peer,
1129 int nchar
1132 struct refclockproc *pp;
1133 struct chuunit *up;
1135 char tbuf[80]; /* trace buffer */
1136 l_fp offset; /* timestamp offset */
1137 int val; /* distance */
1138 int temp;
1139 int i, j, k;
1141 pp = peer->procptr;
1142 up = (struct chuunit *)pp->unitptr;
1145 * Determine correct burst phase. There are three cases
1146 * corresponding to in-phase, one character early or one
1147 * character late. These cases are distinguished by the position
1148 * of the framing digits x6 at positions 0 and 5 and x3 at
1149 * positions 4 and 9. The correct phase is when the distance
1150 * relative to the framing digits is maximum. The burst is valid
1151 * only if the maximum distance is at least MINSYNC.
1153 up->syndist = k = 0;
1154 val = -16;
1155 for (i = -1; i < 2; i++) {
1156 temp = up->cbuf[i + 4] & 0xf;
1157 if (i >= 0)
1158 temp |= (up->cbuf[i] & 0xf) << 4;
1159 val = chu_dist(temp, 0x63);
1160 temp = (up->cbuf[i + 5] & 0xf) << 4;
1161 if (i + 9 < nchar)
1162 temp |= up->cbuf[i + 9] & 0xf;
1163 val += chu_dist(temp, 0x63);
1164 if (val > up->syndist) {
1165 up->syndist = val;
1166 k = i;
1169 temp = (up->cbuf[k + 4] >> 4) & 0xf;
1170 if (temp > 9 || k + 9 >= nchar || temp != ((up->cbuf[k + 9] >>
1171 4) & 0xf))
1172 temp = 0;
1173 #ifdef HAVE_AUDIO
1174 if (up->fd_audio)
1175 sprintf(tbuf, "chuA %04x %4.0f %2d %2d %2d %2d %1d ",
1176 up->status, up->maxsignal, nchar, up->burdist, k,
1177 up->syndist, temp);
1178 else
1179 sprintf(tbuf, "chuA %04x %2d %2d %2d %2d %1d ",
1180 up->status, nchar, up->burdist, k, up->syndist,
1181 temp);
1183 #else
1184 sprintf(tbuf, "chuA %04x %2d %2d %2d %2d %1d ", up->status,
1185 nchar, up->burdist, k, up->syndist, temp);
1186 #endif /* HAVE_AUDIO */
1187 for (i = 0; i < nchar; i++)
1188 sprintf(&tbuf[strlen(tbuf)], "%02x",
1189 up->cbuf[i]);
1190 if (pp->sloppyclockflag & CLK_FLAG4)
1191 record_clock_stats(&peer->srcadr, tbuf);
1192 #ifdef DEBUG
1193 if (debug)
1194 printf("%s\n", tbuf);
1195 #endif
1196 if (up->syndist < MINSYNC) {
1197 up->status |= AFRAME;
1198 return;
1202 * A valid burst requires the first seconds number to match the
1203 * last seconds number. If so, the burst timestamps are
1204 * corrected to the current minute and saved for later
1205 * processing. In addition, the seconds decode is advanced from
1206 * the previous burst to the current one.
1208 if (temp != 0) {
1209 pp->second = 30 + temp;
1210 offset.l_ui = 30 + temp;
1211 offset.l_f = 0;
1212 i = 0;
1213 if (k < 0)
1214 offset = up->charstamp;
1215 else if (k > 0)
1216 i = 1;
1217 for (; i < nchar && i < k + 10; i++) {
1218 up->tstamp[up->ntstamp] = up->cstamp[i];
1219 L_SUB(&up->tstamp[up->ntstamp], &offset);
1220 L_ADD(&offset, &up->charstamp);
1221 if (up->ntstamp < MAXSTAGE - 1)
1222 up->ntstamp++;
1224 while (temp > up->prevsec) {
1225 for (j = 15; j > 0; j--) {
1226 up->decode[9][j] = up->decode[9][j - 1];
1227 up->decode[19][j] =
1228 up->decode[19][j - 1];
1230 up->decode[9][j] = up->decode[19][j] = 0;
1231 up->prevsec++;
1234 i = -(2 * k);
1235 for (j = 0; j < nchar; j++) {
1236 if (i < 0 || i > 18) {
1237 i += 2;
1238 continue;
1240 up->decode[i][up->cbuf[j] & 0xf]++;
1241 i++;
1242 up->decode[i][(up->cbuf[j] >> 4) & 0xf]++;
1243 i++;
1245 up->status |= AVALID;
1246 up->burstcnt++;
1251 * chu_poll - called by the transmit procedure
1253 static void
1254 chu_poll(
1255 int unit,
1256 struct peer *peer /* peer structure pointer */
1259 struct refclockproc *pp;
1260 struct chuunit *up;
1261 l_fp offset;
1262 char synchar, qual, leapchar;
1263 int minset, i;
1264 double dtemp;
1266 pp = peer->procptr;
1267 up = (struct chuunit *)pp->unitptr;
1268 if (pp->coderecv == pp->codeproc)
1269 up->errflg = CEVNT_TIMEOUT;
1270 else
1271 pp->polls++;
1274 * If once in sync and the radio has not been heard for awhile
1275 * (30 m), it is no longer reachable. If not heard in a long
1276 * while (one day), turn out the lights and start from scratch.
1278 minset = ((current_time - peer->update) + 30) / 60;
1279 if (up->status & INSYNC) {
1280 if (minset > PANIC)
1281 up->status = 0;
1282 else if (minset <= HOLD)
1283 peer->reach |= 1;
1287 * Process the last burst, if still in the burst buffer.
1288 * Don't mess with anything if nothing has been heard. If the
1289 * minute contains a valid A frame and valid B frame, assume
1290 * synchronized; however, believe the time only if within metric
1291 * threshold. Note the quality indicator is only for
1292 * diagnostics; the data are used only if in sync and above
1293 * metric threshold.
1295 chu_burst(peer);
1296 if (up->burstcnt == 0) {
1297 #ifdef ICOM
1298 chu_newchan(peer, 0);
1299 #endif /* ICOM */
1300 return;
1302 dtemp = chu_major(peer);
1303 qual = 0;
1304 if (up->status & (BFRAME | AFRAME))
1305 qual |= SYNERR;
1306 if (up->status & (BFORMAT | AFORMAT))
1307 qual |= FMTERR;
1308 if (up->status & DECODE)
1309 qual |= DECERR;
1310 if (up->status & STAMP)
1311 qual |= TSPERR;
1312 if (up->status & AVALID && up->status & BVALID)
1313 up->status |= INSYNC;
1314 synchar = leapchar = ' ';
1315 if (!(up->status & INSYNC)) {
1316 pp->leap = LEAP_NOTINSYNC;
1317 synchar = '?';
1318 } else if (up->leap & 0x2) {
1319 pp->leap = LEAP_ADDSECOND;
1320 leapchar = 'L';
1321 } else if (up->leap & 0x4) {
1322 pp->leap = LEAP_DELSECOND;
1323 leapchar = 'l';
1324 } else {
1325 pp->leap = LEAP_NOWARNING;
1327 #ifdef HAVE_AUDIO
1328 if (up->fd_audio)
1329 sprintf(pp->a_lastcode,
1330 "%c%1X %04d %3d %02d:%02d:%02d %c%x %+d %d %d %s %.0f %d",
1331 synchar, qual, pp->year, pp->day, pp->hour,
1332 pp->minute, pp->second, leapchar, up->dst, up->dut,
1333 minset, up->gain, up->ident, dtemp, up->ntstamp);
1334 else
1335 sprintf(pp->a_lastcode,
1336 "%c%1X %04d %3d %02d:%02d:%02d %c%x %+d %d %s %.0f %d",
1337 synchar, qual, pp->year, pp->day, pp->hour,
1338 pp->minute, pp->second, leapchar, up->dst, up->dut,
1339 minset, up->ident, dtemp, up->ntstamp);
1340 #else
1341 sprintf(pp->a_lastcode,
1342 "%c%1X %04d %3d %02d:%02d:%02d %c%x %+d %d %s %.0f %d",
1343 synchar, qual, pp->year, pp->day, pp->hour, pp->minute,
1344 pp->second, leapchar, up->dst, up->dut, minset, up->ident,
1345 dtemp, up->ntstamp);
1346 #endif /* HAVE_AUDIO */
1347 pp->lencode = strlen(pp->a_lastcode);
1350 * If in sync and the signal metric is above threshold, the
1351 * timecode is ipso fatso valid and can be selected to
1352 * discipline the clock. Be sure not to leave stray timestamps
1353 * around if signals are too weak or the clock time is invalid.
1355 if (up->status & INSYNC && dtemp > METRIC) {
1356 if (!clocktime(pp->day, pp->hour, pp->minute, 0, GMT,
1357 up->tstamp[0].l_ui, &pp->yearstart, &offset.l_ui)) {
1358 up->errflg = CEVNT_BADTIME;
1359 } else {
1360 offset.l_uf = 0;
1361 for (i = 0; i < up->ntstamp; i++)
1362 refclock_process_offset(pp, offset,
1363 up->tstamp[i], FUDGE +
1364 pp->fudgetime1);
1365 pp->lastref = up->timestamp;
1366 refclock_receive(peer);
1368 record_clock_stats(&peer->srcadr, pp->a_lastcode);
1369 } else if (pp->sloppyclockflag & CLK_FLAG4) {
1370 record_clock_stats(&peer->srcadr, pp->a_lastcode);
1372 #ifdef DEBUG
1373 if (debug)
1374 printf("chu: timecode %d %s\n", pp->lencode,
1375 pp->a_lastcode);
1376 #endif
1377 #ifdef ICOM
1378 chu_newchan(peer, dtemp);
1379 #endif /* ICOM */
1380 chu_clear(peer);
1381 if (up->errflg)
1382 refclock_report(peer, up->errflg);
1383 up->errflg = 0;
1388 * chu_major - majority decoder
1390 static double
1391 chu_major(
1392 struct peer *peer /* peer structure pointer */
1395 struct refclockproc *pp;
1396 struct chuunit *up;
1398 u_char code[11]; /* decoded timecode */
1399 int mindist; /* minimum distance */
1400 int val1, val2; /* maximum distance */
1401 int synchar; /* stray cat */
1402 int temp;
1403 int i, j, k;
1405 pp = peer->procptr;
1406 up = (struct chuunit *)pp->unitptr;
1409 * Majority decoder. Each burst encodes two replications at each
1410 * digit position in the timecode. Each row of the decoding
1411 * matrix encodes the number of occurrences of each digit found
1412 * at the corresponding position. The maximum over all
1413 * occurrences at each position is the distance for this
1414 * position and the corresponding digit is the maximum
1415 * likelihood candidate. If the distance is zero, assume a miss
1416 * '_'; if the distance is not more than half the total number
1417 * of occurrences, assume a soft error '*'; if two different
1418 * digits with the same distance are found, assume a hard error
1419 * '='. These will later cause a format error when the timecode
1420 * is interpreted. The decoding distance is defined as the
1421 * minimum distance over the first nine digits. The tenth digit
1422 * varies over the seconds, so we don't count it.
1424 mindist = 16;
1425 for (i = 0; i < 9; i++) {
1426 val1 = val2 = 0;
1427 k = 0;
1428 for (j = 0; j < 16; j++) {
1429 temp = up->decode[i][j] + up->decode[i + 10][j];
1430 if (temp > val1) {
1431 val2 = val1;
1432 val1 = temp;
1433 k = j;
1436 if (val1 == 0)
1437 code[i] = HEX_MISS;
1438 else if (val1 == val2)
1439 code[i] = HEX_HARD;
1440 else if (val1 <= up->burstcnt)
1441 code[i] = HEX_SOFT;
1442 else
1443 code[i] = k;
1444 if (val1 < mindist)
1445 mindist = val1;
1446 code[i] = hexchar[code[i]];
1448 code[i] = 0;
1451 * A valid timecode requires a minimum distance at least half
1452 * the total number of occurrences. A valid timecode also
1453 * requires at least 20 valid timestamps.
1455 if (up->burstcnt < MINBURST || mindist < up->burstcnt)
1456 up->status |= DECODE;
1457 if (up->ntstamp < MINSTAMP)
1458 up->status |= STAMP;
1461 * Compute the timecode timestamp from the days, hours and
1462 * minutes of the timecode. Use clocktime() for the aggregate
1463 * minutes and the minute offset computed from the burst
1464 * seconds. Note that this code relies on the filesystem time
1465 * for the years and does not use the years of the timecode.
1467 if (sscanf((char *)code, "%1x%3d%2d%2d", &synchar, &pp->day,
1468 &pp->hour, &pp->minute) != 4) {
1469 up->status |= AFORMAT;
1470 return (0);
1472 if (up->status & (DECODE | STAMP)) {
1473 up->errflg = CEVNT_BADREPLY;
1474 return (0);
1476 return (mindist * 100. / (2. * up->burstcnt));
1481 * chu_clear - clear decoding matrix
1483 static void
1484 chu_clear(
1485 struct peer *peer /* peer structure pointer */
1488 struct refclockproc *pp;
1489 struct chuunit *up;
1490 int i, j;
1492 pp = peer->procptr;
1493 up = (struct chuunit *)pp->unitptr;
1496 * Clear stuff for the minute.
1498 up->ndx = up->prevsec = 0;
1499 up->burstcnt = up->ntstamp = 0;
1500 up->status &= INSYNC;
1501 for (i = 0; i < 20; i++) {
1502 for (j = 0; j < 16; j++)
1503 up->decode[i][j] = 0;
1507 #ifdef ICOM
1509 * chu_newchan - called once per minute to find the best channel;
1510 * returns zero on success, nonzero if ICOM error.
1512 static int
1513 chu_newchan(
1514 struct peer *peer,
1515 double met
1518 struct chuunit *up;
1519 struct refclockproc *pp;
1520 struct xmtr *sp;
1521 char tbuf[80]; /* trace buffer */
1522 int rval;
1523 double metric;
1524 int i, j;
1526 pp = peer->procptr;
1527 up = (struct chuunit *)pp->unitptr;
1530 * The radio can be tuned to three channels: 0 (3330 kHz), 1
1531 * (7335 kHz) and 2 (14670 kHz). There are five one-minute
1532 * dwells in each cycle. During the first dwell the radio is
1533 * tuned to one of three probe channels; during the remaining
1534 * four dwells the radio is tuned to the data channel. The probe
1535 * channel is selects as the least recently used. At the end of
1536 * each dwell the channel metrics are measured and the highest
1537 * one is selected as the data channel.
1539 if (up->fd_icom <= 0)
1540 return (0);
1542 sp = &up->xmtr[up->achan];
1543 sp->metric -= sp->integ[sp->iptr];
1544 sp->integ[sp->iptr] = met;
1545 sp->metric += sp->integ[sp->iptr];
1546 sp->iptr = (sp->iptr + 1) % ISTAGE;
1547 metric = 0;
1548 j = 0;
1549 for (i = 0; i < NCHAN; i++) {
1550 up->xmtr[i].probe++;
1551 if (i == up->achan)
1552 up->xmtr[i].probe = 0;
1553 if (up->xmtr[i].metric < metric)
1554 continue;
1555 metric = up->xmtr[i].metric;
1556 j = i;
1558 if (j != up->chan && metric > 0) {
1559 up->chan = j;
1560 sprintf(tbuf, "chu: QSY to %.3f MHz metric %.0f",
1561 qsy[up->chan], metric);
1562 if (pp->sloppyclockflag & CLK_FLAG4)
1563 record_clock_stats(&peer->srcadr, tbuf);
1564 #ifdef DEBUG
1565 if (debug)
1566 printf("%s\n", tbuf);
1567 #endif
1571 * Start the next dwell. We speed up the initial sync a little.
1572 * If not in sync and no bursts were heard the previous dwell,
1573 * restart the probe.
1575 rval = 0;
1576 if (up->burstcnt == 0 && !(up->status & INSYNC))
1577 up->dwell = 0;
1578 #ifdef DEBUG
1579 if (debug)
1580 printf(
1581 "chu: at %ld dwell %d achan %d metric %.0f chan %d\n",
1582 current_time, up->dwell, up->achan, sp->metric,
1583 up->chan);
1584 #endif
1585 if (up->dwell == 0) {
1586 rval = 0;
1587 for (i = 0; i < NCHAN; i++) {
1588 if (up->xmtr[i].probe < rval)
1589 continue;
1590 rval = up->xmtr[i].probe;
1591 up->achan = i;
1593 rval = icom_freq(up->fd_icom, peer->ttl & 0x7f,
1594 qsy[up->achan] + TUNE);
1595 #ifdef DEBUG
1596 if (debug)
1597 printf("chu: at %ld probe channel %d\n",
1598 current_time, up->achan);
1599 #endif
1600 } else {
1601 if (up->achan != up->chan) {
1602 rval = icom_freq(up->fd_icom, peer->ttl & 0x7f,
1603 qsy[up->chan] + TUNE);
1604 up->achan = up->chan;
1607 sprintf(up->ident, "CHU%d", up->achan);
1608 memcpy(&peer->refid, up->ident, 4);
1609 up->dwell = (up->dwell + 1) % DWELL;
1610 return (rval);
1612 #endif /* ICOM */
1615 * chu_dist - determine the distance of two octet arguments
1617 static int
1618 chu_dist(
1619 int x, /* an octet of bits */
1620 int y /* another octet of bits */
1623 int val; /* bit count */
1624 int temp;
1625 int i;
1628 * The distance is determined as the weight of the exclusive OR
1629 * of the two arguments. The weight is determined by the number
1630 * of one bits in the result. Each one bit increases the weight,
1631 * while each zero bit decreases it.
1633 temp = x ^ y;
1634 val = 0;
1635 for (i = 0; i < 8; i++) {
1636 if ((temp & 0x1) == 0)
1637 val++;
1638 else
1639 val--;
1640 temp >>= 1;
1642 return (val);
1646 #ifdef HAVE_AUDIO
1648 * chu_gain - adjust codec gain
1650 * This routine is called once each second. If the signal envelope
1651 * amplitude is too low, the codec gain is bumped up by four units; if
1652 * too high, it is bumped down. The decoder is relatively insensitive to
1653 * amplitude, so this crudity works just fine. The input port is set and
1654 * the error flag is cleared, mostly to be ornery.
1656 static void
1657 chu_gain(
1658 struct peer *peer /* peer structure pointer */
1661 struct refclockproc *pp;
1662 struct chuunit *up;
1664 pp = peer->procptr;
1665 up = (struct chuunit *)pp->unitptr;
1668 * Apparently, the codec uses only the high order bits of the
1669 * gain control field. Thus, it may take awhile for changes to
1670 * wiggle the hardware bits.
1672 if (up->clipcnt == 0) {
1673 up->gain += 4;
1674 if (up->gain > MAXGAIN)
1675 up->gain = MAXGAIN;
1676 } else if (up->clipcnt > MAXCLP) {
1677 up->gain -= 4;
1678 if (up->gain < 0)
1679 up->gain = 0;
1681 audio_gain(up->gain, up->mongain, up->port);
1682 up->clipcnt = 0;
1684 #endif /* HAVE_AUDIO */
1687 #else
1688 int refclock_chu_bs;
1689 #endif /* REFCLOCK */