Expand PMF_FN_* macros.
[netbsd-mini2440.git] / dist / ntp / ntpd / refclock_wwv.c
blob621132c0f6bc681dcddb42be9127e77c1db857fe
1 /* $NetBSD: refclock_wwv.c,v 1.5 2006/06/11 19:34:13 kardel Exp $ */
3 /*
4 * refclock_wwv - clock driver for NIST WWV/H time/frequency station
5 */
6 #ifdef HAVE_CONFIG_H
7 #include <config.h>
8 #endif
10 #if defined(REFCLOCK) && defined(CLOCK_WWV)
12 #include "ntpd.h"
13 #include "ntp_io.h"
14 #include "ntp_refclock.h"
15 #include "ntp_calendar.h"
16 #include "ntp_stdlib.h"
17 #include "audio.h"
19 #include <stdio.h>
20 #include <ctype.h>
21 #include <math.h>
22 #ifdef HAVE_SYS_IOCTL_H
23 # include <sys/ioctl.h>
24 #endif /* HAVE_SYS_IOCTL_H */
26 #define ICOM 1
28 #ifdef ICOM
29 #include "icom.h"
30 #endif /* ICOM */
33 * Audio WWV/H demodulator/decoder
35 * This driver synchronizes the computer time using data encoded in
36 * radio transmissions from NIST time/frequency stations WWV in Boulder,
37 * CO, and WWVH in Kauai, HI. Transmissions are made continuously on
38 * 2.5, 5, 10 and 15 MHz from WWV and WWVH, and 20 MHz from WWV. An
39 * ordinary AM 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 weasons, both day and night.
44 * The driver receives, demodulates and decodes the radio signals when
45 * connected to the audio codec of a workstation running Solaris, SunOS
46 * FreeBSD or Linux, and with a little help, other workstations with
47 * similar codecs or sound cards. In this implementation, only one audio
48 * driver and codec can be supported on a single machine.
50 * The demodulation and decoding algorithms used in this driver are
51 * based on those developed for the TAPR DSP93 development board and the
52 * TI 320C25 digital signal processor described in: Mills, D.L. A
53 * precision radio clock for WWV transmissions. Electrical Engineering
54 * Report 97-8-1, University of Delaware, August 1997, 25 pp., available
55 * from www.eecis.udel.edu/~mills/reports.html. The algorithms described
56 * in this report have been modified somewhat to improve performance
57 * under weak signal conditions and to provide an automatic station
58 * identification feature.
60 * The ICOM code is normally compiled in the driver. It isn't used,
61 * unless the mode keyword on the server configuration command specifies
62 * a nonzero ICOM ID select code. The C-IV trace is turned on if the
63 * debug level is greater than one.
65 * Fudge factors
67 * Fudge flag4 causes the dubugging output described above to be
68 * recorded in the clockstats file. Fudge flag2 selects the audio input
69 * port, where 0 is the mike port (default) and 1 is the line-in port.
70 * It does not seem useful to select the compact disc player port. Fudge
71 * flag3 enables audio monitoring of the input signal. For this purpose,
72 * the monitor gain is set to a default value.
75 * General definitions. These ordinarily do not need to be changed.
77 #define DEVICE_AUDIO "/dev/audio" /* audio device name */
78 #define AUDIO_BUFSIZ 320 /* audio buffer size (50 ms) */
79 #define PRECISION (-10) /* precision assumed (about 1 ms) */
80 #define DESCRIPTION "WWV/H Audio Demodulator/Decoder" /* WRU */
81 #define SECOND 8000 /* second epoch (sample rate) (Hz) */
82 #define MINUTE (SECOND * 60) /* minute epoch */
83 #define OFFSET 128 /* companded sample offset */
84 #define SIZE 256 /* decompanding table size */
85 #define MAXAMP 6000. /* max signal level reference */
86 #define MAXCLP 100 /* max clips above reference per s */
87 #define MAXSNR 40. /* max SNR reference */
88 #define MAXFREQ 1.5 /* max frequency tolerance (187 PPM) */
89 #define DATCYC 170 /* data filter cycles */
90 #define DATSIZ (DATCYC * MS) /* data filter size */
91 #define SYNCYC 800 /* minute filter cycles */
92 #define SYNSIZ (SYNCYC * MS) /* minute filter size */
93 #define TCKCYC 5 /* tick filter cycles */
94 #define TCKSIZ (TCKCYC * MS) /* tick filter size */
95 #define NCHAN 5 /* number of radio channels */
96 #define AUDIO_PHI 5e-6 /* dispersion growth factor */
99 * Tunable parameters. The DGAIN parameter can be changed to fit the
100 * audio response of the radio at 100 Hz. The WWV/WWVH data subcarrier
101 * is transmitted at about 20 percent percent modulation; the matched
102 * filter boosts it by a factor of 17 and the receiver response does
103 * what it does. The compromise value works for ICOM radios. If the
104 * radio is not tunable, the DCHAN parameter can be changed to fit the
105 * expected best propagation frequency: higher if further from the
106 * transmitter, lower if nearer. The compromise value works for the US
107 * right coast. The FREQ_OFFSET parameter can be used as a frequency
108 * vernier to correct codec requency if greater than MAXFREQ.
110 #define DCHAN 3 /* default radio channel (15 Mhz) */
111 #define DGAIN 5. /* subcarrier gain */
112 #define FREQ_OFFSET 0. /* codec frequency correction (PPM) */
115 * General purpose status bits (status)
117 * SELV and/or SELH are set when WWV or WWVH have been heard and cleared
118 * on signal loss. SSYNC is set when the second sync pulse has been
119 * acquired and cleared by signal loss. MSYNC is set when the minute
120 * sync pulse has been acquired. DSYNC is set when the units digit has
121 * has reached the threshold and INSYNC is set when all nine digits have
122 * reached the threshold. The MSYNC, DSYNC and INSYNC bits are cleared
123 * only by timeout, upon which the driver starts over from scratch.
125 * DGATE is lit if the data bit amplitude or SNR is below thresholds and
126 * BGATE is lit if the pulse width amplitude or SNR is below thresolds.
127 * LEPSEC is set during the last minute of the leap day. At the end of
128 * this minute the driver inserts second 60 in the seconds state machine
129 * and the minute sync slips a second.
131 #define MSYNC 0x0001 /* minute epoch sync */
132 #define SSYNC 0x0002 /* second epoch sync */
133 #define DSYNC 0x0004 /* minute units sync */
134 #define INSYNC 0x0008 /* clock synchronized */
135 #define FGATE 0x0010 /* frequency gate */
136 #define DGATE 0x0020 /* data pulse amplitude error */
137 #define BGATE 0x0040 /* data pulse width error */
138 #define LEPSEC 0x1000 /* leap minute */
141 * Station scoreboard bits
143 * These are used to establish the signal quality for each of the five
144 * frequencies and two stations.
146 #define SELV 0x0100 /* WWV station select */
147 #define SELH 0x0200 /* WWVH station select */
150 * Alarm status bits (alarm)
152 * These bits indicate various alarm conditions, which are decoded to
153 * form the quality character included in the timecode.
155 #define CMPERR 1 /* digit or misc bit compare error */
156 #define LOWERR 2 /* low bit or digit amplitude or SNR */
157 #define NINERR 4 /* less than nine digits in minute */
158 #define SYNERR 8 /* not tracking second sync */
161 * Watchcat timeouts (watch)
163 * If these timeouts expire, the status bits are mashed to zero and the
164 * driver starts from scratch. Suitably more refined procedures may be
165 * developed in future. All these are in minutes.
167 #define ACQSN 6 /* station acquisition timeout */
168 #define DATA 15 /* unit minutes timeout */
169 #define SYNCH 40 /* station sync timeout */
170 #define PANIC (2 * 1440) /* panic timeout */
173 * Thresholds. These establish the minimum signal level, minimum SNR and
174 * maximum jitter thresholds which establish the error and false alarm
175 * rates of the driver. The values defined here may be on the
176 * adventurous side in the interest of the highest sensitivity.
178 #define MTHR 13. /* minute sync gate (percent) */
179 #define TTHR 50. /* minute sync threshold (percent) */
180 #define AWND 20 /* minute sync jitter threshold (ms) */
181 #define ATHR 2500. /* QRZ minute sync threshold */
182 #define ASNR 20. /* QRZ minute sync SNR threshold (dB) */
183 #define QTHR 2500. /* QSY minute sync threshold */
184 #define QSNR 20. /* QSY minute sync SNR threshold (dB) */
185 #define STHR 2500. /* second sync threshold */
186 #define SSNR 15. /* second sync SNR threshold (dB) */
187 #define SCMP 10 /* second sync compare threshold */
188 #define DTHR 1000. /* bit threshold */
189 #define DSNR 10. /* bit SNR threshold (dB) */
190 #define AMIN 3 /* min bit count */
191 #define AMAX 6 /* max bit count */
192 #define BTHR 1000. /* digit threshold */
193 #define BSNR 3. /* digit likelihood threshold (dB) */
194 #define BCMP 3 /* digit compare threshold */
195 #define MAXERR 40 /* maximum error alarm */
198 * Tone frequency definitions. The increments are for 4.5-deg sine
199 * table.
201 #define MS (SECOND / 1000) /* samples per millisecond */
202 #define IN100 ((100 * 80) / SECOND) /* 100 Hz increment */
203 #define IN1000 ((1000 * 80) / SECOND) /* 1000 Hz increment */
204 #define IN1200 ((1200 * 80) / SECOND) /* 1200 Hz increment */
207 * Acquisition and tracking time constants
209 #define MINAVG 8 /* min averaging time */
210 #define MAXAVG 1024 /* max averaging time */
211 #define FCONST 3 /* frequency time constant */
212 #define TCONST 16 /* data bit/digit time constant */
215 * Miscellaneous status bits (misc)
217 * These bits correspond to designated bits in the WWV/H timecode. The
218 * bit probabilities are exponentially averaged over several minutes and
219 * processed by a integrator and threshold.
221 #define DUT1 0x01 /* 56 DUT .1 */
222 #define DUT2 0x02 /* 57 DUT .2 */
223 #define DUT4 0x04 /* 58 DUT .4 */
224 #define DUTS 0x08 /* 50 DUT sign */
225 #define DST1 0x10 /* 55 DST1 leap warning */
226 #define DST2 0x20 /* 2 DST2 DST1 delayed one day */
227 #define SECWAR 0x40 /* 3 leap second warning */
230 * The on-time synchronization point for the driver is the second epoch
231 * sync pulse produced by the FIR matched filters. As the 5-ms delay of
232 * these filters is compensated, the program delay is 1.1 ms due to the
233 * 600-Hz IIR bandpass filter. The measured receiver delay is 4.7 ms and
234 * the codec delay less than 0.2 ms. The additional propagation delay
235 * specific to each receiver location can be programmed in the fudge
236 * time1 and time2 values for WWV and WWVH, respectively.
238 #define PDELAY (.0011 + .0047 + .0002) /* net system delay (s) */
241 * Table of sine values at 4.5-degree increments. This is used by the
242 * synchronous matched filter demodulators.
244 double sintab[] = {
245 0.000000e+00, 7.845910e-02, 1.564345e-01, 2.334454e-01, /* 0-3 */
246 3.090170e-01, 3.826834e-01, 4.539905e-01, 5.224986e-01, /* 4-7 */
247 5.877853e-01, 6.494480e-01, 7.071068e-01, 7.604060e-01, /* 8-11 */
248 8.090170e-01, 8.526402e-01, 8.910065e-01, 9.238795e-01, /* 12-15 */
249 9.510565e-01, 9.723699e-01, 9.876883e-01, 9.969173e-01, /* 16-19 */
250 1.000000e+00, 9.969173e-01, 9.876883e-01, 9.723699e-01, /* 20-23 */
251 9.510565e-01, 9.238795e-01, 8.910065e-01, 8.526402e-01, /* 24-27 */
252 8.090170e-01, 7.604060e-01, 7.071068e-01, 6.494480e-01, /* 28-31 */
253 5.877853e-01, 5.224986e-01, 4.539905e-01, 3.826834e-01, /* 32-35 */
254 3.090170e-01, 2.334454e-01, 1.564345e-01, 7.845910e-02, /* 36-39 */
255 -0.000000e+00, -7.845910e-02, -1.564345e-01, -2.334454e-01, /* 40-43 */
256 -3.090170e-01, -3.826834e-01, -4.539905e-01, -5.224986e-01, /* 44-47 */
257 -5.877853e-01, -6.494480e-01, -7.071068e-01, -7.604060e-01, /* 48-51 */
258 -8.090170e-01, -8.526402e-01, -8.910065e-01, -9.238795e-01, /* 52-55 */
259 -9.510565e-01, -9.723699e-01, -9.876883e-01, -9.969173e-01, /* 56-59 */
260 -1.000000e+00, -9.969173e-01, -9.876883e-01, -9.723699e-01, /* 60-63 */
261 -9.510565e-01, -9.238795e-01, -8.910065e-01, -8.526402e-01, /* 64-67 */
262 -8.090170e-01, -7.604060e-01, -7.071068e-01, -6.494480e-01, /* 68-71 */
263 -5.877853e-01, -5.224986e-01, -4.539905e-01, -3.826834e-01, /* 72-75 */
264 -3.090170e-01, -2.334454e-01, -1.564345e-01, -7.845910e-02, /* 76-79 */
265 0.000000e+00}; /* 80 */
268 * Decoder operations at the end of each second are driven by a state
269 * machine. The transition matrix consists of a dispatch table indexed
270 * by second number. Each entry in the table contains a case switch
271 * number and argument.
273 struct progx {
274 int sw; /* case switch number */
275 int arg; /* argument */
279 * Case switch numbers
281 #define IDLE 0 /* no operation */
282 #define COEF 1 /* BCD bit */
283 #define COEF1 2 /* BCD bit for minute unit */
284 #define COEF2 3 /* BCD bit not used */
285 #define DECIM9 4 /* BCD digit 0-9 */
286 #define DECIM6 5 /* BCD digit 0-6 */
287 #define DECIM3 6 /* BCD digit 0-3 */
288 #define DECIM2 7 /* BCD digit 0-2 */
289 #define MSCBIT 8 /* miscellaneous bit */
290 #define MSC20 9 /* miscellaneous bit */
291 #define MSC21 10 /* QSY probe channel */
292 #define MIN1 11 /* latch time */
293 #define MIN2 12 /* leap second */
294 #define SYNC2 13 /* latch minute sync pulse */
295 #define SYNC3 14 /* latch data pulse */
298 * Offsets in decoding matrix
300 #define MN 0 /* minute digits (2) */
301 #define HR 2 /* hour digits (2) */
302 #define DA 4 /* day digits (3) */
303 #define YR 7 /* year digits (2) */
305 struct progx progx[] = {
306 {SYNC2, 0}, /* 0 latch minute sync pulse */
307 {SYNC3, 0}, /* 1 latch data pulse */
308 {MSCBIT, DST2}, /* 2 dst2 */
309 {MSCBIT, SECWAR}, /* 3 lw */
310 {COEF, 0}, /* 4 1 year units */
311 {COEF, 1}, /* 5 2 */
312 {COEF, 2}, /* 6 4 */
313 {COEF, 3}, /* 7 8 */
314 {DECIM9, YR}, /* 8 */
315 {IDLE, 0}, /* 9 p1 */
316 {COEF1, 0}, /* 10 1 minute units */
317 {COEF1, 1}, /* 11 2 */
318 {COEF1, 2}, /* 12 4 */
319 {COEF1, 3}, /* 13 8 */
320 {DECIM9, MN}, /* 14 */
321 {COEF, 0}, /* 15 10 minute tens */
322 {COEF, 1}, /* 16 20 */
323 {COEF, 2}, /* 17 40 */
324 {COEF2, 3}, /* 18 80 (not used) */
325 {DECIM6, MN + 1}, /* 19 p2 */
326 {COEF, 0}, /* 20 1 hour units */
327 {COEF, 1}, /* 21 2 */
328 {COEF, 2}, /* 22 4 */
329 {COEF, 3}, /* 23 8 */
330 {DECIM9, HR}, /* 24 */
331 {COEF, 0}, /* 25 10 hour tens */
332 {COEF, 1}, /* 26 20 */
333 {COEF2, 2}, /* 27 40 (not used) */
334 {COEF2, 3}, /* 28 80 (not used) */
335 {DECIM2, HR + 1}, /* 29 p3 */
336 {COEF, 0}, /* 30 1 day units */
337 {COEF, 1}, /* 31 2 */
338 {COEF, 2}, /* 32 4 */
339 {COEF, 3}, /* 33 8 */
340 {DECIM9, DA}, /* 34 */
341 {COEF, 0}, /* 35 10 day tens */
342 {COEF, 1}, /* 36 20 */
343 {COEF, 2}, /* 37 40 */
344 {COEF, 3}, /* 38 80 */
345 {DECIM9, DA + 1}, /* 39 p4 */
346 {COEF, 0}, /* 40 100 day hundreds */
347 {COEF, 1}, /* 41 200 */
348 {COEF2, 2}, /* 42 400 (not used) */
349 {COEF2, 3}, /* 43 800 (not used) */
350 {DECIM3, DA + 2}, /* 44 */
351 {IDLE, 0}, /* 45 */
352 {IDLE, 0}, /* 46 */
353 {IDLE, 0}, /* 47 */
354 {IDLE, 0}, /* 48 */
355 {IDLE, 0}, /* 49 p5 */
356 {MSCBIT, DUTS}, /* 50 dut+- */
357 {COEF, 0}, /* 51 10 year tens */
358 {COEF, 1}, /* 52 20 */
359 {COEF, 2}, /* 53 40 */
360 {COEF, 3}, /* 54 80 */
361 {MSC20, DST1}, /* 55 dst1 */
362 {MSCBIT, DUT1}, /* 56 0.1 dut */
363 {MSCBIT, DUT2}, /* 57 0.2 */
364 {MSC21, DUT4}, /* 58 0.4 QSY probe channel */
365 {MIN1, 0}, /* 59 p6 latch time */
366 {MIN2, 0} /* 60 leap second */
370 * BCD coefficients for maximum likelihood digit decode
372 #define P15 1. /* max positive number */
373 #define N15 -1. /* max negative number */
376 * Digits 0-9
378 #define P9 (P15 / 4) /* mark (+1) */
379 #define N9 (N15 / 4) /* space (-1) */
381 double bcd9[][4] = {
382 {N9, N9, N9, N9}, /* 0 */
383 {P9, N9, N9, N9}, /* 1 */
384 {N9, P9, N9, N9}, /* 2 */
385 {P9, P9, N9, N9}, /* 3 */
386 {N9, N9, P9, N9}, /* 4 */
387 {P9, N9, P9, N9}, /* 5 */
388 {N9, P9, P9, N9}, /* 6 */
389 {P9, P9, P9, N9}, /* 7 */
390 {N9, N9, N9, P9}, /* 8 */
391 {P9, N9, N9, P9}, /* 9 */
392 {0, 0, 0, 0} /* backstop */
396 * Digits 0-6 (minute tens)
398 #define P6 (P15 / 3) /* mark (+1) */
399 #define N6 (N15 / 3) /* space (-1) */
401 double bcd6[][4] = {
402 {N6, N6, N6, 0}, /* 0 */
403 {P6, N6, N6, 0}, /* 1 */
404 {N6, P6, N6, 0}, /* 2 */
405 {P6, P6, N6, 0}, /* 3 */
406 {N6, N6, P6, 0}, /* 4 */
407 {P6, N6, P6, 0}, /* 5 */
408 {N6, P6, P6, 0}, /* 6 */
409 {0, 0, 0, 0} /* backstop */
413 * Digits 0-3 (day hundreds)
415 #define P3 (P15 / 2) /* mark (+1) */
416 #define N3 (N15 / 2) /* space (-1) */
418 double bcd3[][4] = {
419 {N3, N3, 0, 0}, /* 0 */
420 {P3, N3, 0, 0}, /* 1 */
421 {N3, P3, 0, 0}, /* 2 */
422 {P3, P3, 0, 0}, /* 3 */
423 {0, 0, 0, 0} /* backstop */
427 * Digits 0-2 (hour tens)
429 #define P2 (P15 / 2) /* mark (+1) */
430 #define N2 (N15 / 2) /* space (-1) */
432 double bcd2[][4] = {
433 {N2, N2, 0, 0}, /* 0 */
434 {P2, N2, 0, 0}, /* 1 */
435 {N2, P2, 0, 0}, /* 2 */
436 {0, 0, 0, 0} /* backstop */
440 * DST decode (DST2 DST1) for prettyprint
442 char dstcod[] = {
443 'S', /* 00 standard time */
444 'I', /* 01 set clock ahead at 0200 local */
445 'O', /* 10 set clock back at 0200 local */
446 'D' /* 11 daylight time */
450 * The decoding matrix consists of nine row vectors, one for each digit
451 * of the timecode. The digits are stored from least to most significant
452 * order. The maximum likelihood timecode is formed from the digits
453 * corresponding to the maximum likelihood values reading in the
454 * opposite order: yy ddd hh:mm.
456 struct decvec {
457 int radix; /* radix (3, 4, 6, 10) */
458 int digit; /* current clock digit */
459 int mldigit; /* maximum likelihood digit */
460 int count; /* match count */
461 double digprb; /* max digit probability */
462 double digsnr; /* likelihood function (dB) */
463 double like[10]; /* likelihood integrator 0-9 */
467 * The station structure (sp) is used to acquire the minute pulse from
468 * WWV and/or WWVH. These stations are distinguished by the frequency
469 * used for the second and minute sync pulses, 1000 Hz for WWV and 1200
470 * Hz for WWVH. Other than frequency, the format is the same.
472 struct sync {
473 double epoch; /* accumulated epoch differences */
474 double maxeng; /* sync max energy */
475 double noieng; /* sync noise energy */
476 long pos; /* max amplitude position */
477 long lastpos; /* last max position */
478 long mepoch; /* minute synch epoch */
480 double amp; /* sync signal */
481 double syneng; /* sync signal max */
482 double synmax; /* sync signal max latched at 0 s */
483 double synsnr; /* sync signal SNR */
484 double metric; /* signal quality metric */
485 int reach; /* reachability register */
486 int count; /* bit counter */
487 int select; /* select bits */
488 char refid[5]; /* reference identifier */
492 * The channel structure (cp) is used to mitigate between channels.
494 struct chan {
495 int gain; /* audio gain */
496 struct sync wwv; /* wwv station */
497 struct sync wwvh; /* wwvh station */
501 * WWV unit control structure (up)
503 struct wwvunit {
504 l_fp timestamp; /* audio sample timestamp */
505 l_fp tick; /* audio sample increment */
506 double phase, freq; /* logical clock phase and frequency */
507 double monitor; /* audio monitor point */
508 #ifdef ICOM
509 int fd_icom; /* ICOM file descriptor */
510 #endif /* ICOM */
511 int errflg; /* error flags */
512 int watch; /* watchcat */
515 * Audio codec variables
517 double comp[SIZE]; /* decompanding table */
518 int port; /* codec port */
519 int gain; /* codec gain */
520 int mongain; /* codec monitor gain */
521 int clipcnt; /* sample clipped count */
524 * Variables used to establish basic system timing
526 int avgint; /* master time constant */
527 int yepoch; /* sync epoch */
528 int repoch; /* buffered sync epoch */
529 double epomax; /* second sync amplitude */
530 double eposnr; /* second sync SNR */
531 double irig; /* data I channel amplitude */
532 double qrig; /* data Q channel amplitude */
533 int datapt; /* 100 Hz ramp */
534 double datpha; /* 100 Hz VFO control */
535 int rphase; /* second sample counter */
536 long mphase; /* minute sample counter */
539 * Variables used to mitigate which channel to use
541 struct chan mitig[NCHAN]; /* channel data */
542 struct sync *sptr; /* station pointer */
543 int dchan; /* data channel */
544 int schan; /* probe channel */
545 int achan; /* active channel */
548 * Variables used by the clock state machine
550 struct decvec decvec[9]; /* decoding matrix */
551 int rsec; /* seconds counter */
552 int digcnt; /* count of digits synchronized */
555 * Variables used to estimate signal levels and bit/digit
556 * probabilities
558 double datsig; /* data signal max */
559 double datsnr; /* data signal SNR (dB) */
562 * Variables used to establish status and alarm conditions
564 int status; /* status bits */
565 int alarm; /* alarm flashers */
566 int misc; /* miscellaneous timecode bits */
567 int errcnt; /* data bit error counter */
571 * Function prototypes
573 static int wwv_start P((int, struct peer *));
574 static void wwv_shutdown P((int, struct peer *));
575 static void wwv_receive P((struct recvbuf *));
576 static void wwv_poll P((int, struct peer *));
579 * More function prototypes
581 static void wwv_epoch P((struct peer *));
582 static void wwv_rf P((struct peer *, double));
583 static void wwv_endpoc P((struct peer *, int));
584 static void wwv_rsec P((struct peer *, double));
585 static void wwv_qrz P((struct peer *, struct sync *, int));
586 static void wwv_corr4 P((struct peer *, struct decvec *,
587 double [], double [][4]));
588 static void wwv_gain P((struct peer *));
589 static void wwv_tsec P((struct peer *));
590 static int timecode P((struct wwvunit *, char *));
591 static double wwv_snr P((double, double));
592 static int carry P((struct decvec *));
593 static int wwv_newchan P((struct peer *));
594 static void wwv_newgame P((struct peer *));
595 static double wwv_metric P((struct sync *));
596 static void wwv_clock P((struct peer *));
597 #ifdef ICOM
598 static int wwv_qsy P((struct peer *, int));
599 #endif /* ICOM */
601 static double qsy[NCHAN] = {2.5, 5, 10, 15, 20}; /* frequencies (MHz) */
604 * Transfer vector
606 struct refclock refclock_wwv = {
607 wwv_start, /* start up driver */
608 wwv_shutdown, /* shut down driver */
609 wwv_poll, /* transmit poll message */
610 noentry, /* not used (old wwv_control) */
611 noentry, /* initialize driver (not used) */
612 noentry, /* not used (old wwv_buginfo) */
613 NOFLAGS /* not used */
618 * wwv_start - open the devices and initialize data for processing
620 static int
621 wwv_start(
622 int unit, /* instance number (used by PCM) */
623 struct peer *peer /* peer structure pointer */
626 struct refclockproc *pp;
627 struct wwvunit *up;
628 #ifdef ICOM
629 int temp;
630 #endif /* ICOM */
633 * Local variables
635 int fd; /* file descriptor */
636 int i; /* index */
637 double step; /* codec adjustment */
640 * Open audio device
642 fd = audio_init(DEVICE_AUDIO, AUDIO_BUFSIZ, unit);
643 if (fd < 0)
644 return (0);
645 #ifdef DEBUG
646 if (debug)
647 audio_show();
648 #endif /* DEBUG */
651 * Allocate and initialize unit structure
653 if (!(up = (struct wwvunit *)emalloc(sizeof(struct wwvunit)))) {
654 close(fd);
655 return (0);
657 memset(up, 0, sizeof(struct wwvunit));
658 pp = peer->procptr;
659 pp->unitptr = (caddr_t)up;
660 pp->io.clock_recv = wwv_receive;
661 pp->io.srcclock = (caddr_t)peer;
662 pp->io.datalen = 0;
663 pp->io.fd = fd;
664 if (!io_addclock(&pp->io)) {
665 close(fd);
666 free(up);
667 return (0);
671 * Initialize miscellaneous variables
673 peer->precision = PRECISION;
674 pp->clockdesc = DESCRIPTION;
677 * The companded samples are encoded sign-magnitude. The table
678 * contains all the 256 values in the interest of speed.
680 up->comp[0] = up->comp[OFFSET] = 0.;
681 up->comp[1] = 1.; up->comp[OFFSET + 1] = -1.;
682 up->comp[2] = 3.; up->comp[OFFSET + 2] = -3.;
683 step = 2.;
684 for (i = 3; i < OFFSET; i++) {
685 up->comp[i] = up->comp[i - 1] + step;
686 up->comp[OFFSET + i] = -up->comp[i];
687 if (i % 16 == 0)
688 step *= 2.;
690 DTOLFP(1. / SECOND, &up->tick);
693 * Initialize the decoding matrix with the radix for each digit
694 * position.
696 up->decvec[MN].radix = 10; /* minutes */
697 up->decvec[MN + 1].radix = 6;
698 up->decvec[HR].radix = 10; /* hours */
699 up->decvec[HR + 1].radix = 3;
700 up->decvec[DA].radix = 10; /* days */
701 up->decvec[DA + 1].radix = 10;
702 up->decvec[DA + 2].radix = 4;
703 up->decvec[YR].radix = 10; /* years */
704 up->decvec[YR + 1].radix = 10;
706 #ifdef ICOM
708 * Initialize autotune if available. Note that the ICOM select
709 * code must be less than 128, so the high order bit can be used
710 * to select the line speed 0 (9600 bps) or 1 (1200 bps).
712 temp = 0;
713 #ifdef DEBUG
714 if (debug > 1)
715 temp = P_TRACE;
716 #endif /* DEBUG */
717 if (peer->ttl != 0) {
718 if (peer->ttl & 0x80)
719 up->fd_icom = icom_init("/dev/icom", B1200,
720 temp);
721 else
722 up->fd_icom = icom_init("/dev/icom", B9600,
723 temp);
724 if (up->fd_icom < 0) {
725 NLOG(NLOG_SYNCEVENT | NLOG_SYSEVENT)
726 msyslog(LOG_NOTICE,
727 "icom: %m");
728 up->errflg = CEVNT_FAULT;
731 if (up->fd_icom > 0) {
732 if (wwv_qsy(peer, DCHAN) != 0) {
733 NLOG(NLOG_SYNCEVENT | NLOG_SYSEVENT)
734 msyslog(LOG_NOTICE,
735 "icom: radio not found");
736 up->errflg = CEVNT_FAULT;
737 close(up->fd_icom);
738 up->fd_icom = 0;
739 } else {
740 NLOG(NLOG_SYNCEVENT | NLOG_SYSEVENT)
741 msyslog(LOG_NOTICE,
742 "icom: autotune enabled");
745 #endif /* ICOM */
748 * Let the games begin.
750 wwv_newgame(peer);
751 return (1);
756 * wwv_shutdown - shut down the clock
758 static void
759 wwv_shutdown(
760 int unit, /* instance number (not used) */
761 struct peer *peer /* peer structure pointer */
764 struct refclockproc *pp;
765 struct wwvunit *up;
767 pp = peer->procptr;
768 up = (struct wwvunit *)pp->unitptr;
769 if (up == NULL)
770 return;
772 io_closeclock(&pp->io);
773 #ifdef ICOM
774 if (up->fd_icom > 0)
775 close(up->fd_icom);
776 #endif /* ICOM */
777 free(up);
782 * wwv_receive - receive data from the audio device
784 * This routine reads input samples and adjusts the logical clock to
785 * track the A/D sample clock by dropping or duplicating codec samples.
786 * It also controls the A/D signal level with an AGC loop to mimimize
787 * quantization noise and avoid overload.
789 static void
790 wwv_receive(
791 struct recvbuf *rbufp /* receive buffer structure pointer */
794 struct peer *peer;
795 struct refclockproc *pp;
796 struct wwvunit *up;
799 * Local variables
801 double sample; /* codec sample */
802 u_char *dpt; /* buffer pointer */
803 int bufcnt; /* buffer counter */
804 l_fp ltemp;
806 peer = (struct peer *)rbufp->recv_srcclock;
807 pp = peer->procptr;
808 up = (struct wwvunit *)pp->unitptr;
811 * Main loop - read until there ain't no more. Note codec
812 * samples are bit-inverted.
814 DTOLFP((double)rbufp->recv_length / SECOND, &ltemp);
815 L_SUB(&rbufp->recv_time, &ltemp);
816 up->timestamp = rbufp->recv_time;
817 dpt = rbufp->recv_buffer;
818 for (bufcnt = 0; bufcnt < rbufp->recv_length; bufcnt++) {
819 sample = up->comp[~*dpt++ & 0xff];
822 * Clip noise spikes greater than MAXAMP (6000) and
823 * record the number of clips to be used later by the
824 * AGC.
826 if (sample > MAXAMP) {
827 sample = MAXAMP;
828 up->clipcnt++;
829 } else if (sample < -MAXAMP) {
830 sample = -MAXAMP;
831 up->clipcnt++;
835 * Variable frequency oscillator. The codec oscillator
836 * runs at the nominal rate of 8000 samples per second,
837 * or 125 us per sample. A frequency change of one unit
838 * results in either duplicating or deleting one sample
839 * per second, which results in a frequency change of
840 * 125 PPM.
842 up->phase += up->freq / SECOND;
843 up->phase += FREQ_OFFSET / 1e6;
844 if (up->phase >= .5) {
845 up->phase -= 1.;
846 } else if (up->phase < -.5) {
847 up->phase += 1.;
848 wwv_rf(peer, sample);
849 wwv_rf(peer, sample);
850 } else {
851 wwv_rf(peer, sample);
853 L_ADD(&up->timestamp, &up->tick);
857 * Set the input port and monitor gain for the next buffer.
859 if (pp->sloppyclockflag & CLK_FLAG2)
860 up->port = 2;
861 else
862 up->port = 1;
863 if (pp->sloppyclockflag & CLK_FLAG3)
864 up->mongain = MONGAIN;
865 else
866 up->mongain = 0;
871 * wwv_poll - called by the transmit procedure
873 * This routine keeps track of status. If no offset samples have been
874 * processed during a poll interval, a timeout event is declared. If
875 * errors have have occurred during the interval, they are reported as
876 * well.
878 static void
879 wwv_poll(
880 int unit, /* instance number (not used) */
881 struct peer *peer /* peer structure pointer */
884 struct refclockproc *pp;
885 struct wwvunit *up;
887 pp = peer->procptr;
888 up = (struct wwvunit *)pp->unitptr;
889 if (pp->coderecv == pp->codeproc)
890 up->errflg = CEVNT_TIMEOUT;
891 if (up->errflg)
892 refclock_report(peer, up->errflg);
893 up->errflg = 0;
894 pp->polls++;
899 * wwv_rf - process signals and demodulate to baseband
901 * This routine grooms and filters decompanded raw audio samples. The
902 * output signal is the 100-Hz filtered baseband data signal in
903 * quadrature phase. The routine also determines the minute synch epoch,
904 * as well as certain signal maxima, minima and related values.
906 * There are two 1-s ramps used by this program. Both count the 8000
907 * logical clock samples spanning exactly one second. The epoch ramp
908 * counts the samples starting at an arbitrary time. The rphase ramp
909 * counts the samples starting at the 5-ms second sync pulse found
910 * during the epoch ramp.
912 * There are two 1-m ramps used by this program. The mphase ramp counts
913 * the 480,000 logical clock samples spanning exactly one minute and
914 * starting at an arbitrary time. The rsec ramp counts the 60 seconds of
915 * the minute starting at the 800-ms minute sync pulse found during the
916 * mphase ramp. The rsec ramp drives the seconds state machine to
917 * determine the bits and digits of the timecode.
919 * Demodulation operations are based on three synthesized quadrature
920 * sinusoids: 100 Hz for the data signal, 1000 Hz for the WWV sync
921 * signal and 1200 Hz for the WWVH sync signal. These drive synchronous
922 * matched filters for the data signal (170 ms at 100 Hz), WWV minute
923 * sync signal (800 ms at 1000 Hz) and WWVH minute sync signal (800 ms
924 * at 1200 Hz). Two additional matched filters are switched in
925 * as required for the WWV second sync signal (5 cycles at 1000 Hz) and
926 * WWVH second sync signal (6 cycles at 1200 Hz).
928 static void
929 wwv_rf(
930 struct peer *peer, /* peerstructure pointer */
931 double isig /* input signal */
934 struct refclockproc *pp;
935 struct wwvunit *up;
936 struct sync *sp, *rp;
938 static double lpf[5]; /* 150-Hz lpf delay line */
939 double data; /* lpf output */
940 static double bpf[9]; /* 1000/1200-Hz bpf delay line */
941 double syncx; /* bpf output */
942 static double mf[41]; /* 1000/1200-Hz mf delay line */
943 double mfsync; /* mf output */
945 static int iptr; /* data channel pointer */
946 static double ibuf[DATSIZ]; /* data I channel delay line */
947 static double qbuf[DATSIZ]; /* data Q channel delay line */
949 static int jptr; /* sync channel pointer */
950 static int kptr; /* tick channel pointer */
952 static int csinptr; /* wwv channel phase */
953 static double cibuf[SYNSIZ]; /* wwv I channel delay line */
954 static double cqbuf[SYNSIZ]; /* wwv Q channel delay line */
955 static double ciamp; /* wwv I channel amplitude */
956 static double cqamp; /* wwv Q channel amplitude */
958 static double csibuf[TCKSIZ]; /* wwv I tick delay line */
959 static double csqbuf[TCKSIZ]; /* wwv Q tick delay line */
960 static double csiamp; /* wwv I tick amplitude */
961 static double csqamp; /* wwv Q tick amplitude */
963 static int hsinptr; /* wwvh channel phase */
964 static double hibuf[SYNSIZ]; /* wwvh I channel delay line */
965 static double hqbuf[SYNSIZ]; /* wwvh Q channel delay line */
966 static double hiamp; /* wwvh I channel amplitude */
967 static double hqamp; /* wwvh Q channel amplitude */
969 static double hsibuf[TCKSIZ]; /* wwvh I tick delay line */
970 static double hsqbuf[TCKSIZ]; /* wwvh Q tick delay line */
971 static double hsiamp; /* wwvh I tick amplitude */
972 static double hsqamp; /* wwvh Q tick amplitude */
974 static double epobuf[SECOND]; /* second sync comb filter */
975 static double epomax, nxtmax; /* second sync amplitude buffer */
976 static int epopos; /* epoch second sync position buffer */
978 static int iniflg; /* initialization flag */
979 int pdelay; /* propagation delay (samples) */
980 int epoch; /* comb filter index */
981 double dtemp;
982 int i;
984 pp = peer->procptr;
985 up = (struct wwvunit *)pp->unitptr;
987 if (!iniflg) {
988 iniflg = 1;
989 memset((char *)lpf, 0, sizeof(lpf));
990 memset((char *)bpf, 0, sizeof(bpf));
991 memset((char *)mf, 0, sizeof(mf));
992 memset((char *)ibuf, 0, sizeof(ibuf));
993 memset((char *)qbuf, 0, sizeof(qbuf));
994 memset((char *)cibuf, 0, sizeof(cibuf));
995 memset((char *)cqbuf, 0, sizeof(cqbuf));
996 memset((char *)csibuf, 0, sizeof(csibuf));
997 memset((char *)csqbuf, 0, sizeof(csqbuf));
998 memset((char *)hibuf, 0, sizeof(hibuf));
999 memset((char *)hqbuf, 0, sizeof(hqbuf));
1000 memset((char *)hsibuf, 0, sizeof(hsibuf));
1001 memset((char *)hsqbuf, 0, sizeof(hsqbuf));
1002 memset((char *)epobuf, 0, sizeof(epobuf));
1006 * Baseband data demodulation. The 100-Hz subcarrier is
1007 * extracted using a 150-Hz IIR lowpass filter. This attenuates
1008 * the 1000/1200-Hz sync signals, as well as the 440-Hz and
1009 * 600-Hz tones and most of the noise and voice modulation
1010 * components.
1012 * The subcarrier is transmitted 10 dB down from the carrier.
1013 * The DGAIN parameter can be adjusted for this and to
1014 * compensate for the radio audio response at 100 Hz.
1016 * Matlab IIR 4th-order IIR elliptic, 150 Hz lowpass, 0.2 dB
1017 * passband ripple, -50 dB stopband ripple.
1019 data = (lpf[4] = lpf[3]) * 8.360961e-01;
1020 data += (lpf[3] = lpf[2]) * -3.481740e+00;
1021 data += (lpf[2] = lpf[1]) * 5.452988e+00;
1022 data += (lpf[1] = lpf[0]) * -3.807229e+00;
1023 lpf[0] = isig * DGAIN - data;
1024 data = lpf[0] * 3.281435e-03
1025 + lpf[1] * -1.149947e-02
1026 + lpf[2] * 1.654858e-02
1027 + lpf[3] * -1.149947e-02
1028 + lpf[4] * 3.281435e-03;
1031 * The 100-Hz data signal is demodulated using a pair of
1032 * quadrature multipliers, matched filters and a phase lock
1033 * loop. The I and Q quadrature data signals are produced by
1034 * multiplying the filtered signal by 100-Hz sine and cosine
1035 * signals, respectively. The signals are processed by 170-ms
1036 * synchronous matched filters to produce the amplitude and
1037 * phase signals used by the demodulator. The signals are scaled
1038 * to produce unit energy at the maximum value.
1040 i = up->datapt;
1041 up->datapt = (up->datapt + IN100) % 80;
1042 dtemp = sintab[i] * data / (MS / 2. * DATCYC);
1043 up->irig -= ibuf[iptr];
1044 ibuf[iptr] = dtemp;
1045 up->irig += dtemp;
1047 i = (i + 20) % 80;
1048 dtemp = sintab[i] * data / (MS / 2. * DATCYC);
1049 up->qrig -= qbuf[iptr];
1050 qbuf[iptr] = dtemp;
1051 up->qrig += dtemp;
1052 iptr = (iptr + 1) % DATSIZ;
1055 * Baseband sync demodulation. The 1000/1200 sync signals are
1056 * extracted using a 600-Hz IIR bandpass filter. This removes
1057 * the 100-Hz data subcarrier, as well as the 440-Hz and 600-Hz
1058 * tones and most of the noise and voice modulation components.
1060 * Matlab 4th-order IIR elliptic, 800-1400 Hz bandpass, 0.2 dB
1061 * passband ripple, -50 dB stopband ripple.
1063 syncx = (bpf[8] = bpf[7]) * 4.897278e-01;
1064 syncx += (bpf[7] = bpf[6]) * -2.765914e+00;
1065 syncx += (bpf[6] = bpf[5]) * 8.110921e+00;
1066 syncx += (bpf[5] = bpf[4]) * -1.517732e+01;
1067 syncx += (bpf[4] = bpf[3]) * 1.975197e+01;
1068 syncx += (bpf[3] = bpf[2]) * -1.814365e+01;
1069 syncx += (bpf[2] = bpf[1]) * 1.159783e+01;
1070 syncx += (bpf[1] = bpf[0]) * -4.735040e+00;
1071 bpf[0] = isig - syncx;
1072 syncx = bpf[0] * 8.203628e-03
1073 + bpf[1] * -2.375732e-02
1074 + bpf[2] * 3.353214e-02
1075 + bpf[3] * -4.080258e-02
1076 + bpf[4] * 4.605479e-02
1077 + bpf[5] * -4.080258e-02
1078 + bpf[6] * 3.353214e-02
1079 + bpf[7] * -2.375732e-02
1080 + bpf[8] * 8.203628e-03;
1083 * The 1000/1200 sync signals are demodulated using a pair of
1084 * quadrature multipliers and matched filters. However,
1085 * synchronous demodulation at these frequencies is impractical,
1086 * so only the signal amplitude is used. The I and Q quadrature
1087 * sync signals are produced by multiplying the filtered signal
1088 * by 1000-Hz (WWV) and 1200-Hz (WWVH) sine and cosine signals,
1089 * respectively. The WWV and WWVH signals are processed by 800-
1090 * ms synchronous matched filters and combined to produce the
1091 * minute sync signal and detect which one (or both) the WWV or
1092 * WWVH signal is present. The WWV and WWVH signals are also
1093 * processed by 5-ms synchronous matched filters and combined to
1094 * produce the second sync signal. The signals are scaled to
1095 * produce unit energy at the maximum value.
1097 * Note the master timing ramps, which run continuously. The
1098 * minute counter (mphase) counts the samples in the minute,
1099 * while the second counter (epoch) counts the samples in the
1100 * second.
1102 up->mphase = (up->mphase + 1) % MINUTE;
1103 epoch = up->mphase % SECOND;
1106 * WWV
1108 i = csinptr;
1109 csinptr = (csinptr + IN1000) % 80;
1111 dtemp = sintab[i] * syncx / (MS / 2.);
1112 ciamp -= cibuf[jptr];
1113 cibuf[jptr] = dtemp;
1114 ciamp += dtemp;
1115 csiamp -= csibuf[kptr];
1116 csibuf[kptr] = dtemp;
1117 csiamp += dtemp;
1119 i = (i + 20) % 80;
1120 dtemp = sintab[i] * syncx / (MS / 2.);
1121 cqamp -= cqbuf[jptr];
1122 cqbuf[jptr] = dtemp;
1123 cqamp += dtemp;
1124 csqamp -= csqbuf[kptr];
1125 csqbuf[kptr] = dtemp;
1126 csqamp += dtemp;
1128 sp = &up->mitig[up->achan].wwv;
1129 sp->amp = sqrt(ciamp * ciamp + cqamp * cqamp) / SYNCYC;
1130 if (!(up->status & MSYNC))
1131 wwv_qrz(peer, sp, (int)(pp->fudgetime1 * SECOND));
1134 * WWVH
1136 i = hsinptr;
1137 hsinptr = (hsinptr + IN1200) % 80;
1139 dtemp = sintab[i] * syncx / (MS / 2.);
1140 hiamp -= hibuf[jptr];
1141 hibuf[jptr] = dtemp;
1142 hiamp += dtemp;
1143 hsiamp -= hsibuf[kptr];
1144 hsibuf[kptr] = dtemp;
1145 hsiamp += dtemp;
1147 i = (i + 20) % 80;
1148 dtemp = sintab[i] * syncx / (MS / 2.);
1149 hqamp -= hqbuf[jptr];
1150 hqbuf[jptr] = dtemp;
1151 hqamp += dtemp;
1152 hsqamp -= hsqbuf[kptr];
1153 hsqbuf[kptr] = dtemp;
1154 hsqamp += dtemp;
1156 rp = &up->mitig[up->achan].wwvh;
1157 rp->amp = sqrt(hiamp * hiamp + hqamp * hqamp) / SYNCYC;
1158 if (!(up->status & MSYNC))
1159 wwv_qrz(peer, rp, (int)(pp->fudgetime2 * SECOND));
1160 jptr = (jptr + 1) % SYNSIZ;
1161 kptr = (kptr + 1) % TCKSIZ;
1164 * The following section is called once per minute. It does
1165 * housekeeping and timeout functions and empties the dustbins.
1167 if (up->mphase == 0) {
1168 up->watch++;
1169 if (!(up->status & MSYNC)) {
1172 * If minute sync has not been acquired before
1173 * ACQSN timeout (6 min), or if no signal is
1174 * heard, the program cycles to the next
1175 * frequency and tries again.
1177 if (!wwv_newchan(peer))
1178 up->watch = 0;
1179 #ifdef ICOM
1180 if (up->fd_icom > 0)
1181 wwv_qsy(peer, up->dchan);
1182 #endif /* ICOM */
1183 } else {
1186 * If the leap bit is set, set the minute epoch
1187 * back one second so the station processes
1188 * don't miss a beat.
1190 if (up->status & LEPSEC) {
1191 up->mphase -= SECOND;
1192 if (up->mphase < 0)
1193 up->mphase += MINUTE;
1199 * When the channel metric reaches threshold and the second
1200 * counter matches the minute epoch within the second, the
1201 * driver has synchronized to the station. The second number is
1202 * the remaining seconds until the next minute epoch, while the
1203 * sync epoch is zero. Watch out for the first second; if
1204 * already synchronized to the second, the buffered sync epoch
1205 * must be set.
1207 * Note the guard interval is 200 ms; if for some reason the
1208 * clock drifts more than that, it might wind up in the wrong
1209 * second. If the maximum frequency error is not more than about
1210 * 1 PPM, the clock can go as much as two days while still in
1211 * the same second.
1213 if (up->status & MSYNC) {
1214 wwv_epoch(peer);
1215 } else if (up->sptr != NULL) {
1216 sp = up->sptr;
1217 if (sp->metric >= TTHR && epoch == sp->mepoch % SECOND) {
1218 up->rsec = (60 - sp->mepoch / SECOND) % 60;
1219 up->rphase = 0;
1220 up->status |= MSYNC;
1221 up->watch = 0;
1222 if (!(up->status & SSYNC))
1223 up->repoch = up->yepoch = epoch;
1224 else
1225 up->repoch = up->yepoch;
1231 * The second sync pulse is extracted using 5-ms (40 sample) FIR
1232 * matched filters at 1000 Hz for WWV or 1200 Hz for WWVH. This
1233 * pulse is used for the most precise synchronization, since if
1234 * provides a resolution of one sample (125 us). The filters run
1235 * only if the station has been reliably determined.
1237 if (up->status & SELV) {
1238 pdelay = (int)(pp->fudgetime1 * SECOND);
1239 mfsync = sqrt(csiamp * csiamp + csqamp * csqamp) /
1240 TCKCYC;
1241 } else if (up->status & SELH) {
1242 pdelay = (int)(pp->fudgetime2 * SECOND);
1243 mfsync = sqrt(hsiamp * hsiamp + hsqamp * hsqamp) /
1244 TCKCYC;
1245 } else {
1246 pdelay = 0;
1247 mfsync = 0;
1251 * Enhance the seconds sync pulse using a 1-s (8000-sample) comb
1252 * filter. Correct for the FIR matched filter delay, which is 5
1253 * ms for both the WWV and WWVH filters, and also for the
1254 * propagation delay. Once each second look for second sync. If
1255 * not in minute sync, fiddle the codec gain. Note the SNR is
1256 * computed from the maximum sample and the envelope of the
1257 * sample 6 ms before it, so if we slip more than a cycle the
1258 * SNR should plummet. The signal is scaled to produce unit
1259 * energy at the maximum value.
1261 dtemp = (epobuf[epoch] += (mfsync - epobuf[epoch]) /
1262 up->avgint);
1263 if (dtemp > epomax) {
1264 int j;
1266 epomax = dtemp;
1267 epopos = epoch;
1268 j = epoch - 6 * MS;
1269 if (j < 0)
1270 j += SECOND;
1271 nxtmax = fabs(epobuf[j]);
1273 if (epoch == 0) {
1274 up->epomax = epomax;
1275 up->eposnr = wwv_snr(epomax, nxtmax);
1276 epopos -= pdelay + TCKCYC * MS;
1277 if (epopos < 0)
1278 epopos += SECOND;
1279 wwv_endpoc(peer, epopos);
1280 if (!(up->status & SSYNC))
1281 up->alarm |= SYNERR;
1282 epomax = 0;
1283 if (!(up->status & MSYNC))
1284 wwv_gain(peer);
1290 * wwv_qrz - identify and acquire WWV/WWVH minute sync pulse
1292 * This routine implements a virtual station process used to acquire
1293 * minute sync and to mitigate among the ten frequency and station
1294 * combinations. During minute sync acquisition the process probes each
1295 * frequency and station in turn for the minute pulse, which
1296 * involves searching through the entire 480,000-sample minute. The
1297 * process finds the maximum signal and RMS noise plus signal. Then, the
1298 * actual noise is determined by subtracting the energy of the matched
1299 * filter.
1301 * Students of radar receiver technology will discover this algorithm
1302 * amounts to a range-gate discriminator. A valid pulse must have peak
1303 * amplitude at least QTHR (2500) and SNR at least QSNR (20) dB and the
1304 * difference between the current and previous epoch must be less than
1305 * AWND (20 ms). Note that the discriminator peak occurs about 800 ms
1306 * into the second, so the timing is retarded to the previous second
1307 * epoch.
1309 static void
1310 wwv_qrz(
1311 struct peer *peer, /* peer structure pointer */
1312 struct sync *sp, /* sync channel structure */
1313 int pdelay /* propagation delay (samples) */
1316 struct refclockproc *pp;
1317 struct wwvunit *up;
1318 char tbuf[80]; /* monitor buffer */
1319 long epoch;
1321 pp = peer->procptr;
1322 up = (struct wwvunit *)pp->unitptr;
1325 * Find the sample with peak amplitude, which defines the minute
1326 * epoch. Accumulate all samples to determine the total noise
1327 * energy.
1329 epoch = up->mphase - pdelay - SYNSIZ;
1330 if (epoch < 0)
1331 epoch += MINUTE;
1332 if (sp->amp > sp->maxeng) {
1333 sp->maxeng = sp->amp;
1334 sp->pos = epoch;
1336 sp->noieng += sp->amp;
1339 * At the end of the minute, determine the epoch of the minute
1340 * sync pulse, as well as the difference between the current and
1341 * previous epoches due to the intrinsic frequency error plus
1342 * jitter. When calculating the SNR, subtract the pulse energy
1343 * from the total noise energy and then normalize.
1345 if (up->mphase == 0) {
1346 sp->synmax = sp->maxeng;
1347 sp->synsnr = wwv_snr(sp->synmax, (sp->noieng -
1348 sp->synmax) / MINUTE);
1349 if (sp->count == 0)
1350 sp->lastpos = sp->pos;
1351 epoch = (sp->pos - sp->lastpos) % MINUTE;
1352 sp->reach <<= 1;
1353 if (sp->reach & (1 << AMAX))
1354 sp->count--;
1355 if (sp->synmax > ATHR && sp->synsnr > ASNR) {
1356 if (abs(epoch) < AWND * MS) {
1357 sp->reach |= 1;
1358 sp->count++;
1359 sp->mepoch = sp->lastpos = sp->pos;
1360 } else if (sp->count == 1) {
1361 sp->lastpos = sp->pos;
1364 if (up->watch > ACQSN)
1365 sp->metric = 0;
1366 else
1367 sp->metric = wwv_metric(sp);
1368 if (pp->sloppyclockflag & CLK_FLAG4) {
1369 sprintf(tbuf,
1370 "wwv8 %04x %3d %s %04x %.0f %.0f/%.1f %4ld %4ld",
1371 up->status, up->gain, sp->refid,
1372 sp->reach & 0xffff, sp->metric, sp->synmax,
1373 sp->synsnr, sp->pos % SECOND, epoch);
1374 record_clock_stats(&peer->srcadr, tbuf);
1375 #ifdef DEBUG
1376 if (debug)
1377 printf("%s\n", tbuf);
1378 #endif /* DEBUG */
1380 sp->maxeng = sp->noieng = 0;
1386 * wwv_endpoc - identify and acquire second sync pulse
1388 * This routine is called at the end of the second sync interval. It
1389 * determines the second sync epoch position within the second and
1390 * disciplines the sample clock using a frequency-lock loop (FLL).
1392 * Second sync is determined in the RF input routine as the maximum
1393 * over all 8000 samples in the second comb filter. To assure accurate
1394 * and reliable time and frequency discipline, this routine performs a
1395 * great deal of heavy-handed heuristic data filtering and grooming.
1397 static void
1398 wwv_endpoc(
1399 struct peer *peer, /* peer structure pointer */
1400 int epopos /* epoch max position */
1403 struct refclockproc *pp;
1404 struct wwvunit *up;
1405 static int epoch_mf[3]; /* epoch median filter */
1406 static int tepoch; /* current second epoch */
1407 static int xepoch; /* last second epoch */
1408 static int zepoch; /* last run epoch */
1409 static int zcount; /* last run end time */
1410 static int scount; /* seconds counter */
1411 static int syncnt; /* run length counter */
1412 static int maxrun; /* longest run length */
1413 static int mepoch; /* longest run end epoch */
1414 static int mcount; /* longest run end time */
1415 static int avgcnt; /* averaging interval counter */
1416 static int avginc; /* averaging ratchet */
1417 static int iniflg; /* initialization flag */
1418 char tbuf[80]; /* monitor buffer */
1419 double dtemp;
1420 int tmp2;
1422 pp = peer->procptr;
1423 up = (struct wwvunit *)pp->unitptr;
1424 if (!iniflg) {
1425 iniflg = 1;
1426 memset((char *)epoch_mf, 0, sizeof(epoch_mf));
1430 * If the signal amplitude or SNR fall below thresholds, dim the
1431 * second sync lamp and wait for hotter ions. If no stations are
1432 * heard, we are either in a probe cycle or the ions are really
1433 * cold.
1435 scount++;
1436 if (up->epomax < STHR || up->eposnr < SSNR) {
1437 up->status &= ~(SSYNC | FGATE);
1438 avgcnt = syncnt = maxrun = 0;
1439 return;
1441 if (!(up->status & (SELV | SELH)))
1442 return;
1445 * A three-stage median filter is used to help denoise the
1446 * second sync pulse. The median sample becomes the candidate
1447 * epoch.
1449 epoch_mf[2] = epoch_mf[1];
1450 epoch_mf[1] = epoch_mf[0];
1451 epoch_mf[0] = epopos;
1452 if (epoch_mf[0] > epoch_mf[1]) {
1453 if (epoch_mf[1] > epoch_mf[2])
1454 tepoch = epoch_mf[1]; /* 0 1 2 */
1455 else if (epoch_mf[2] > epoch_mf[0])
1456 tepoch = epoch_mf[0]; /* 2 0 1 */
1457 else
1458 tepoch = epoch_mf[2]; /* 0 2 1 */
1459 } else {
1460 if (epoch_mf[1] < epoch_mf[2])
1461 tepoch = epoch_mf[1]; /* 2 1 0 */
1462 else if (epoch_mf[2] < epoch_mf[0])
1463 tepoch = epoch_mf[0]; /* 1 0 2 */
1464 else
1465 tepoch = epoch_mf[2]; /* 1 2 0 */
1470 * If the epoch candidate is the same as the last one, increment
1471 * the run counter. If not, save the length, epoch and end
1472 * time of the current run for use later and reset the counter.
1473 * The epoch is considered valid if the run is at least SCMP
1474 * (10) s, the minute is synchronized and the interval since the
1475 * last epoch is not greater than the averaging interval. Thus,
1476 * after a long absence, the program will wait a full averaging
1477 * interval while the comb filter charges up and noise
1478 * dissapates..
1480 tmp2 = (tepoch - xepoch) % SECOND;
1481 if (tmp2 == 0) {
1482 syncnt++;
1483 if (syncnt > SCMP && up->status & MSYNC && (up->status &
1484 FGATE || scount - zcount <= up->avgint)) {
1485 up->status |= SSYNC;
1486 up->yepoch = tepoch;
1488 } else if (syncnt >= maxrun) {
1489 maxrun = syncnt;
1490 mcount = scount;
1491 mepoch = xepoch;
1492 syncnt = 0;
1494 if ((pp->sloppyclockflag & CLK_FLAG4) && !(up->status & MSYNC))
1496 sprintf(tbuf,
1497 "wwv1 %04x %3d %4d %5.0f %5.1f %5d %4d %4d %4d",
1498 up->status, up->gain, tepoch, up->epomax,
1499 up->eposnr, tmp2, avgcnt, syncnt,
1500 maxrun);
1501 record_clock_stats(&peer->srcadr, tbuf);
1502 #ifdef DEBUG
1503 if (debug)
1504 printf("%s\n", tbuf);
1505 #endif /* DEBUG */
1507 avgcnt++;
1508 if (avgcnt < up->avgint) {
1509 xepoch = tepoch;
1510 return;
1514 * The sample clock frequency is disciplined using a first-order
1515 * feedback loop with time constant consistent with the Allan
1516 * intercept of typical computer clocks. During each averaging
1517 * interval the candidate epoch at the end of the longest run is
1518 * determined. If the longest run is zero, all epoches in the
1519 * interval are different, so the candidate epoch is the current
1520 * epoch. The frequency update is computed from the candidate
1521 * epoch difference (125-us units) and time difference (seconds)
1522 * between updates.
1524 if (syncnt >= maxrun) {
1525 maxrun = syncnt;
1526 mcount = scount;
1527 mepoch = xepoch;
1529 xepoch = tepoch;
1530 if (maxrun == 0) {
1531 mepoch = tepoch;
1532 mcount = scount;
1536 * The master clock runs at the codec sample frequency of 8000
1537 * Hz, so the intrinsic time resolution is 125 us. The frequency
1538 * resolution ranges from 18 PPM at the minimum averaging
1539 * interval of 8 s to 0.12 PPM at the maximum interval of 1024
1540 * s. An offset update is determined at the end of the longest
1541 * run in each averaging interval. The frequency adjustment is
1542 * computed from the difference between offset updates and the
1543 * interval between them.
1545 * The maximum frequency adjustment ranges from 187 PPM at the
1546 * minimum interval to 1.5 PPM at the maximum. If the adjustment
1547 * exceeds the maximum, the update is discarded and the
1548 * hysteresis counter is decremented. Otherwise, the frequency
1549 * is incremented by the adjustment, but clamped to the maximum
1550 * 187.5 PPM. If the update is less than half the maximum, the
1551 * hysteresis counter is incremented. If the counter increments
1552 * to +3, the averaging interval is doubled and the counter set
1553 * to zero; if it decrements to -3, the interval is halved and
1554 * the counter set to zero.
1556 dtemp = (mepoch - zepoch) % SECOND;
1557 if (up->status & FGATE) {
1558 if (abs(dtemp) < MAXFREQ * MINAVG) {
1559 up->freq += (dtemp / 2.) / ((mcount - zcount) *
1560 FCONST);
1561 if (up->freq > MAXFREQ)
1562 up->freq = MAXFREQ;
1563 else if (up->freq < -MAXFREQ)
1564 up->freq = -MAXFREQ;
1565 if (abs(dtemp) < MAXFREQ * MINAVG / 2.) {
1566 if (avginc < 3) {
1567 avginc++;
1568 } else {
1569 if (up->avgint < MAXAVG) {
1570 up->avgint <<= 1;
1571 avginc = 0;
1575 } else {
1576 if (avginc > -3) {
1577 avginc--;
1578 } else {
1579 if (up->avgint > MINAVG) {
1580 up->avgint >>= 1;
1581 avginc = 0;
1586 if (pp->sloppyclockflag & CLK_FLAG4) {
1587 sprintf(tbuf,
1588 "wwv2 %04x %5.0f %5.1f %5d %4d %4d %4d %4.0f %7.2f",
1589 up->status, up->epomax, up->eposnr, mepoch,
1590 up->avgint, maxrun, mcount - zcount, dtemp,
1591 up->freq * 1e6 / SECOND);
1592 record_clock_stats(&peer->srcadr, tbuf);
1593 #ifdef DEBUG
1594 if (debug)
1595 printf("%s\n", tbuf);
1596 #endif /* DEBUG */
1600 * This is a valid update; set up for the next interval.
1602 up->status |= FGATE;
1603 zepoch = mepoch;
1604 zcount = mcount;
1605 avgcnt = syncnt = maxrun = 0;
1610 * wwv_epoch - epoch scanner
1612 * This routine extracts data signals from the 100-Hz subcarrier. It
1613 * scans the receiver second epoch to determine the signal amplitudes
1614 * and pulse timings. Receiver synchronization is determined by the
1615 * minute sync pulse detected in the wwv_rf() routine and the second
1616 * sync pulse detected in the wwv_epoch() routine. The transmitted
1617 * signals are delayed by the propagation delay, receiver delay and
1618 * filter delay of this program. Delay corrections are introduced
1619 * separately for WWV and WWVH.
1621 * Most communications radios use a highpass filter in the audio stages,
1622 * which can do nasty things to the subcarrier phase relative to the
1623 * sync pulses. Therefore, the data subcarrier reference phase is
1624 * disciplined using the hardlimited quadrature-phase signal sampled at
1625 * the same time as the in-phase signal. The phase tracking loop uses
1626 * phase adjustments of plus-minus one sample (125 us).
1628 static void
1629 wwv_epoch(
1630 struct peer *peer /* peer structure pointer */
1633 struct refclockproc *pp;
1634 struct wwvunit *up;
1635 struct chan *cp;
1636 static double sigmin, sigzer, sigone, engmax, engmin;
1638 pp = peer->procptr;
1639 up = (struct wwvunit *)pp->unitptr;
1642 * Find the maximum minute sync pulse energy for both the
1643 * WWV and WWVH stations. This will be used later for channel
1644 * and station mitigation. Also set the seconds epoch at 800 ms
1645 * well before the end of the second to make sure we never set
1646 * the epoch backwards.
1648 cp = &up->mitig[up->achan];
1649 if (cp->wwv.amp > cp->wwv.syneng)
1650 cp->wwv.syneng = cp->wwv.amp;
1651 if (cp->wwvh.amp > cp->wwvh.syneng)
1652 cp->wwvh.syneng = cp->wwvh.amp;
1653 if (up->rphase == 800 * MS)
1654 up->repoch = up->yepoch;
1657 * Use the signal amplitude at epoch 15 ms as the noise floor.
1658 * This gives a guard time of +-15 ms from the beginning of the
1659 * second until the second pulse rises at 30 ms. There is a
1660 * compromise here; we want to delay the sample as long as
1661 * possible to give the radio time to change frequency and the
1662 * AGC to stabilize, but as early as possible if the second
1663 * epoch is not exact.
1665 if (up->rphase == 15 * MS)
1666 sigmin = sigzer = sigone = up->irig;
1669 * Latch the data signal at 200 ms. Keep this around until the
1670 * end of the second. Use the signal energy as the peak to
1671 * compute the SNR. Use the Q sample to adjust the 100-Hz
1672 * reference oscillator phase.
1674 if (up->rphase == 200 * MS) {
1675 sigzer = up->irig;
1676 engmax = sqrt(up->irig * up->irig + up->qrig *
1677 up->qrig);
1678 up->datpha = up->qrig / up->avgint;
1679 if (up->datpha >= 0) {
1680 up->datapt++;
1681 if (up->datapt >= 80)
1682 up->datapt -= 80;
1683 } else {
1684 up->datapt--;
1685 if (up->datapt < 0)
1686 up->datapt += 80;
1692 * Latch the data signal at 500 ms. Keep this around until the
1693 * end of the second.
1695 else if (up->rphase == 500 * MS)
1696 sigone = up->irig;
1699 * At the end of the second crank the clock state machine and
1700 * adjust the codec gain. Note the epoch is buffered from the
1701 * center of the second in order to avoid jitter while the
1702 * seconds synch is diddling the epoch. Then, determine the true
1703 * offset and update the median filter in the driver interface.
1705 * Use the energy at the end of the second as the noise to
1706 * compute the SNR for the data pulse. This gives a better
1707 * measurement than the beginning of the second, especially when
1708 * returning from the probe channel. This gives a guard time of
1709 * 30 ms from the decay of the longest pulse to the rise of the
1710 * next pulse.
1712 up->rphase++;
1713 if (up->mphase % SECOND == up->repoch) {
1714 up->status &= ~(DGATE | BGATE);
1715 engmin = sqrt(up->irig * up->irig + up->qrig *
1716 up->qrig);
1717 up->datsig = engmax;
1718 up->datsnr = wwv_snr(engmax, engmin);
1721 * If the amplitude or SNR is below threshold, average a
1722 * 0 in the the integrators; otherwise, average the
1723 * bipolar signal. This is done to avoid noise polution.
1725 if (engmax < DTHR || up->datsnr < DSNR) {
1726 up->status |= DGATE;
1727 wwv_rsec(peer, 0);
1728 } else {
1729 sigzer -= sigone;
1730 sigone -= sigmin;
1731 wwv_rsec(peer, sigone - sigzer);
1733 if (up->status & (DGATE | BGATE))
1734 up->errcnt++;
1735 if (up->errcnt > MAXERR)
1736 up->alarm |= LOWERR;
1737 wwv_gain(peer);
1738 cp = &up->mitig[up->achan];
1739 cp->wwv.syneng = 0;
1740 cp->wwvh.syneng = 0;
1741 up->rphase = 0;
1747 * wwv_rsec - process receiver second
1749 * This routine is called at the end of each receiver second to
1750 * implement the per-second state machine. The machine assembles BCD
1751 * digit bits, decodes miscellaneous bits and dances the leap seconds.
1753 * Normally, the minute has 60 seconds numbered 0-59. If the leap
1754 * warning bit is set, the last minute (1439) of 30 June (day 181 or 182
1755 * for leap years) or 31 December (day 365 or 366 for leap years) is
1756 * augmented by one second numbered 60. This is accomplished by
1757 * extending the minute interval by one second and teaching the state
1758 * machine to ignore it.
1760 static void
1761 wwv_rsec(
1762 struct peer *peer, /* peer structure pointer */
1763 double bit
1766 static int iniflg; /* initialization flag */
1767 static double bcddld[4]; /* BCD data bits */
1768 static double bitvec[61]; /* bit integrator for misc bits */
1769 struct refclockproc *pp;
1770 struct wwvunit *up;
1771 struct chan *cp;
1772 struct sync *sp, *rp;
1773 char tbuf[80]; /* monitor buffer */
1774 int sw, arg, nsec;
1776 pp = peer->procptr;
1777 up = (struct wwvunit *)pp->unitptr;
1778 if (!iniflg) {
1779 iniflg = 1;
1780 memset((char *)bitvec, 0, sizeof(bitvec));
1784 * The bit represents the probability of a hit on zero (negative
1785 * values), a hit on one (positive values) or a miss (zero
1786 * value). The likelihood vector is the exponential average of
1787 * these probabilities. Only the bits of this vector
1788 * corresponding to the miscellaneous bits of the timecode are
1789 * used, but it's easier to do them all. After that, crank the
1790 * seconds state machine.
1792 nsec = up->rsec;
1793 up->rsec++;
1794 bitvec[nsec] += (bit - bitvec[nsec]) / TCONST;
1795 sw = progx[nsec].sw;
1796 arg = progx[nsec].arg;
1799 * The minute state machine. Fly off to a particular section as
1800 * directed by the transition matrix and second number.
1802 switch (sw) {
1805 * Ignore this second.
1807 case IDLE: /* 9, 45-49 */
1808 break;
1811 * Probe channel stuff
1813 * The WWV/H format contains data pulses in second 59 (position
1814 * identifier) and second 1, but not in second 0. The minute
1815 * sync pulse is contained in second 0. At the end of second 58
1816 * QSY to the probe channel, which rotates in turn over all
1817 * WWV/H frequencies. At the end of second 0 measure the minute
1818 * sync pulse. At the end of second 1 measure the data pulse and
1819 * QSY back to the data channel. Note that the actions commented
1820 * here happen at the end of the second numbered as shown.
1822 * At the end of second 0 save the minute sync amplitude latched
1823 * at 800 ms as the signal later used to calculate the SNR.
1825 case SYNC2: /* 0 */
1826 cp = &up->mitig[up->achan];
1827 cp->wwv.synmax = cp->wwv.syneng;
1828 cp->wwvh.synmax = cp->wwvh.syneng;
1829 break;
1832 * At the end of second 1 use the minute sync amplitude latched
1833 * at 800 ms as the noise to calculate the SNR. If the minute
1834 * sync pulse and SNR are above thresholds and the data pulse
1835 * amplitude and SNR are above thresolds, shift a 1 into the
1836 * station reachability register; otherwise, shift a 0. The
1837 * number of 1 bits in the last six intervals is a component of
1838 * the channel metric computed by the wwv_metric() routine.
1839 * Finally, QSY back to the data channel.
1841 case SYNC3: /* 1 */
1842 cp = &up->mitig[up->achan];
1845 * WWV station
1847 sp = &cp->wwv;
1848 sp->synsnr = wwv_snr(sp->synmax, sp->amp);
1849 sp->reach <<= 1;
1850 if (sp->reach & (1 << AMAX))
1851 sp->count--;
1852 if (sp->synmax >= QTHR && sp->synsnr >= QSNR &&
1853 !(up->status & (DGATE | BGATE))) {
1854 sp->reach |= 1;
1855 sp->count++;
1857 sp->metric = wwv_metric(sp);
1860 * WWVH station
1862 rp = &cp->wwvh;
1863 rp->synsnr = wwv_snr(rp->synmax, rp->amp);
1864 rp->reach <<= 1;
1865 if (rp->reach & (1 << AMAX))
1866 rp->count--;
1867 if (rp->synmax >= QTHR && rp->synsnr >= QSNR &&
1868 !(up->status & (DGATE | BGATE))) {
1869 rp->reach |= 1;
1870 rp->count++;
1872 rp->metric = wwv_metric(rp);
1873 if (pp->sloppyclockflag & CLK_FLAG4) {
1874 sprintf(tbuf,
1875 "wwv5 %04x %3d %4d %.0f/%.1f %.0f/%.1f %s %04x %.0f %.0f/%.1f %s %04x %.0f %.0f/%.1f",
1876 up->status, up->gain, up->yepoch,
1877 up->epomax, up->eposnr, up->datsig,
1878 up->datsnr,
1879 sp->refid, sp->reach & 0xffff,
1880 sp->metric, sp->synmax, sp->synsnr,
1881 rp->refid, rp->reach & 0xffff,
1882 rp->metric, rp->synmax, rp->synsnr);
1883 record_clock_stats(&peer->srcadr, tbuf);
1884 #ifdef DEBUG
1885 if (debug)
1886 printf("%s\n", tbuf);
1887 #endif /* DEBUG */
1889 up->errcnt = up->digcnt = up->alarm = 0;
1892 * We now begin the minute scan. If not yet synchronized
1893 * to a station, restart if the units digit has not been
1894 * found within the DATA timeout (15 m) or if not
1895 * synchronized within the SYNCH timeout (40 m). After
1896 * synchronizing to a station, restart if no stations
1897 * are found within the PANIC timeout (2 days).
1899 if (up->status & INSYNC) {
1900 if (up->watch > PANIC) {
1901 wwv_newgame(peer);
1902 return;
1904 } else {
1905 if (!(up->status & DSYNC)) {
1906 if (up->watch > DATA) {
1907 wwv_newgame(peer);
1908 return;
1911 if (up->watch > SYNCH) {
1912 wwv_newgame(peer);
1913 return;
1916 wwv_newchan(peer);
1917 #ifdef ICOM
1918 if (up->fd_icom > 0)
1919 wwv_qsy(peer, up->dchan);
1920 #endif /* ICOM */
1921 break;
1924 * Save the bit probability in the BCD data vector at the index
1925 * given by the argument. Bits not used in the digit are forced
1926 * to zero.
1928 case COEF1: /* 4-7 */
1929 bcddld[arg] = bit;
1930 break;
1932 case COEF: /* 10-13, 15-17, 20-23, 25-26,
1933 30-33, 35-38, 40-41, 51-54 */
1934 if (up->status & DSYNC)
1935 bcddld[arg] = bit;
1936 else
1937 bcddld[arg] = 0;
1938 break;
1940 case COEF2: /* 18, 27-28, 42-43 */
1941 bcddld[arg] = 0;
1942 break;
1945 * Correlate coefficient vector with each valid digit vector and
1946 * save in decoding matrix. We step through the decoding matrix
1947 * digits correlating each with the coefficients and saving the
1948 * greatest and the next lower for later SNR calculation.
1950 case DECIM2: /* 29 */
1951 wwv_corr4(peer, &up->decvec[arg], bcddld, bcd2);
1952 break;
1954 case DECIM3: /* 44 */
1955 wwv_corr4(peer, &up->decvec[arg], bcddld, bcd3);
1956 break;
1958 case DECIM6: /* 19 */
1959 wwv_corr4(peer, &up->decvec[arg], bcddld, bcd6);
1960 break;
1962 case DECIM9: /* 8, 14, 24, 34, 39 */
1963 wwv_corr4(peer, &up->decvec[arg], bcddld, bcd9);
1964 break;
1967 * Miscellaneous bits. If above the positive threshold, declare
1968 * 1; if below the negative threshold, declare 0; otherwise
1969 * raise the BGATE bit. The design is intended to avoid
1970 * integrating noise under low SNR conditions.
1972 case MSC20: /* 55 */
1973 wwv_corr4(peer, &up->decvec[YR + 1], bcddld, bcd9);
1974 /* fall through */
1976 case MSCBIT: /* 2-3, 50, 56-57 */
1977 if (bitvec[nsec] > BTHR) {
1978 if (!(up->misc & arg))
1979 up->alarm |= CMPERR;
1980 up->misc |= arg;
1981 } else if (bitvec[nsec] < -BTHR) {
1982 if (up->misc & arg)
1983 up->alarm |= CMPERR;
1984 up->misc &= ~arg;
1985 } else {
1986 up->status |= BGATE;
1988 break;
1991 * Save the data channel gain, then QSY to the probe channel and
1992 * dim the seconds comb filters. The newchan() routine will
1993 * light them back up.
1995 case MSC21: /* 58 */
1996 if (bitvec[nsec] > BTHR) {
1997 if (!(up->misc & arg))
1998 up->alarm |= CMPERR;
1999 up->misc |= arg;
2000 } else if (bitvec[nsec] < -BTHR) {
2001 if (up->misc & arg)
2002 up->alarm |= CMPERR;
2003 up->misc &= ~arg;
2004 } else {
2005 up->status |= BGATE;
2007 up->status &= ~(SELV | SELH);
2008 #ifdef ICOM
2009 if (up->fd_icom > 0) {
2010 up->schan = (up->schan + 1) % NCHAN;
2011 wwv_qsy(peer, up->schan);
2012 } else {
2013 up->mitig[up->achan].gain = up->gain;
2015 #else
2016 up->mitig[up->achan].gain = up->gain;
2017 #endif /* ICOM */
2018 break;
2021 * The endgames
2023 * During second 59 the receiver and codec AGC are settling
2024 * down, so the data pulse is unusable as quality metric. If
2025 * LEPSEC is set on the last minute of 30 June or 31 December,
2026 * the transmitter and receiver insert an extra second (60) in
2027 * the timescale and the minute sync repeats the second. Once
2028 * leaps occurred at intervals of about 18 months, but the last
2029 * leap before the most recent leap in 1995 was in 1998.
2031 case MIN1: /* 59 */
2032 if (up->status & LEPSEC)
2033 break;
2035 /* fall through */
2037 case MIN2: /* 60 */
2038 up->status &= ~LEPSEC;
2039 wwv_tsec(peer);
2040 up->rsec = 0;
2041 wwv_clock(peer);
2042 break;
2044 if ((pp->sloppyclockflag & CLK_FLAG4) && !(up->status &
2045 DSYNC)) {
2046 sprintf(tbuf,
2047 "wwv3 %2d %04x %3d %4d %5.0f %5.1f %5.0f %5.1f %5.0f",
2048 nsec, up->status, up->gain, up->yepoch, up->epomax,
2049 up->eposnr, up->datsig, up->datsnr, bit);
2050 record_clock_stats(&peer->srcadr, tbuf);
2051 #ifdef DEBUG
2052 if (debug)
2053 printf("%s\n", tbuf);
2054 #endif /* DEBUG */
2056 pp->disp += AUDIO_PHI;
2060 * The radio clock is set if the alarm bits are all zero. After that,
2061 * the time is considered valid if the second sync bit is lit. It should
2062 * not be a surprise, especially if the radio is not tunable, that
2063 * sometimes no stations are above the noise and the integrators
2064 * discharge below the thresholds. We assume that, after a day of signal
2065 * loss, the minute sync epoch will be in the same second. This requires
2066 * the codec frequency be accurate within 6 PPM. Practical experience
2067 * shows the frequency typically within 0.1 PPM, so after a day of
2068 * signal loss, the time should be within 8.6 ms..
2070 static void
2071 wwv_clock(
2072 struct peer *peer /* peer unit pointer */
2075 struct refclockproc *pp;
2076 struct wwvunit *up;
2077 l_fp offset; /* offset in NTP seconds */
2079 pp = peer->procptr;
2080 up = (struct wwvunit *)pp->unitptr;
2081 if (!(up->status & SSYNC))
2082 up->alarm |= SYNERR;
2083 if (up->digcnt < 9)
2084 up->alarm |= NINERR;
2085 if (!(up->alarm))
2086 up->status |= INSYNC;
2087 if (up->status & INSYNC && up->status & SSYNC) {
2088 if (up->misc & SECWAR)
2089 pp->leap = LEAP_ADDSECOND;
2090 else
2091 pp->leap = LEAP_NOWARNING;
2092 pp->second = up->rsec;
2093 pp->minute = up->decvec[MN].digit + up->decvec[MN +
2094 1].digit * 10;
2095 pp->hour = up->decvec[HR].digit + up->decvec[HR +
2096 1].digit * 10;
2097 pp->day = up->decvec[DA].digit + up->decvec[DA +
2098 1].digit * 10 + up->decvec[DA + 2].digit * 100;
2099 pp->year = up->decvec[YR].digit + up->decvec[YR +
2100 1].digit * 10;
2101 pp->year += 2000;
2102 L_CLR(&offset);
2103 if (!clocktime(pp->day, pp->hour, pp->minute,
2104 pp->second, GMT, up->timestamp.l_ui,
2105 &pp->yearstart, &offset.l_ui)) {
2106 up->errflg = CEVNT_BADTIME;
2107 } else {
2108 up->watch = 0;
2109 pp->disp = 0;
2110 pp->lastref = up->timestamp;
2111 refclock_process_offset(pp, offset,
2112 up->timestamp, PDELAY);
2113 refclock_receive(peer);
2116 pp->lencode = timecode(up, pp->a_lastcode);
2117 record_clock_stats(&peer->srcadr, pp->a_lastcode);
2118 #ifdef DEBUG
2119 if (debug)
2120 printf("wwv: timecode %d %s\n", pp->lencode,
2121 pp->a_lastcode);
2122 #endif /* DEBUG */
2127 * wwv_corr4 - determine maximum likelihood digit
2129 * This routine correlates the received digit vector with the BCD
2130 * coefficient vectors corresponding to all valid digits at the given
2131 * position in the decoding matrix. The maximum value corresponds to the
2132 * maximum likelihood digit, while the ratio of this value to the next
2133 * lower value determines the likelihood function. Note that, if the
2134 * digit is invalid, the likelihood vector is averaged toward a miss.
2136 static void
2137 wwv_corr4(
2138 struct peer *peer, /* peer unit pointer */
2139 struct decvec *vp, /* decoding table pointer */
2140 double data[], /* received data vector */
2141 double tab[][4] /* correlation vector array */
2144 struct refclockproc *pp;
2145 struct wwvunit *up;
2146 double topmax, nxtmax; /* metrics */
2147 double acc; /* accumulator */
2148 char tbuf[80]; /* monitor buffer */
2149 int mldigit; /* max likelihood digit */
2150 int i, j;
2152 pp = peer->procptr;
2153 up = (struct wwvunit *)pp->unitptr;
2156 * Correlate digit vector with each BCD coefficient vector. If
2157 * any BCD digit bit is bad, consider all bits a miss. Until the
2158 * minute units digit has been resolved, don't to anything else.
2159 * Note the SNR is calculated as the ratio of the largest
2160 * likelihood value to the next largest likelihood value.
2162 mldigit = 0;
2163 topmax = nxtmax = -MAXAMP;
2164 for (i = 0; tab[i][0] != 0; i++) {
2165 acc = 0;
2166 for (j = 0; j < 4; j++)
2167 acc += data[j] * tab[i][j];
2168 acc = (vp->like[i] += (acc - vp->like[i]) / TCONST);
2169 if (acc > topmax) {
2170 nxtmax = topmax;
2171 topmax = acc;
2172 mldigit = i;
2173 } else if (acc > nxtmax) {
2174 nxtmax = acc;
2177 vp->digprb = topmax;
2178 vp->digsnr = wwv_snr(topmax, nxtmax);
2181 * The current maximum likelihood digit is compared to the last
2182 * maximum likelihood digit. If different, the compare counter
2183 * and maximum likelihood digit are reset. When the compare
2184 * counter reaches the BCMP threshold (3), the digit is assumed
2185 * correct. When the compare counter of all nine digits have
2186 * reached threshold, the clock is assumed correct.
2188 * Note that the clock display digit is set before the compare
2189 * counter has reached threshold; however, the clock display is
2190 * not considered correct until all nine clock digits have
2191 * reached threshold. This is intended as eye candy, but avoids
2192 * mistakes when the signal is low and the SNR is very marginal.
2193 * once correctly set, the maximum likelihood digit is ignored
2194 * on the assumption the clock will always be correct unless for
2195 * some reason it drifts to a different second.
2197 vp->mldigit = mldigit;
2198 if (vp->digprb < BTHR || vp->digsnr < BSNR) {
2199 vp->count = 0;
2200 up->status |= BGATE;
2201 } else {
2202 up->status |= DSYNC;
2203 if (vp->digit != mldigit) {
2204 vp->count = 0;
2205 up->alarm |= CMPERR;
2206 if (!(up->status & INSYNC))
2207 vp->digit = mldigit;
2208 } else {
2209 if (vp->count < BCMP)
2210 vp->count++;
2211 else
2212 up->digcnt++;
2215 if ((pp->sloppyclockflag & CLK_FLAG4) && !(up->status &
2216 INSYNC)) {
2217 sprintf(tbuf,
2218 "wwv4 %2d %04x %3d %4d %5.0f %2d %d %d %d %5.0f %5.1f",
2219 up->rsec - 1, up->status, up->gain, up->yepoch,
2220 up->epomax, vp->radix, vp->digit, vp->mldigit,
2221 vp->count, vp->digprb, vp->digsnr);
2222 record_clock_stats(&peer->srcadr, tbuf);
2223 #ifdef DEBUG
2224 if (debug)
2225 printf("%s\n", tbuf);
2226 #endif /* DEBUG */
2232 * wwv_tsec - transmitter minute processing
2234 * This routine is called at the end of the transmitter minute. It
2235 * implements a state machine that advances the logical clock subject to
2236 * the funny rules that govern the conventional clock and calendar.
2238 static void
2239 wwv_tsec(
2240 struct peer *peer /* driver structure pointer */
2243 struct refclockproc *pp;
2244 struct wwvunit *up;
2245 int minute, day, isleap;
2246 int temp;
2248 pp = peer->procptr;
2249 up = (struct wwvunit *)pp->unitptr;
2252 * Advance minute unit of the day. Don't propagate carries until
2253 * the unit minute digit has been found.
2255 temp = carry(&up->decvec[MN]); /* minute units */
2256 if (!(up->status & DSYNC))
2257 return;
2260 * Propagate carries through the day.
2262 if (temp == 0) /* carry minutes */
2263 temp = carry(&up->decvec[MN + 1]);
2264 if (temp == 0) /* carry hours */
2265 temp = carry(&up->decvec[HR]);
2266 if (temp == 0)
2267 temp = carry(&up->decvec[HR + 1]);
2270 * Decode the current minute and day. Set leap day if the
2271 * timecode leap bit is set on 30 June or 31 December. Set leap
2272 * minute if the last minute on leap day, but only if the clock
2273 * is syncrhronized. This code fails in 2400 AD.
2275 minute = up->decvec[MN].digit + up->decvec[MN + 1].digit *
2276 10 + up->decvec[HR].digit * 60 + up->decvec[HR +
2277 1].digit * 600;
2278 day = up->decvec[DA].digit + up->decvec[DA + 1].digit * 10 +
2279 up->decvec[DA + 2].digit * 100;
2282 * Set the leap bit on the last minute of the leap day.
2284 isleap = up->decvec[YR].digit & 0x3;
2285 if (up->misc & SECWAR && up->status & INSYNC) {
2286 if ((day == (isleap ? 182 : 183) || day == (isleap ?
2287 365 : 366)) && minute == 1439)
2288 up->status |= LEPSEC;
2292 * Roll the day if this the first minute and propagate carries
2293 * through the year.
2295 if (minute != 1440)
2296 return;
2298 minute = 0;
2299 while (carry(&up->decvec[HR]) != 0); /* advance to minute 0 */
2300 while (carry(&up->decvec[HR + 1]) != 0);
2301 day++;
2302 temp = carry(&up->decvec[DA]); /* carry days */
2303 if (temp == 0)
2304 temp = carry(&up->decvec[DA + 1]);
2305 if (temp == 0)
2306 temp = carry(&up->decvec[DA + 2]);
2309 * Roll the year if this the first day and propagate carries
2310 * through the century.
2312 if (day != (isleap ? 365 : 366))
2313 return;
2315 day = 1;
2316 while (carry(&up->decvec[DA]) != 1); /* advance to day 1 */
2317 while (carry(&up->decvec[DA + 1]) != 0);
2318 while (carry(&up->decvec[DA + 2]) != 0);
2319 temp = carry(&up->decvec[YR]); /* carry years */
2320 if (temp == 0)
2321 carry(&up->decvec[YR + 1]);
2326 * carry - process digit
2328 * This routine rotates a likelihood vector one position and increments
2329 * the clock digit modulo the radix. It returns the new clock digit or
2330 * zero if a carry occurred. Once synchronized, the clock digit will
2331 * match the maximum likelihood digit corresponding to that position.
2333 static int
2334 carry(
2335 struct decvec *dp /* decoding table pointer */
2338 int temp;
2339 int j;
2341 dp->digit++;
2342 if (dp->digit == dp->radix)
2343 dp->digit = 0;
2344 temp = dp->like[dp->radix - 1];
2345 for (j = dp->radix - 1; j > 0; j--)
2346 dp->like[j] = dp->like[j - 1];
2347 dp->like[0] = temp;
2348 return (dp->digit);
2353 * wwv_snr - compute SNR or likelihood function
2355 static double
2356 wwv_snr(
2357 double signal, /* signal */
2358 double noise /* noise */
2361 double rval;
2364 * This is a little tricky. Due to the way things are measured,
2365 * either or both the signal or noise amplitude can be negative
2366 * or zero. The intent is that, if the signal is negative or
2367 * zero, the SNR must always be zero. This can happen with the
2368 * subcarrier SNR before the phase has been aligned. On the
2369 * other hand, in the likelihood function the "noise" is the
2370 * next maximum down from the peak and this could be negative.
2371 * However, in this case the SNR is truly stupendous, so we
2372 * simply cap at MAXSNR dB (40).
2374 if (signal <= 0) {
2375 rval = 0;
2376 } else if (noise <= 0) {
2377 rval = MAXSNR;
2378 } else {
2379 rval = 20. * log10(signal / noise);
2380 if (rval > MAXSNR)
2381 rval = MAXSNR;
2383 return (rval);
2388 * wwv_newchan - change to new data channel
2390 * The radio actually appears to have ten channels, one channel for each
2391 * of five frequencies and each of two stations (WWV and WWVH), although
2392 * if not tunable only the DCHAN channel appears live. While the radio
2393 * is tuned to the working data channel frequency and station for most
2394 * of the minute, during seconds 59, 0 and 1 the radio is tuned to a
2395 * probe frequency in order to search for minute sync pulse and data
2396 * subcarrier from other transmitters.
2398 * The search for WWV and WWVH operates simultaneously, with WWV minute
2399 * sync pulse at 1000 Hz and WWVH at 1200 Hz. The probe frequency
2400 * rotates each minute over 2.5, 5, 10, 15 and 20 MHz in order and yes,
2401 * we all know WWVH is dark on 20 MHz, but few remember when WWV was lit
2402 * on 25 MHz.
2404 * This routine selects the best channel using a metric computed from
2405 * the reachability register and minute pulse amplitude. Normally, the
2406 * award goes to the the channel with the highest metric; but, in case
2407 * of ties, the award goes to the channel with the highest minute sync
2408 * pulse amplitude and then to the highest frequency.
2410 * The routine performs an important squelch function to keep dirty data
2411 * from polluting the integrators. In order to consider a station valid,
2412 * the metric must be at least MTHR (13); otherwise, the station select
2413 * bits are cleared so the second sync is disabled and the data bit
2414 * integrators averaged to a miss.
2416 static int
2417 wwv_newchan(
2418 struct peer *peer /* peer structure pointer */
2421 struct refclockproc *pp;
2422 struct wwvunit *up;
2423 struct sync *sp, *rp;
2424 double rank, dtemp;
2425 int i, j;
2427 pp = peer->procptr;
2428 up = (struct wwvunit *)pp->unitptr;
2431 * Search all five station pairs looking for the channel with
2432 * maximum metric. If no station is found above thresholds, tune
2433 * to WWV on 15 MHz, set the reference ID to NONE and wait for
2434 * hotter ions.
2436 sp = NULL;
2437 j = 0;
2438 rank = 0;
2439 for (i = 0; i < NCHAN; i++) {
2440 rp = &up->mitig[i].wwvh;
2441 dtemp = rp->metric;
2442 if (dtemp >= rank) {
2443 rank = dtemp;
2444 sp = rp;
2445 j = i;
2447 rp = &up->mitig[i].wwv;
2448 dtemp = rp->metric;
2449 if (dtemp >= rank) {
2450 rank = dtemp;
2451 sp = rp;
2452 j = i;
2457 * If the strongest signal is less than the MTHR threshold (13),
2458 * we are beneath the waves, so squelch the second sync. If the
2459 * strongest signal is greater than the threshold, tune to that
2460 * frequency and transmitter QTH.
2462 if (rank < MTHR) {
2463 up->dchan = (up->dchan + 1) % NCHAN;
2464 up->status &= ~(SELV | SELH);
2465 return (FALSE);
2467 up->dchan = j;
2468 up->status |= SELV | SELH;
2469 up->sptr = sp;
2470 memcpy(&pp->refid, sp->refid, 4);
2471 peer->refid = pp->refid;
2472 return (TRUE);
2477 * wwv_newgame - reset and start over
2479 * There are four conditions resulting in a new game:
2481 * 1 During initial acquisition (MSYNC dark) going 6 minutes (ACQSN)
2482 * without reliably finding the minute pulse (MSYNC lit).
2484 * 2 After finding the minute pulse (MSYNC lit), going 15 minutes
2485 * (DATA) without finding the unit seconds digit.
2487 * 3 After finding good data (DATA lit), going more than 40 minutes
2488 * (SYNCH) without finding station sync (INSYNC lit).
2490 * 4 After finding station sync (INSYNC lit), going more than 2 days
2491 * (PANIC) without finding any station.
2493 static void
2494 wwv_newgame(
2495 struct peer *peer /* peer structure pointer */
2498 struct refclockproc *pp;
2499 struct wwvunit *up;
2500 struct chan *cp;
2501 int i;
2503 pp = peer->procptr;
2504 up = (struct wwvunit *)pp->unitptr;
2507 * Initialize strategic values. Note we set the leap bits
2508 * NOTINSYNC and the refid "NONE".
2510 peer->leap = LEAP_NOTINSYNC;
2511 up->watch = up->status = up->alarm = 0;
2512 up->avgint = MINAVG;
2513 up->freq = 0;
2514 up->gain = MAXGAIN / 2;
2517 * Initialize the station processes for audio gain, select bit,
2518 * station/frequency identifier and reference identifier. Start
2519 * probing at the next channel after the data channel.
2521 memset(up->mitig, 0, sizeof(up->mitig));
2522 for (i = 0; i < NCHAN; i++) {
2523 cp = &up->mitig[i];
2524 cp->gain = up->gain;
2525 cp->wwv.select = SELV;
2526 sprintf(cp->wwv.refid, "WV%.0f", floor(qsy[i]));
2527 cp->wwvh.select = SELH;
2528 sprintf(cp->wwvh.refid, "WH%.0f", floor(qsy[i]));
2530 up->dchan = (DCHAN + NCHAN - 1) % NCHAN;;
2531 wwv_newchan(peer);
2532 up->achan = up->schan = up->dchan;
2533 #ifdef ICOM
2534 if (up->fd_icom > 0)
2535 wwv_qsy(peer, up->dchan);
2536 #endif /* ICOM */
2540 * wwv_metric - compute station metric
2542 * The most significant bits represent the number of ones in the
2543 * station reachability register. The least significant bits represent
2544 * the minute sync pulse amplitude. The combined value is scaled 0-100.
2546 double
2547 wwv_metric(
2548 struct sync *sp /* station pointer */
2551 double dtemp;
2553 dtemp = sp->count * MAXAMP;
2554 if (sp->synmax < MAXAMP)
2555 dtemp += sp->synmax;
2556 else
2557 dtemp += MAXAMP - 1;
2558 dtemp /= (AMAX + 1) * MAXAMP;
2559 return (dtemp * 100.);
2563 #ifdef ICOM
2565 * wwv_qsy - Tune ICOM receiver
2567 * This routine saves the AGC for the current channel, switches to a new
2568 * channel and restores the AGC for that channel. If a tunable receiver
2569 * is not available, just fake it.
2571 static int
2572 wwv_qsy(
2573 struct peer *peer, /* peer structure pointer */
2574 int chan /* channel */
2577 int rval = 0;
2578 struct refclockproc *pp;
2579 struct wwvunit *up;
2581 pp = peer->procptr;
2582 up = (struct wwvunit *)pp->unitptr;
2583 if (up->fd_icom > 0) {
2584 up->mitig[up->achan].gain = up->gain;
2585 rval = icom_freq(up->fd_icom, peer->ttl & 0x7f,
2586 qsy[chan]);
2587 up->achan = chan;
2588 up->gain = up->mitig[up->achan].gain;
2590 return (rval);
2592 #endif /* ICOM */
2596 * timecode - assemble timecode string and length
2598 * Prettytime format - similar to Spectracom
2600 * sq yy ddd hh:mm:ss ld dut lset agc iden sig errs freq avgt
2602 * s sync indicator ('?' or ' ')
2603 * q error bits (hex 0-F)
2604 * yyyy year of century
2605 * ddd day of year
2606 * hh hour of day
2607 * mm minute of hour
2608 * ss second of minute)
2609 * l leap second warning (' ' or 'L')
2610 * d DST state ('S', 'D', 'I', or 'O')
2611 * dut DUT sign and magnitude (0.1 s)
2612 * lset minutes since last clock update
2613 * agc audio gain (0-255)
2614 * iden reference identifier (station and frequency)
2615 * sig signal quality (0-100)
2616 * errs bit errors in last minute
2617 * freq frequency offset (PPM)
2618 * avgt averaging time (s)
2620 static int
2621 timecode(
2622 struct wwvunit *up, /* driver structure pointer */
2623 char *ptr /* target string */
2626 struct sync *sp;
2627 int year, day, hour, minute, second, dut;
2628 char synchar, leapchar, dst;
2629 char cptr[50];
2633 * Common fixed-format fields
2635 synchar = (up->status & INSYNC) ? ' ' : '?';
2636 year = up->decvec[YR].digit + up->decvec[YR + 1].digit * 10 +
2637 2000;
2638 day = up->decvec[DA].digit + up->decvec[DA + 1].digit * 10 +
2639 up->decvec[DA + 2].digit * 100;
2640 hour = up->decvec[HR].digit + up->decvec[HR + 1].digit * 10;
2641 minute = up->decvec[MN].digit + up->decvec[MN + 1].digit * 10;
2642 second = 0;
2643 leapchar = (up->misc & SECWAR) ? 'L' : ' ';
2644 dst = dstcod[(up->misc >> 4) & 0x3];
2645 dut = up->misc & 0x7;
2646 if (!(up->misc & DUTS))
2647 dut = -dut;
2648 sprintf(ptr, "%c%1X", synchar, up->alarm);
2649 sprintf(cptr, " %4d %03d %02d:%02d:%02d %c%c %+d",
2650 year, day, hour, minute, second, leapchar, dst, dut);
2651 strcat(ptr, cptr);
2654 * Specific variable-format fields
2656 sp = up->sptr;
2657 sprintf(cptr, " %d %d %s %.0f %d %.1f %d", up->watch,
2658 up->mitig[up->dchan].gain, sp->refid, sp->metric,
2659 up->errcnt, up->freq / SECOND * 1e6, up->avgint);
2660 strcat(ptr, cptr);
2661 return (strlen(ptr));
2666 * wwv_gain - adjust codec gain
2668 * This routine is called at the end of each second. During the second
2669 * the number of signal clips above the MAXAMP threshold (6000). If
2670 * there are no clips, the gain is bumped up; if there are more than
2671 * MAXCLP clips (100), it is bumped down. The decoder is relatively
2672 * insensitive to amplitude, so this crudity works just peachy. The
2673 * input port is set and the error flag is cleared, mostly to be ornery.
2675 static void
2676 wwv_gain(
2677 struct peer *peer /* peer structure pointer */
2680 struct refclockproc *pp;
2681 struct wwvunit *up;
2683 pp = peer->procptr;
2684 up = (struct wwvunit *)pp->unitptr;
2687 * Apparently, the codec uses only the high order bits of the
2688 * gain control field. Thus, it may take awhile for changes to
2689 * wiggle the hardware bits.
2691 if (up->clipcnt == 0) {
2692 up->gain += 4;
2693 if (up->gain > MAXGAIN)
2694 up->gain = MAXGAIN;
2695 } else if (up->clipcnt > MAXCLP) {
2696 up->gain -= 4;
2697 if (up->gain < 0)
2698 up->gain = 0;
2700 audio_gain(up->gain, up->mongain, up->port);
2701 up->clipcnt = 0;
2702 #if DEBUG
2703 if (debug > 1)
2704 audio_show();
2705 #endif
2709 #else
2710 int refclock_wwv_bs;
2711 #endif /* REFCLOCK */